From e4cc3002cab7b1b12c0319a190431f66021d24a0 Mon Sep 17 00:00:00 2001 From: Brad Anderson Date: Mon, 26 Oct 2026 10:51:37 -0400 Subject: [PATCH 1/8] fix: remove deprecated OpenSSL APIs from bundled ncrypto Track a reduced ncrypto snapshot and use provider encoders for traditional key exports. Preserve prime-check assurance and fix private DER import routing exposed by regression coverage. Fixes #1081 --- .github/workflows/validate-cpp.yml | 36 +- .gitmodules | 3 - example/src/tests/keys/create_keys.ts | 178 +- example/src/tests/keys/fixtures.ts | 30 + packages/react-native-quick-crypto/.gitignore | 1 + .../QuickCrypto.podspec | 3 +- .../android/CMakeLists.txt | 1 - .../cpp/keys/KeyObjectData.cpp | 14 +- .../react-native-quick-crypto/deps/ncrypto | 1 - .../deps/ncrypto/LICENSE | 21 + .../deps/ncrypto/README.md | 23 + .../deps/ncrypto/include/ncrypto.h | 1259 ++++++ .../deps/ncrypto/include/ncrypto/aead.h | 136 + .../deps/ncrypto/include/ncrypto/version.h | 14 + .../deps/ncrypto/src/aead.cpp | 249 ++ .../deps/ncrypto/src/ncrypto.cpp | 3809 +++++++++++++++++ .../react-native-quick-crypto/package.json | 2 +- .../src/keys/index.ts | 2 + scripts/check-ncrypto-openssl-deprecations.sh | 86 + 19 files changed, 5854 insertions(+), 14 deletions(-) delete mode 160000 packages/react-native-quick-crypto/deps/ncrypto create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/LICENSE create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/README.md create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp create mode 100644 packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp create mode 100755 scripts/check-ncrypto-openssl-deprecations.sh diff --git a/.github/workflows/validate-cpp.yml b/.github/workflows/validate-cpp.yml index 313186991..25a2f530b 100644 --- a/.github/workflows/validate-cpp.yml +++ b/.github/workflows/validate-cpp.yml @@ -8,13 +8,17 @@ on: - '.github/workflows/validate-cpp.yml' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' + - 'scripts/check-ncrypto-openssl-deprecations.sh' pull_request: paths: - '.github/workflows/validate-cpp.yml' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' + - 'scripts/check-ncrypto-openssl-deprecations.sh' env: # Opt actions still on Node 20 (e.g. reviewdog/action-cpplint) into the runner's Node 24. @@ -34,13 +38,39 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - - name: Set up clang-format - run: sudo apt-get install -y clang-format + - name: Set up native validation + run: sudo apt-get install -y build-essential clang-format perl pkg-config + - name: Build OpenSSL 3.6.2 + env: + OPENSSL_VERSION: 3.6.2 + OPENSSL_SHA256: aaf51a1fe064384f811daeaeb4ec4dce7340ec8bd893027eee676af31e83a04f + run: | + openssl_archive="openssl-${OPENSSL_VERSION}.tar.gz" + curl --fail --location --silent --show-error \ + --output "$RUNNER_TEMP/$openssl_archive" \ + "https://github.com/openssl/openssl/releases/download/openssl-${OPENSSL_VERSION}/$openssl_archive" + echo "$OPENSSL_SHA256 $RUNNER_TEMP/$openssl_archive" | sha256sum --check + tar --extract --gzip --file "$RUNNER_TEMP/$openssl_archive" --directory "$RUNNER_TEMP" + cd "$RUNNER_TEMP/openssl-${OPENSSL_VERSION}" + ./Configure \ + --prefix="$RUNNER_TEMP/openssl" \ + --openssldir="$RUNNER_TEMP/openssl/ssl" \ + --libdir=lib \ + no-shared \ + no-tests + make --jobs="$(nproc)" + make install_sw + echo "OPENSSL_ROOT_DIR=$RUNNER_TEMP/openssl" >> "$GITHUB_ENV" - name: Run clang-format check run: | - find packages/react-native-quick-crypto/cpp packages/react-native-quick-crypto/android/src/main/cpp \ + find packages/react-native-quick-crypto/cpp \ + packages/react-native-quick-crypto/android/src/main/cpp \ + packages/react-native-quick-crypto/deps/ncrypto/include \ + packages/react-native-quick-crypto/deps/ncrypto/src \ -regex '.*\.\(cpp\|hpp\|cc\|cxx\|h\)' \ -exec clang-format --style=file --dry-run --Werror {} + + - name: Reject ncrypto OpenSSL deprecations + run: scripts/check-ncrypto-openssl-deprecations.sh - uses: reviewdog/action-cpplint@9552c62f4bd516c1e3a6f84eae56bd864cc304c6 # v1.11.0 with: github_token: ${{ secrets.github_token }} diff --git a/.gitmodules b/.gitmodules index 5e87fa645..24b8ba494 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "packages/react-native-quick-crypto/deps/blake3"] path = packages/react-native-quick-crypto/deps/blake3 url = https://github.com/BLAKE3-team/BLAKE3.git -[submodule "packages/react-native-quick-crypto/deps/ncrypto"] - path = packages/react-native-quick-crypto/deps/ncrypto - url = https://github.com/nodejs/ncrypto.git [submodule "packages/react-native-quick-crypto/deps/simdutf"] path = packages/react-native-quick-crypto/deps/simdutf url = https://github.com/simdutf/simdutf.git diff --git a/example/src/tests/keys/create_keys.ts b/example/src/tests/keys/create_keys.ts index 838f9d569..d44f033ae 100644 --- a/example/src/tests/keys/create_keys.ts +++ b/example/src/tests/keys/create_keys.ts @@ -11,7 +11,11 @@ import { import type { JWK, KeyObject } from 'react-native-quick-crypto'; import { expect } from 'chai'; import { test, assertThrowsAsync, decodeHex } from '../util'; -import { rsaPrivateKeyPem, rsaPublicKeyPem } from './fixtures'; +import { + rsaPrivateKeyPem, + rsaPssPrivateKeyPem, + rsaPublicKeyPem, +} from './fixtures'; const SUITE = 'keys.createKey'; @@ -358,6 +362,24 @@ async function generateRsaKeyPair(): Promise<{ }); } +async function generateEcKeyPair(): Promise<{ + privateKey: KeyObject; + publicKey: KeyObject; +}> { + return new Promise((resolve, reject) => { + generateKeyPair('ec', { namedCurve: 'P-256' }, (err, pubKey, privKey) => { + if (err) { + reject(err); + return; + } + resolve({ + privateKey: privKey as KeyObject, + publicKey: pubKey as KeyObject, + }); + }); + }); +} + test(SUITE, 'createPrivateKey with passphrase (PEM, PKCS8)', async () => { const { privateKey, publicKey } = await generateRsaKeyPair(); const passphrase = 'user-test'; @@ -414,6 +436,160 @@ test(SUITE, 'createPrivateKey passphrase as Buffer (PEM)', async () => { expect(imported.equals(privateKey)).to.equal(true); }); +test(SUITE, 'RSA PKCS1 private key PEM and DER round-trip', () => { + const privateKey = createPrivateKey(rsaPrivateKeyPem); + const publicKey = createPublicKey(privateKey); + const pem = privateKey.export({ format: 'pem', type: 'pkcs1' }) as string; + const der = privateKey.export({ format: 'der', type: 'pkcs1' }) as Buffer; + + expect(pem).to.match(/^-----BEGIN RSA PRIVATE KEY-----/); + expect(createPrivateKey(pem).equals(privateKey)).to.equal(true); + expect( + createPrivateKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + privateKey, + ), + ).to.equal(true); + expect(() => + createPublicKey({ + key: Buffer.from([0x30, 0x00]), + format: 'der', + type: 'pkcs1', + }), + ).to.throw(); + expect( + createPublicKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + publicKey, + ), + ).to.equal(true); +}); + +test(SUITE, 'RSA PKCS1 public-only key PEM and DER round-trip', () => { + const publicKey = createPublicKey(rsaPublicKeyPem); + const pem = publicKey.export({ format: 'pem', type: 'pkcs1' }) as string; + const der = publicKey.export({ format: 'der', type: 'pkcs1' }) as Buffer; + + expect(pem).to.match(/^-----BEGIN RSA PUBLIC KEY-----/); + expect(createPublicKey(pem).equals(publicKey)).to.equal(true); + expect( + createPublicKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + publicKey, + ), + ).to.equal(true); +}); + +test( + SUITE, + 'RSA PKCS1 encrypted PEM accepts binary and empty passphrases', + () => { + const privateKey = createPrivateKey(rsaPrivateKeyPem); + const passphrases = [ + Buffer.from([0x61, 0x00, 0xff, 0x62]), + Buffer.alloc(0), + ]; + + for (const passphrase of passphrases) { + const pem = privateKey.export({ + format: 'pem', + type: 'pkcs1', + cipher: 'aes-256-cbc', + passphrase, + }) as string; + + expect(pem).to.include('Proc-Type: 4,ENCRYPTED'); + expect( + createPrivateKey({ key: pem, passphrase }).equals(privateKey), + ).to.equal(true); + + if (passphrase.length > 0) { + expect(() => createPrivateKey(pem)).to.throw('Passphrase required'); + expect(() => + createPrivateKey({ key: pem, passphrase: 'wrong' }), + ).to.throw('Failed to read'); + } + } + }, +); + +test(SUITE, 'EC SEC1 private key PEM and DER round-trip', async () => { + const { privateKey, publicKey } = await generateEcKeyPair(); + const pem = privateKey.export({ format: 'pem', type: 'sec1' }) as string; + const der = privateKey.export({ format: 'der', type: 'sec1' }) as Buffer; + const reimported = createPrivateKey({ + key: der, + format: 'der', + type: 'sec1', + }); + + expect(pem).to.match(/^-----BEGIN EC PRIVATE KEY-----/); + expect(createPrivateKey(pem).equals(privateKey)).to.equal(true); + expect(reimported.equals(privateKey)).to.equal(true); + expect(() => + createPublicKey({ + key: Buffer.from([0x30, 0x00]), + format: 'der', + type: 'sec1', + }), + ).to.throw(); + const reimportedPublic = createPublicKey({ + key: der, + format: 'der', + type: 'sec1', + }); + + for (const type of ['compressed', 'uncompressed'] as const) { + const originalPoint = publicKey.export({ + format: 'raw-public', + type, + }) as Buffer; + const reimportedPoint = reimportedPublic.export({ + format: 'raw-public', + type, + }); + expect(Buffer.compare(reimportedPoint, originalPoint)).to.equal(0); + } +}); + +test( + SUITE, + 'EC SEC1 encrypted PEM accepts binary and empty passphrases', + async () => { + const { privateKey } = await generateEcKeyPair(); + const passphrases = [ + Buffer.from([0x61, 0x00, 0xff, 0x62]), + Buffer.alloc(0), + ]; + + for (const passphrase of passphrases) { + const pem = privateKey.export({ + format: 'pem', + type: 'sec1', + cipher: 'aes-256-cbc', + passphrase, + }) as string; + + expect(pem).to.include('Proc-Type: 4,ENCRYPTED'); + expect( + createPrivateKey({ key: pem, passphrase }).equals(privateKey), + ).to.equal(true); + } + }, +); + +test(SUITE, 'RSA-PSS rejects traditional PKCS1 export', () => { + const privateKey = createPrivateKey(rsaPssPrivateKeyPem); + const publicKey = createPublicKey(privateKey); + + expect(privateKey.asymmetricKeyType).to.equal('rsa-pss'); + expect(publicKey.asymmetricKeyType).to.equal('rsa-pss'); + + expect(() => privateKey.export({ format: 'pem', type: 'pkcs1' })).to.throw( + 'pkcs1 can only be used for RSA keys', + ); + expect(() => publicKey.export({ format: 'pem', type: 'pkcs1' })).to.throw( + 'pkcs1 can only be used for RSA keys', + ); +}); + test( SUITE, 'createPrivateKey on encrypted PEM without passphrase throws Passphrase required', diff --git a/example/src/tests/keys/fixtures.ts b/example/src/tests/keys/fixtures.ts index 03232fb8c..c3ab0c393 100644 --- a/example/src/tests/keys/fixtures.ts +++ b/example/src/tests/keys/fixtures.ts @@ -37,3 +37,33 @@ xK2Nlm+ofI61tXO31YSXSd0cyw1v8xd0wJLJbtSg5X4jS9t79gLUeVSgOQses/t9 4vfFwn1MwYqQ252xNcMOamV1Q7qM7OYqJrUOxJ0OUQnqCZKF5PxjpSuOl9whzUOh owIDAQAB -----END PUBLIC KEY-----`; + +// Source: Node.js test/fixtures/keys/rsa_pss_private_2048.pem +export const rsaPssPrivateKeyPem = `-----BEGIN PRIVATE KEY----- +MIIEvAIBADALBgkqhkiG9w0BAQoEggSoMIIEpAIBAAKCAQEAy4OMdS84PlgI5CRL +bdbud9Ru7vprFr2YNNUmdT7D3YgApiv8CjzKXLiVDnbMET+lwmtag/EcZsxVCKov +su30pYASBriHOiMVYui9+ZaJoQ9yI6lOjG1RbuUBJXNSjHBJxqBqmcgZOb1mdRr/ +eXzpAMWJ3hfuLojU2+zUSJ3/rvepepcLFG2q9nA0+PJskJ7Pnh3L0ydnv3U3hduM +n5OVfm/Jx1FPyZpD184tJff+N+MY3s3hIcfuOnL9Pl4RPGeaTC4T1o460NaG6bG7 +c2Whg6NOaVgaFIaiNbrTTNCpVjeTyalsTXYlQQ3hiKjst0Q7pfFEkJDo8qiqLad1 +Msl59wIDAQABAoIBAQC6G8aqs0/f02nuGDLSc6cH9kCsUlz0ItW6GuJcfdVoFSNi +0v5d7lGwkSveWk0ryOSw8rOHzUqHx3xLvDZ6jpkXcBMMClu/kq3QEb8JK90YaKOc +cQvf52h83Pc7ZEatH1KYTcKudwp6fvXfSZ0vYEdD6WG2tHOgIollxSIsdjCHs1qi +7baNHdK9T4DveuEZNcZ+LraZ1haHmFeqIPcy+KvpGuTaLCg5FPhH2jsIkw9apr7i +iFLi+IJ7S5Bn/8XShmJWk4hPyx0jtIkC5r2iJnHf4x+XYWZfdo7oew3Dg6Pa7T6r +I164Nnaw0u0LvO4gQdvYaJ/j9A602nHTp7Tsq8chAoGBAOtVHgIqpmdzwR5KjotW +LuGXDdO9X6Xfge9ca2MlWH1jOj+zqEV7JtrjnZAzzOgP2kgqzpIR71Njs8wkaxTJ +Tle0Ke6R/ghU9YOQgRByKjqJfQXHZnYFPsMg0diNYLroJ4SG8LO4+2SygTYZ4eKL +qU0bda3QvQ7FL+rTNQBy01b9AoGBAN1jEQI80JxCT7AMvXE6nObIhbkASHte4yOE +1CBwcOuBEGcuvMOvQVMzKITgea6+kgsu4ids4dM5PTPapQgpKqIIQ2/eSesaf56g +73clGGSTPHJP0v+EfKg4+GYJf8o2swT0xDHkgWLgjjdsncB9hATc2j6DvHeau18d +pgCLz9kDAoGAXl/SGvhTp2UqayVnKMW1I07agrGNLA4II5+iiS4u4InskCNSNhr/ +KATj6TJ82AuTdCGGmdmLapuvPQzVzI42VsGvlzcA8wJvOwW2XIwMF1GPy8N9eZL8 +6m+89+Uqh4oWXvVmjgx+9JEJdFLI3Xs4t+1tMfll+AhoAPoWZUmnK1kCgYAvEBxR +iXQfg8lE97BeHcO1G/OxfGnsMCPBLT+bFcwrhGhkRv9B6kPM2BdJCB9WEpUhY3oY +P4FSUdy85UIoFfhGMdOEOJEmNZ/jrPq7LVueJd63vlhwkU2exV2o82QDLNWpvA7p +PFZ1Gp+hEKoIfaZPElQi7gZmtrIWaksb2pz42QKBgQCct9NP2qJfqeS4206RDnfv +M238/O2lNhLWdSwY0g+tcN+I1sGs3+4vvrm95cxwAmXZyIM11wjdMcAPNxibodY7 +vufsebPHDBA0j0yuTjGkXefUKd1GdO88i5fppzxB7prDX9//DsWWrFhIMMRNYe0Q +aeHd/NPuHcjZKcnaVBgukQ== +-----END PRIVATE KEY-----`; diff --git a/packages/react-native-quick-crypto/.gitignore b/packages/react-native-quick-crypto/.gitignore index 253e0720a..5c6d040d7 100644 --- a/packages/react-native-quick-crypto/.gitignore +++ b/packages/react-native-quick-crypto/.gitignore @@ -1,5 +1,6 @@ # will be copied from root README.md README.md +!deps/ncrypto/README.md ios/** diff --git a/packages/react-native-quick-crypto/QuickCrypto.podspec b/packages/react-native-quick-crypto/QuickCrypto.podspec index 72abe7ee4..216afa2a1 100644 --- a/packages/react-native-quick-crypto/QuickCrypto.podspec +++ b/packages/react-native-quick-crypto/QuickCrypto.podspec @@ -130,7 +130,8 @@ Pod::Spec.new do |s| "cpp/**/*.{hpp,cpp}", # dependencies (C++) - ncrypto "deps/ncrypto/include/**/*.{h}", - "deps/ncrypto/src/*.{cpp}", + "deps/ncrypto/src/aead.cpp", + "deps/ncrypto/src/ncrypto.cpp", # dependencies (C++) - simdutf "deps/simdutf/include/**/*.{h}", "deps/simdutf/src/simdutf.cpp", diff --git a/packages/react-native-quick-crypto/android/CMakeLists.txt b/packages/react-native-quick-crypto/android/CMakeLists.txt index 2bb708e66..2ec7cdd7e 100644 --- a/packages/react-native-quick-crypto/android/CMakeLists.txt +++ b/packages/react-native-quick-crypto/android/CMakeLists.txt @@ -67,7 +67,6 @@ add_library( ${BLAKE3_SOURCES} ../deps/fastpbkdf2/fastpbkdf2.c ../deps/ncrypto/src/aead.cpp - ../deps/ncrypto/src/engine.cpp ../deps/ncrypto/src/ncrypto.cpp ../deps/simdutf/src/simdutf.cpp ) diff --git a/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp b/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp index 82147caeb..b34818ec5 100644 --- a/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp +++ b/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp @@ -181,20 +181,28 @@ KeyObjectData KeyObjectData::GetPublicOrPrivateKey(std::shared_ptr ERR_error_string_n(err, err_buf, sizeof(err_buf)); throw std::runtime_error("Failed to read PEM asymmetric key: " + std::string(err_buf)); } else if (actualFormat == KFormatType::DER) { - // For DER, try parsing as public key first - if (type.has_value() && type.value() == KeyEncoding::SPKI) { + // PKCS#1 DER can contain either an RSA public or private key. + if (type.has_value() && type.value() == KeyEncoding::PKCS1 && !ncrypto::EVPKeyPointer::IsRSAPrivateKey(buffer)) { auto public_config = GetPublicKeyEncodingConfig(actualFormat, type.value()); auto res = ncrypto::EVPKeyPointer::TryParsePublicKey(public_config, buffer); if (res) { return CreateAsymmetric(KeyType::PUBLIC, std::move(res.value)); } - } else if (type.has_value() && type.value() == KeyEncoding::PKCS8) { + } else if (type.has_value() && type.value() == KeyEncoding::SPKI) { + auto public_config = GetPublicKeyEncodingConfig(actualFormat, type.value()); + auto res = ncrypto::EVPKeyPointer::TryParsePublicKey(public_config, buffer); + if (res) { + return CreateAsymmetric(KeyType::PUBLIC, std::move(res.value)); + } + } else if (type.has_value() && + (type.value() == KeyEncoding::PKCS1 || type.value() == KeyEncoding::PKCS8 || type.value() == KeyEncoding::SEC1)) { auto private_config = GetPrivateKeyEncodingConfig(actualFormat, type.value()); if (passphrase.has_value()) { auto& passphrase_ptr = passphrase.value(); private_config.passphrase = std::make_optional(ncrypto::DataPointer::Copy(ncrypto::Buffer{passphrase_ptr->data(), passphrase_ptr->size()})); } + ERR_clear_error(); auto res = ncrypto::EVPKeyPointer::TryParsePrivateKey(private_config, buffer); if (res) { return CreateAsymmetric(KeyType::PRIVATE, std::move(res.value)); diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto deleted file mode 160000 index 027d1e44b..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 027d1e44bbded3e40549d8edb0887cd783de8e5d diff --git a/packages/react-native-quick-crypto/deps/ncrypto/LICENSE b/packages/react-native-quick-crypto/deps/ncrypto/LICENSE new file mode 100644 index 000000000..6da37b652 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Node.js + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/react-native-quick-crypto/deps/ncrypto/README.md b/packages/react-native-quick-crypto/deps/ncrypto/README.md new file mode 100644 index 000000000..f9db254f9 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/README.md @@ -0,0 +1,23 @@ +# RNQC ncrypto snapshot + +This directory is a reduced, directly tracked snapshot of `ncrypto` for React Native Quick Crypto. It is not a standalone fork or independently published package. + +## Provenance + +- Upstream repository: `https://github.com/nodejs/ncrypto` +- Base revision: `027d1e44bbded3e40549d8edb0887cd783de8e5d` (`v1.1.4`) +- License: MIT; see `LICENSE` + +## Retained surface + +- `include/ncrypto.h` +- `include/ncrypto/aead.h` +- `include/ncrypto/version.h` +- `src/ncrypto.cpp` +- `src/aead.cpp` + +RNQC retains EVP key parsing and export, X.509 and SPKAC helpers, ciphers, digests, KDF support including Argon2, AEAD helpers, and the other utilities used by its native consumers. + +## Deliberate reductions + +Upstream build systems, tests, tools, ENGINE support, and unused legacy DH, DSA, EC, HMAC, RSA, SSL, and X.509 wrapper surfaces are omitted. Traditional PKCS#1 and SEC1 export uses OpenSSL 3 provider encoders rather than deprecated low-level key APIs. Keep additions limited to APIs required by RNQC and verify retained translation units against OpenSSL deprecation warnings before updating this snapshot. diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h new file mode 100644 index 000000000..22133c7e6 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h @@ -0,0 +1,1259 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef OPENSSL_IS_BORINGSSL +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#if NCRYPTO_DEVELOPMENT_CHECKS +#include +#endif + +// The FIPS-related functions are only available +// when the OpenSSL itself was compiled with FIPS support. +#if defined(OPENSSL_FIPS) && OPENSSL_VERSION_MAJOR < 3 +#include +#endif // OPENSSL_FIPS + +// Define OPENSSL_WITH_PQC for post-quantum cryptography support +#if OPENSSL_VERSION_NUMBER >= 0x30500000L +#define OPENSSL_WITH_PQC 1 +#define EVP_PKEY_ML_KEM_512 NID_ML_KEM_512 +#define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768 +#define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024 +#endif + +#ifdef __GNUC__ +#define NCRYPTO_MUST_USE_RESULT __attribute__((warn_unused_result)) +#else +#define NCRYPTO_MUST_USE_RESULT +#endif + +#ifdef OPENSSL_IS_BORINGSSL +// Boringssl has opted to use size_t for some size related +// APIs while Openssl is still using ints +using OPENSSL_SIZE_T = size_t; +#else +using OPENSSL_SIZE_T = int; +#endif + +namespace ncrypto { + +// ============================================================================ +// Utility macros + +inline bool EqualNoCase(const std::string_view a, const std::string_view b) { + if (a.size() != b.size()) + return false; + return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); +} + +#if NCRYPTO_DEVELOPMENT_CHECKS +#define NCRYPTO_STR(x) #x +#define NCRYPTO_REQUIRE(EXPR) \ + { \ + if (!(EXPR)) { \ + abort(); \ + } \ + } + +#define NCRYPTO_FAIL(MESSAGE) \ + do { \ + std::cerr << "FAIL: " << (MESSAGE) << std::endl; \ + abort(); \ + } while (0); +#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) \ + do { \ + if (LHS != RHS) { \ + std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \ + NCRYPTO_FAIL(MESSAGE); \ + } \ + } while (0); +#define NCRYPTO_ASSERT_TRUE(COND) \ + do { \ + if (!(COND)) { \ + std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ << std::endl; \ + NCRYPTO_FAIL(NCRYPTO_STR(COND)); \ + } \ + } while (0); +#else +#define NCRYPTO_FAIL(MESSAGE) +#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) +#define NCRYPTO_ASSERT_TRUE(COND) +#endif + +#define NCRYPTO_DISALLOW_COPY(Name) \ + Name(const Name&) = delete; \ + Name& operator=(const Name&) = delete; +#define NCRYPTO_DISALLOW_MOVE(Name) \ + Name(Name&&) = delete; \ + Name& operator=(Name&&) = delete; +#define NCRYPTO_DISALLOW_COPY_AND_MOVE(Name) \ + NCRYPTO_DISALLOW_COPY(Name) \ + NCRYPTO_DISALLOW_MOVE(Name) +#define NCRYPTO_DISALLOW_NEW_DELETE() \ + void* operator new(size_t) = delete; \ + void operator delete(void*) = delete; + +[[noreturn]] inline void unreachable() { +#ifdef __GNUC__ + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(false); +#else +#endif +} + +static constexpr int kX509NameFlagsMultiline = + ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_MULTILINE | XN_FLAG_FN_SN; + +// ============================================================================ +// Error handling utilities + +// Capture the current OpenSSL Error Stack. The stack will be ordered such +// that the error currently at the top of the stack is at the end of the +// list and the error at the bottom of the stack is at the beginning. +class CryptoErrorList final { + public: + enum class Option { NONE, CAPTURE_ON_CONSTRUCT }; + CryptoErrorList(Option option = Option::CAPTURE_ON_CONSTRUCT); + + void capture(); + + // Add an error message to the end of the stack. + void add(std::string message); + + inline const std::string& peek_back() const { + return errors_.back(); + } + inline size_t size() const { + return errors_.size(); + } + inline bool empty() const { + return errors_.empty(); + } + + inline auto begin() const noexcept { + return errors_.begin(); + } + inline auto end() const noexcept { + return errors_.end(); + } + inline auto rbegin() const noexcept { + return errors_.rbegin(); + } + inline auto rend() const noexcept { + return errors_.rend(); + } + + std::optional pop_back(); + std::optional pop_front(); + + private: + std::list errors_; +}; + +// Forcibly clears the error stack on destruction. This stops stale errors +// from popping up later in the lifecycle of crypto operations where they +// would cause spurious failures. It is a rather blunt method, though, and +// ERR_clear_error() isn't necessarily cheap. +// +// If created with a pointer to a CryptoErrorList, the current OpenSSL error +// stack will be captured before clearing the error. +class ClearErrorOnReturn final { + public: + ClearErrorOnReturn(CryptoErrorList* errors = nullptr); + ~ClearErrorOnReturn(); + NCRYPTO_DISALLOW_COPY_AND_MOVE(ClearErrorOnReturn) + NCRYPTO_DISALLOW_NEW_DELETE() + + int peekError(); + + private: + CryptoErrorList* errors_; +}; + +// Pop errors from OpenSSL's error stack that were added between when this +// was constructed and destructed. +// +// If created with a pointer to a CryptoErrorList, the current OpenSSL error +// stack will be captured before resetting the error to the mark. +class MarkPopErrorOnReturn final { + public: + MarkPopErrorOnReturn(CryptoErrorList* errors = nullptr); + ~MarkPopErrorOnReturn(); + NCRYPTO_DISALLOW_COPY_AND_MOVE(MarkPopErrorOnReturn) + NCRYPTO_DISALLOW_NEW_DELETE() + + int peekError(); + + private: + CryptoErrorList* errors_; +}; + +// TODO(@jasnell): Eventually replace with std::expected when we are able to +// bump up to c++23. +template +struct Result final { + const bool has_value; + T value; + std::optional error = std::nullopt; + std::optional openssl_error = std::nullopt; + Result(T&& value) : has_value(true), value(std::move(value)) {} + Result(E&& error, std::optional openssl_error = std::nullopt) + : has_value(false), error(std::move(error)), openssl_error(std::move(openssl_error)) {} + inline operator bool() const { + return has_value; + } +}; + +// ============================================================================ +// Various smart pointer aliases for OpenSSL types. + +template +struct FunctionDeleter { + void operator()(T* pointer) const { + function(pointer); + } + typedef std::unique_ptr Pointer; +}; + +template +using DeleteFnPtr = typename FunctionDeleter::Pointer; + +using PKCS8Pointer = DeleteFnPtr; + +class BIOPointer; +class BignumPointer; +class CipherCtxPointer; +class DataPointer; +class EVPKeyPointer; +class EVPMacCtxPointer; +class EVPMacPointer; +class EVPMDCtxPointer; +class X509View; +class X509Pointer; +class ECDSASigPointer; + +struct StackOfXASN1Deleter { + void operator()(STACK_OF(ASN1_OBJECT) * p) const { + sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free); + } +}; +using StackOfASN1 = std::unique_ptr; + +// An unowned, unmanaged pointer to a buffer of data. +template +struct Buffer { + T* data = nullptr; + size_t len = 0; +}; + +class Digest final { + public: + static constexpr size_t MAX_SIZE = EVP_MAX_MD_SIZE; + Digest() = default; + Digest(const EVP_MD* md) : md_(md) {} + Digest(const Digest&) = default; + Digest& operator=(const Digest&) = default; + inline Digest& operator=(const EVP_MD* md) { + md_ = md; + return *this; + } + NCRYPTO_DISALLOW_MOVE(Digest) + + size_t size() const; + + inline const EVP_MD* get() const { + return md_; + } + inline operator const EVP_MD*() const { + return md_; + } + inline operator bool() const { + return md_ != nullptr; + } + + static const Digest MD5; + static const Digest SHA1; + static const Digest SHA256; + static const Digest SHA384; + static const Digest SHA512; + + static const Digest FromName(const char* name); + + private: + const EVP_MD* md_ = nullptr; +}; + +// Computes a fixed-length digest. +DataPointer hashDigest(const Buffer& data, const EVP_MD* md); +// Computes a variable-length digest for XOF algorithms (e.g. SHAKE128). +DataPointer xofHashDigest(const Buffer& data, const EVP_MD* md, size_t length); + +class Cipher final { + public: + static constexpr size_t MAX_KEY_LENGTH = EVP_MAX_KEY_LENGTH; + static constexpr size_t MAX_IV_LENGTH = EVP_MAX_IV_LENGTH; +#ifdef EVP_MAX_AEAD_TAG_LENGTH + static constexpr size_t MAX_AUTH_TAG_LENGTH = EVP_MAX_AEAD_TAG_LENGTH; +#else + static constexpr size_t MAX_AUTH_TAG_LENGTH = 16; +#endif + static_assert(EVP_GCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH +#ifndef OPENSSL_IS_BORINGSSL + && EVP_CCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH && EVP_CHACHAPOLY_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH +#endif + ); + + Cipher() = default; + Cipher(const EVP_CIPHER* cipher) : cipher_(cipher) {} + Cipher(const Cipher&) = default; + Cipher& operator=(const Cipher&) = default; + inline Cipher& operator=(const EVP_CIPHER* cipher) { + cipher_ = cipher; + return *this; + } + NCRYPTO_DISALLOW_MOVE(Cipher) + + inline const EVP_CIPHER* get() const { + return cipher_; + } + inline operator const EVP_CIPHER*() const { + return cipher_; + } + inline operator bool() const { + return cipher_ != nullptr; + } + + int getNid() const; + int getMode() const; + int getIvLength() const; + int getKeyLength() const; + int getBlockSize() const; + std::string_view getModeLabel() const; + const char* getName() const; + + bool isGcmMode() const; + bool isWrapMode() const; + bool isCtrMode() const; + bool isCcmMode() const; + bool isOcbMode() const; + bool isStreamMode() const; + bool isChaCha20Poly1305() const; + + bool isSupportedAuthenticatedMode() const; + + int bytesToKey(const Digest& digest, const Buffer& input, unsigned char* key, unsigned char* iv) const; + + static const Cipher FromName(const char* name); + static const Cipher FromNid(int nid); + static const Cipher FromCtx(const CipherCtxPointer& ctx); + + using CipherNameCallback = std::function; + + // Iterates the known ciphers if the underlying implementation + // is able to do so. + static void ForEach(CipherNameCallback callback); + + // Utilities to get various ciphers by type. If the underlying + // implementation does not support the requested cipher, then + // the result will be an empty Cipher object whose bool operator + // will return false. + + static const Cipher EMPTY; + static const Cipher AES_128_CBC; + static const Cipher AES_192_CBC; + static const Cipher AES_256_CBC; + static const Cipher AES_128_CTR; + static const Cipher AES_192_CTR; + static const Cipher AES_256_CTR; + static const Cipher AES_128_GCM; + static const Cipher AES_192_GCM; + static const Cipher AES_256_GCM; + static const Cipher AES_128_KW; + static const Cipher AES_192_KW; + static const Cipher AES_256_KW; + static const Cipher AES_128_OCB; + static const Cipher AES_192_OCB; + static const Cipher AES_256_OCB; + static const Cipher CHACHA20_POLY1305; + + struct CipherParams { + int padding; + Digest digest; + const Buffer label; + }; + + static DataPointer encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer in); + static DataPointer decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer in); + + static DataPointer sign(const EVPKeyPointer& key, const CipherParams& params, const Buffer in); + + static DataPointer recover(const EVPKeyPointer& key, const CipherParams& params, const Buffer in); + + static constexpr bool IsValidGCMTagLength(unsigned int tag_len) { + return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16); + } + + private: + const EVP_CIPHER* cipher_ = nullptr; +}; + +class BignumPointer final { + public: + BignumPointer() = default; + explicit BignumPointer(BIGNUM* bignum); + explicit BignumPointer(const unsigned char* data, size_t len); + BignumPointer(BignumPointer&& other) noexcept; + BignumPointer& operator=(BignumPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(BignumPointer) + ~BignumPointer(); + + int operator<=>(const BignumPointer& other) const noexcept; + int operator<=>(const BIGNUM* other) const noexcept; + inline operator bool() const { + return bn_ != nullptr; + } + inline BIGNUM* get() const noexcept { + return bn_.get(); + } + void reset(BIGNUM* bn = nullptr); + void reset(const unsigned char* data, size_t len); + BIGNUM* release(); + + bool isZero() const; + bool isOne() const; + + bool setWord(unsigned long w); // NOLINT(runtime/int) + unsigned long getWord() const; // NOLINT(runtime/int) + + size_t byteLength() const; + size_t bitLength() const; + + DataPointer toHex() const; + DataPointer encode() const; + DataPointer encodePadded(size_t size) const; + size_t encodeInto(unsigned char* out) const; + size_t encodePaddedInto(unsigned char* out, size_t size) const; + + using PrimeCheckCallback = std::function; + int isPrime(int checks, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; + struct PrimeConfig { + int bits; + bool safe = false; + const BignumPointer& add; + const BignumPointer& rem; + }; + + static BignumPointer NewPrime(const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback); + + bool generate(const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; + + static BignumPointer New(); + static BignumPointer NewSecure(); + static BignumPointer NewSub(const BignumPointer& a, const BignumPointer& b); + static BignumPointer NewLShift(size_t length); + + static DataPointer Encode(const BIGNUM* bn); + static DataPointer EncodePadded(const BIGNUM* bn, size_t size); + static size_t EncodePaddedInto(const BIGNUM* bn, unsigned char* out, size_t size); + static int GetBitCount(const BIGNUM* bn); + static int GetByteCount(const BIGNUM* bn); + static unsigned long GetWord(const BIGNUM* bn); // NOLINT(runtime/int) + static const BIGNUM* One(); + + BignumPointer clone(); + + private: + DeleteFnPtr bn_; + + static bool defaultPrimeCheckCallback(int, int) { + return 1; + } +}; + +// A managed pointer to a buffer of data. When destroyed the underlying +// buffer will be freed. +class DataPointer final { + public: + static DataPointer Alloc(size_t len); + static DataPointer Copy(const Buffer& buffer); + + // Attempts to allocate the buffer space using the secure heap, if + // supported/enabled. If the secure heap is disabled, then this + // ends up being equivalent to Alloc(len). Note that allocation + // will fail if there is not enough free space remaining in the + // secure heap space. + static DataPointer SecureAlloc(size_t len); + + // If the secure heap is enabled, returns the amount of data that + // has been allocated from the heap. + static size_t GetSecureHeapUsed(); + + enum class InitSecureHeapResult { + FAILED, + UNABLE_TO_MEMORY_MAP, + OK, + }; + + // Attempt to initialize the secure heap. The secure heap is not + // supported on all operating systems and whenever boringssl is + // used. + static InitSecureHeapResult TryInitSecureHeap(size_t amount, size_t min); + + DataPointer() = default; + explicit DataPointer(void* data, size_t len, bool secure = false); + explicit DataPointer(const Buffer& buffer, bool secure = false); + DataPointer(DataPointer&& other) noexcept; + DataPointer& operator=(DataPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(DataPointer) + ~DataPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return data_ == nullptr; + } + inline operator bool() const { + return data_ != nullptr; + } + + template + inline T* get() const noexcept { + return static_cast(data_); + } + + inline size_t size() const noexcept { + return len_; + } + void reset(void* data = nullptr, size_t len = 0); + void reset(const Buffer& buffer); + + // Sets the underlying data buffer to all zeros. + void zero(); + + DataPointer resize(size_t len); + + // Releases ownership of the underlying data buffer. It is the caller's + // responsibility to ensure the buffer is appropriately freed. + Buffer release(); + + // Returns a Buffer struct that is a view of the underlying data. + template + inline operator const Buffer() const { + return { + .data = static_cast(data_), + .len = len_, + }; + } + + bool isSecure() const { + return secure_; + } + + private: + void free(); + + void* data_ = nullptr; + size_t len_ = 0; + bool secure_ = false; +}; + +class BIOPointer final { + public: + static BIOPointer NewMem(); + static BIOPointer NewSecMem(); + static BIOPointer New(const BIO_METHOD* method); + static BIOPointer New(const void* data, size_t len); + static BIOPointer New(const BIGNUM* bn); + static BIOPointer NewFile(const char* filename, const char* mode); + static BIOPointer NewFp(FILE* fd, int flags); + + template + static BIOPointer New(const Buffer& buf) { + return New(buf.data, buf.len); + } + + BIOPointer() = default; + BIOPointer(std::nullptr_t) : bio_(nullptr) {} + explicit BIOPointer(BIO* bio); + BIOPointer(BIOPointer&& other) noexcept; + BIOPointer& operator=(BIOPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(BIOPointer) + ~BIOPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return bio_ == nullptr; + } + inline operator bool() const { + return bio_ != nullptr; + } + inline BIO* get() const noexcept { + return bio_.get(); + } + + inline operator BUF_MEM*() const { + BUF_MEM* mem = nullptr; + if (!bio_) + return mem; + BIO_get_mem_ptr(bio_.get(), &mem); + return mem; + } + + inline operator BIO*() const { + return bio_.get(); + } + + void reset(BIO* bio = nullptr); + BIO* release(); + + bool resetBio() const; + + static int Write(BIOPointer* bio, std::string_view message); + + template + static void Printf(BIOPointer* bio, const char* format, Args... args) { + if (bio == nullptr || !*bio) + return; + BIO_printf(bio->get(), format, std::forward(args...)); + } + + private: + mutable DeleteFnPtr bio_; +}; + +class CipherCtxPointer final { + public: + static CipherCtxPointer New(); + + CipherCtxPointer() = default; + explicit CipherCtxPointer(EVP_CIPHER_CTX* ctx); + CipherCtxPointer(CipherCtxPointer&& other) noexcept; + CipherCtxPointer& operator=(CipherCtxPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(CipherCtxPointer) + ~CipherCtxPointer(); + + inline bool operator==(std::nullptr_t) const noexcept { + return ctx_ == nullptr; + } + inline operator bool() const { + return ctx_ != nullptr; + } + inline EVP_CIPHER_CTX* get() const { + return ctx_.get(); + } + inline operator EVP_CIPHER_CTX*() const { + return ctx_.get(); + } + void reset(EVP_CIPHER_CTX* ctx = nullptr); + EVP_CIPHER_CTX* release(); + + void setAllowWrap(); + + bool setKeyLength(size_t length); + bool setIvLength(size_t length); + bool setAeadTag(const Buffer& tag); + bool setAeadTagLength(size_t length); + bool setPadding(bool padding); + bool init(const Cipher& cipher, bool encrypt, const unsigned char* key = nullptr, const unsigned char* iv = nullptr); + + int getBlockSize() const; + int getMode() const; + int getNid() const; + + bool isGcmMode() const; + bool isOcbMode() const; + bool isCcmMode() const; + bool isWrapMode() const; + bool isChaCha20Poly1305() const; + + bool update(const Buffer& in, unsigned char* out, int* out_len, bool finalize = false); + bool getAeadTag(size_t len, unsigned char* out); + + private: + DeleteFnPtr ctx_; +}; + +class EVPKeyCtxPointer final { + public: + EVPKeyCtxPointer(); + explicit EVPKeyCtxPointer(EVP_PKEY_CTX* ctx); + EVPKeyCtxPointer(EVPKeyCtxPointer&& other) noexcept; + EVPKeyCtxPointer& operator=(EVPKeyCtxPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(EVPKeyCtxPointer) + ~EVPKeyCtxPointer(); + + inline bool operator==(std::nullptr_t) const noexcept { + return ctx_ == nullptr; + } + inline operator bool() const { + return ctx_ != nullptr; + } + inline EVP_PKEY_CTX* get() const { + return ctx_.get(); + } + void reset(EVP_PKEY_CTX* ctx = nullptr); + EVP_PKEY_CTX* release(); + + bool initForDerive(const EVPKeyPointer& peer); + DataPointer derive() const; + + bool initForParamgen(); + bool setDhParameters(int prime_size, uint32_t generator); + bool setDsaParameters(uint32_t bits, std::optional q_bits); + bool setEcParameters(int curve, int encoding); + + bool setRsaOaepMd(const Digest& md); + bool setRsaMgf1Md(const Digest& md); + bool setRsaPadding(int padding); + bool setRsaKeygenPubExp(BignumPointer&& e); + bool setRsaKeygenBits(int bits); + bool setRsaPssKeygenMd(const Digest& md); + bool setRsaPssKeygenMgf1Md(const Digest& md); + bool setRsaPssSaltlen(int salt_len); + bool setRsaImplicitRejection(); + bool setRsaOaepLabel(DataPointer&& data); + + bool setSignatureMd(const EVPMDCtxPointer& md); + + bool publicCheck() const; + bool privateCheck() const; + + bool verify(const Buffer& sig, const Buffer& data); + DataPointer sign(const Buffer& data); + bool signInto(const Buffer& data, Buffer* sig); + + static constexpr int kDefaultRsaExponent = 0x10001; + + static bool setRsaPadding(EVP_PKEY_CTX* ctx, int padding, std::optional salt_len = std::nullopt); + + EVPKeyPointer paramgen() const; + + bool initForEncrypt(); + bool initForDecrypt(); + bool initForKeygen(); + int initForVerify(); + int initForSign(); + + static EVPKeyCtxPointer New(const EVPKeyPointer& key); + static EVPKeyCtxPointer NewFromID(int id); + + private: + DeleteFnPtr ctx_; +}; + +class EVPKeyPointer final { + public: + static EVPKeyPointer New(); + static EVPKeyPointer NewRawPublic(int id, const Buffer& data); + static EVPKeyPointer NewRawPrivate(int id, const Buffer& data); +#if OPENSSL_WITH_PQC + static EVPKeyPointer NewRawSeed(int id, const Buffer& data); +#endif + enum class PKEncodingType { + // RSAPublicKey / RSAPrivateKey according to PKCS#1. + PKCS1, + // PrivateKeyInfo or EncryptedPrivateKeyInfo according to PKCS#8. + PKCS8, + // SubjectPublicKeyInfo according to X.509. + SPKI, + // ECPrivateKey according to SEC1. + SEC1, + }; + + enum class PKFormatType { + DER, + PEM, + JWK, + RAW_PUBLIC, + RAW_PRIVATE, + RAW_SEED, + }; + + enum class PKParseError { NOT_RECOGNIZED, NEED_PASSPHRASE, FAILED }; + using ParseKeyResult = Result; + + struct AsymmetricKeyEncodingConfig { + bool output_key_object = false; + PKFormatType format = PKFormatType::DER; + PKEncodingType type = PKEncodingType::PKCS8; + int ec_point_form = POINT_CONVERSION_UNCOMPRESSED; + AsymmetricKeyEncodingConfig() = default; + AsymmetricKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type); + AsymmetricKeyEncodingConfig(const AsymmetricKeyEncodingConfig&) = default; + AsymmetricKeyEncodingConfig& operator=(const AsymmetricKeyEncodingConfig&) = default; + }; + using PublicKeyEncodingConfig = AsymmetricKeyEncodingConfig; + + struct PrivateKeyEncodingConfig : public AsymmetricKeyEncodingConfig { + const EVP_CIPHER* cipher = nullptr; + std::optional passphrase = std::nullopt; + PrivateKeyEncodingConfig() = default; + PrivateKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type) + : AsymmetricKeyEncodingConfig(output_key_object, format, type) {} + PrivateKeyEncodingConfig(const PrivateKeyEncodingConfig&); + PrivateKeyEncodingConfig& operator=(const PrivateKeyEncodingConfig&); + }; + + static ParseKeyResult TryParsePublicKey(const PublicKeyEncodingConfig& config, const Buffer& buffer); + + static ParseKeyResult TryParsePublicKeyPEM(const Buffer& buffer); + + static ParseKeyResult TryParsePrivateKey(const PrivateKeyEncodingConfig& config, const Buffer& buffer); + + EVPKeyPointer() = default; + explicit EVPKeyPointer(EVP_PKEY* pkey); + EVPKeyPointer(EVPKeyPointer&& other) noexcept; + EVPKeyPointer& operator=(EVPKeyPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(EVPKeyPointer) + ~EVPKeyPointer(); + + inline bool operator==(std::nullptr_t) const noexcept { + return pkey_ == nullptr; + } + inline operator bool() const { + return pkey_ != nullptr; + } + inline EVP_PKEY* get() const { + return pkey_.get(); + } + void reset(EVP_PKEY* pkey = nullptr); + EVP_PKEY* release(); + + static int id(const EVP_PKEY* key); + static int base_id(const EVP_PKEY* key); + + int id() const; + int base_id() const; + int bits() const; + size_t size() const; + + size_t rawPublicKeySize() const; + size_t rawPrivateKeySize() const; + DataPointer rawPublicKey() const; + DataPointer rawPrivateKey() const; + BIOPointer derPublicKey() const; + +#if OPENSSL_WITH_PQC + DataPointer rawSeed() const; +#endif + + Result writePrivateKey(const PrivateKeyEncodingConfig& config) const; + Result writePublicKey(const PublicKeyEncodingConfig& config) const; + + EVPKeyCtxPointer newCtx() const; + + static bool IsRSAPrivateKey(const Buffer& buffer); + + std::optional getBytesOfRS() const; + int getDefaultSignPadding() const; + bool isRsaVariant() const; + bool isOneShotVariant() const; + bool isSigVariant() const; + bool validateDsaParameters() const; + + EVPKeyPointer clone() const; + + private: + DeleteFnPtr pkey_; +}; + +class X509View final { + public: + X509View() = default; + inline explicit X509View(const X509* cert) : cert_(cert) {} + X509View(const X509View& other) = default; + X509View& operator=(const X509View& other) = default; + NCRYPTO_DISALLOW_MOVE(X509View) + + inline X509* get() const { + return const_cast(cert_); + } + inline operator X509*() const { + return const_cast(cert_); + } + inline operator const X509*() const { + return cert_; + } + + inline bool operator==(std::nullptr_t) noexcept { + return cert_ == nullptr; + } + inline operator bool() const { + return cert_ != nullptr; + } + + BIOPointer toPEM() const; + BIOPointer toDER() const; + + BIOPointer getSubject() const; + BIOPointer getSubjectAltName() const; + BIOPointer getIssuer() const; + BIOPointer getInfoAccess() const; + BIOPointer getValidFrom() const; + BIOPointer getValidTo() const; + std::optional getSignatureAlgorithm() const; + std::optional getSignatureAlgorithmOID() const; + int64_t getValidFromTime() const; + int64_t getValidToTime() const; + DataPointer getSerialNumber() const; + Result getPublicKey() const; + StackOfASN1 getKeyUsage() const; + + bool isCA() const; + bool isIssuedBy(const X509View& other) const; + bool checkPrivateKey(const EVPKeyPointer& pkey) const; + bool checkPublicKey(const EVPKeyPointer& pkey) const; + + std::optional getFingerprint(const Digest& method) const; + + enum class CheckMatch { + NO_MATCH, + MATCH, + INVALID_NAME, + OPERATION_FAILED, + }; + CheckMatch checkHost(std::string_view host, int flags, DataPointer* peerName = nullptr) const; + CheckMatch checkEmail(std::string_view email, int flags) const; + CheckMatch checkIp(std::string_view ip, int flags) const; + + using UsageCallback = std::function; + bool enumUsages(UsageCallback callback) const; + + private: + const X509* cert_ = nullptr; +}; + +class X509Pointer final { + public: + static Result Parse(Buffer buffer); + X509Pointer() = default; + explicit X509Pointer(X509* cert); + X509Pointer(X509Pointer&& other) noexcept; + X509Pointer& operator=(X509Pointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(X509Pointer) + ~X509Pointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return cert_ == nullptr; + } + inline operator bool() const { + return cert_ != nullptr; + } + inline X509* get() const { + return cert_.get(); + } + inline operator X509*() const { + return cert_.get(); + } + inline operator const X509*() const { + return cert_.get(); + } + void reset(X509* cert = nullptr); + X509* release(); + + X509View view() const; + operator X509View() const { + return view(); + } + + static const char* ErrorCode(int32_t err); + static std::optional ErrorReason(int32_t err); + + private: + DeleteFnPtr cert_; +}; + +class ECDSASigPointer final { + public: + explicit ECDSASigPointer(); + explicit ECDSASigPointer(ECDSA_SIG* sig); + ECDSASigPointer(ECDSASigPointer&& other) noexcept; + ECDSASigPointer& operator=(ECDSASigPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(ECDSASigPointer) + ~ECDSASigPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return sig_ == nullptr; + } + inline operator bool() const { + return sig_ != nullptr; + } + inline ECDSA_SIG* get() const { + return sig_.get(); + } + inline operator ECDSA_SIG*() const { + return sig_.get(); + } + void reset(ECDSA_SIG* sig = nullptr); + ECDSA_SIG* release(); + + static ECDSASigPointer New(); + static ECDSASigPointer Parse(const Buffer& buffer); + + inline const BIGNUM* r() const { + return pr_; + } + inline const BIGNUM* s() const { + return ps_; + } + + bool setParams(BignumPointer&& r, BignumPointer&& s); + + Buffer encode() const; + + private: + DeleteFnPtr sig_; + const BIGNUM* pr_ = nullptr; + const BIGNUM* ps_ = nullptr; +}; + +class EVPMDCtxPointer final { + public: + EVPMDCtxPointer(); + explicit EVPMDCtxPointer(EVP_MD_CTX* ctx); + EVPMDCtxPointer(EVPMDCtxPointer&& other) noexcept; + EVPMDCtxPointer& operator=(EVPMDCtxPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(EVPMDCtxPointer) + ~EVPMDCtxPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return ctx_ == nullptr; + } + inline operator bool() const { + return ctx_ != nullptr; + } + inline EVP_MD_CTX* get() const { + return ctx_.get(); + } + inline operator EVP_MD_CTX*() const { + return ctx_.get(); + } + void reset(EVP_MD_CTX* ctx = nullptr); + EVP_MD_CTX* release(); + + bool digestInit(const Digest& digest); + bool digestUpdate(const Buffer& in); + DataPointer digestFinal(size_t length); + bool digestFinalInto(Buffer* buf); + size_t getExpectedSize(); + + std::optional signInit(const EVPKeyPointer& key, const Digest& digest); + std::optional verifyInit(const EVPKeyPointer& key, const Digest& digest); + + std::optional signInitWithContext(const EVPKeyPointer& key, const Digest& digest, + const Buffer& context_string); + std::optional verifyInitWithContext(const EVPKeyPointer& key, const Digest& digest, + const Buffer& context_string); + + DataPointer signOneShot(const Buffer& buf) const; + DataPointer sign(const Buffer& buf) const; + bool verify(const Buffer& buf, const Buffer& sig) const; + + const EVP_MD* getDigest() const; + size_t getDigestSize() const; + bool hasXofFlag() const; + + bool copyTo(const EVPMDCtxPointer& other) const; + + static EVPMDCtxPointer New(); + + private: + DeleteFnPtr ctx_; +}; + +#if OPENSSL_VERSION_MAJOR >= 3 +class EVPMacPointer final { + public: + EVPMacPointer() = default; + explicit EVPMacPointer(EVP_MAC* mac); + EVPMacPointer(EVPMacPointer&& other) noexcept; + EVPMacPointer& operator=(EVPMacPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(EVPMacPointer) + ~EVPMacPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return mac_ == nullptr; + } + inline operator bool() const { + return mac_ != nullptr; + } + inline EVP_MAC* get() const { + return mac_.get(); + } + inline operator EVP_MAC*() const { + return mac_.get(); + } + void reset(EVP_MAC* mac = nullptr); + EVP_MAC* release(); + + static EVPMacPointer Fetch(const char* algorithm); + + private: + DeleteFnPtr mac_; +}; + +class EVPMacCtxPointer final { + public: + EVPMacCtxPointer() = default; + explicit EVPMacCtxPointer(EVP_MAC_CTX* ctx); + EVPMacCtxPointer(EVPMacCtxPointer&& other) noexcept; + EVPMacCtxPointer& operator=(EVPMacCtxPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(EVPMacCtxPointer) + ~EVPMacCtxPointer(); + + inline bool operator==(std::nullptr_t) noexcept { + return ctx_ == nullptr; + } + inline operator bool() const { + return ctx_ != nullptr; + } + inline EVP_MAC_CTX* get() const { + return ctx_.get(); + } + inline operator EVP_MAC_CTX*() const { + return ctx_.get(); + } + void reset(EVP_MAC_CTX* ctx = nullptr); + EVP_MAC_CTX* release(); + + bool init(const Buffer& key, const OSSL_PARAM* params = nullptr); + bool update(const Buffer& data); + DataPointer final(size_t length); + + static EVPMacCtxPointer New(EVP_MAC* mac); + + private: + DeleteFnPtr ctx_; +}; +#endif // OPENSSL_VERSION_MAJOR >= 3 + +// ============================================================================ +// FIPS +bool isFipsEnabled(); + +bool setFipsEnabled(bool enabled, CryptoErrorList* errors); + +bool testFipsEnabled(); + +// ============================================================================ +// Various utilities + +bool CSPRNG(void* buffer, size_t length) NCRYPTO_MUST_USE_RESULT; + +// This callback is used to avoid the default passphrase callback in OpenSSL +// which will typically prompt for the passphrase. The prompting is designed +// for the OpenSSL CLI, but works poorly for some environments like Node.js +// because it involves synchronous interaction with the controlling terminal, +// something we never want, and use this function to avoid it. +int NoPasswordCallback(char* buf, int size, int rwflag, void* u); + +int PasswordCallback(char* buf, int size, int rwflag, void* u); + +bool SafeX509SubjectAltNamePrint(const BIOPointer& out, const X509_EXTENSION* ext); +bool SafeX509InfoAccessPrint(const BIOPointer& out, const X509_EXTENSION* ext); + +// ============================================================================ +// SPKAC + +bool VerifySpkac(const char* input, size_t length); +BIOPointer ExportPublicKey(const char* input, size_t length); + +// The caller takes ownership of the returned Buffer +Buffer ExportChallenge(const char* input, size_t length); + +bool VerifySpkac(const Buffer& buf); +BIOPointer ExportPublicKey(const Buffer& buf); +DataPointer ExportChallenge(const Buffer& buf); + +// ============================================================================ +// KDF + +const EVP_MD* getDigestByName(const char* name); +const EVP_CIPHER* getCipherByName(const char* name); + +// Verify that the specified HKDF output length is valid for the given digest. +// The maximum length for HKDF output for a given digest is 255 times the +// hash size for the given digest algorithm. +bool checkHkdfLength(const Digest& digest, size_t length); + +bool extractP1363(const Buffer& buf, unsigned char* dest, size_t n); + +bool hkdfInfo(const Digest& md, const Buffer& key, const Buffer& info, + const Buffer& salt, size_t length, Buffer* out); + +DataPointer hkdf(const Digest& md, const Buffer& key, const Buffer& info, + const Buffer& salt, size_t length); + +bool checkScryptParams(uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem); + +bool scryptInto(const Buffer& pass, const Buffer& salt, uint64_t N, uint64_t r, uint64_t p, + uint64_t maxmem, size_t length, Buffer* out); + +DataPointer scrypt(const Buffer& pass, const Buffer& salt, uint64_t N, uint64_t r, uint64_t p, + uint64_t maxmem, size_t length); + +bool pbkdf2Into(const Digest& md, const Buffer& pass, const Buffer& salt, uint32_t iterations, + size_t length, Buffer* out); + +DataPointer pbkdf2(const Digest& md, const Buffer& pass, const Buffer& salt, uint32_t iterations, + size_t length); + +#if OPENSSL_VERSION_NUMBER >= 0x30200000L +#ifndef OPENSSL_NO_ARGON2 +enum class Argon2Type { ARGON2D, ARGON2I, ARGON2ID }; + +DataPointer argon2(const Buffer& pass, const Buffer& salt, uint32_t lanes, size_t length, uint32_t memcost, + uint32_t iter, uint32_t version, const Buffer& secret, const Buffer& ad, + Argon2Type type); +#endif +#endif + +// ============================================================================ +// KEM (Key Encapsulation Mechanism) +#if OPENSSL_VERSION_MAJOR >= 3 + +class KEM final { + public: + struct EncapsulateResult { + DataPointer ciphertext; + DataPointer shared_key; + + EncapsulateResult() = default; + EncapsulateResult(DataPointer ct, DataPointer sk) : ciphertext(std::move(ct)), shared_key(std::move(sk)) {} + }; + + // Encapsulate a shared secret using KEM with a public key. + // Returns both the ciphertext and shared secret. + static std::optional Encapsulate(const EVPKeyPointer& public_key); + + // Decapsulate a shared secret using KEM with a private key and ciphertext. + // Returns the shared secret. + static DataPointer Decapsulate(const EVPKeyPointer& private_key, const Buffer& ciphertext); + + private: +#if !OPENSSL_VERSION_PREREQ(3, 5) + static bool SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key); +#endif +}; + +#endif // OPENSSL_VERSION_MAJOR >= 3 + +#include "ncrypto/version.h" + +} // namespace ncrypto diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h new file mode 100644 index 000000000..5d4e01b64 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h @@ -0,0 +1,136 @@ +#pragma once + +#include "ncrypto.h" + +#ifdef OPENSSL_IS_BORINGSSL + +namespace ncrypto { + +class AeadCtxPointer; + +class Aead final { + private: + // BoringSSL does not keep a list of AEADs, so we need to maintain our own. + struct AeadInfo { + std::string name; + int mode; + int nid = 0; // Note: BoringSSL only defines NIDs for some AEADs + }; + + public: + Aead() = default; + Aead(const AeadInfo* info, const EVP_AEAD* aead) : aead_(aead), info_(info) {} + Aead(const Aead&) = default; + Aead& operator=(const Aead&) = default; + NCRYPTO_DISALLOW_MOVE(Aead) + + inline const EVP_AEAD* get() const { + return aead_; + } + std::string_view getModeLabel() const; + inline operator const EVP_AEAD*() const { + return aead_; + } + inline operator bool() const { + return aead_ != nullptr; + } + + int getMode() const; + int getNonceLength() const; + int getKeyLength() const; + int getBlockSize() const; + int getMaxOverhead() const; + int getMaxTagLength() const; + std::string_view getName() const; + + static const Aead FromName(std::string_view name); + + // TODO(npaun): BoringSSL does not define NIDs for all AEADs. + // This method is included only for implementing getCipherInfo and can't be + // used to construct an Aead instance. + int getNid() const; + // static const AEAD FromNid(int nid); + + static const Aead FromCtx(std::string_view name, const AeadCtxPointer& ctx); + + using AeadNameCallback = std::function; + + // Iterates the known ciphers if the underlying implementation + // is able to do so. + static void ForEach(AeadNameCallback callback); + + // Utilities to get various AEADs by type. + + static const Aead EMPTY; + static const Aead AES_128_GCM; + static const Aead AES_192_GCM; + static const Aead AES_256_GCM; + static const Aead CHACHA20_POLY1305; + static const Aead XCHACHA20_POLY1305; + static const Aead AES_128_CTR_HMAC_SHA256; + static const Aead AES_256_CTR_HMAC_SHA256; + static const Aead AES_128_GCM_SIV; + static const Aead AES_256_GCM_SIV; + static const Aead AES_128_GCM_RANDNONCE; + static const Aead AES_256_GCM_RANDNONCE; + static const Aead AES_128_CCM_BLUETOOTH; + static const Aead AES_128_CCM_BLUETOOTH_8; + static const Aead AES_128_CCM_MATTER; + static const Aead AES_128_EAX; + static const Aead AES_256_EAX; + + private: + const EVP_AEAD* aead_ = nullptr; + const AeadInfo* info_ = nullptr; + + using AeadConstructor = const EVP_AEAD* (*)(); + static const std::unordered_map aeadIndex; + static const Aead FromConstructor(AeadConstructor construct); +}; + +class AeadCtxPointer final { + public: + static AeadCtxPointer New(const Aead& aead, bool encrypt, const unsigned char* key = nullptr, size_t keyLen = 0, + size_t tagLen = EVP_AEAD_DEFAULT_TAG_LENGTH /* = 0 */); + + AeadCtxPointer() = default; + explicit AeadCtxPointer(EVP_AEAD_CTX* ctx); + AeadCtxPointer(AeadCtxPointer&& other) noexcept; + AeadCtxPointer& operator=(AeadCtxPointer&& other) noexcept; + NCRYPTO_DISALLOW_COPY(AeadCtxPointer) + ~AeadCtxPointer(); + + inline bool operator==(std::nullptr_t) const noexcept { + return ctx_ == nullptr; + } + inline operator bool() const { + return ctx_ != nullptr; + } + inline EVP_AEAD_CTX* get() const { + return ctx_.get(); + } + inline operator EVP_AEAD_CTX*() const { + return ctx_.get(); + } + void reset(EVP_AEAD_CTX* ctx = nullptr); + EVP_AEAD_CTX* release(); + + bool init(const Aead& aead, bool encrypt, const unsigned char* key = nullptr, size_t keyLen = 0, + size_t tagLen = EVP_AEAD_DEFAULT_TAG_LENGTH /* = 0 */); + + // TODO(npaun): BoringSSL does not define NIDs for all AEADs. + // Decide if we will even implement this method. + // int getNid() const; + + bool encrypt(const Buffer& in, Buffer& out, Buffer& tag, + const Buffer& nonce, const Buffer& aad); + + bool decrypt(const Buffer& in, Buffer& out, const Buffer& tag, + const Buffer& nonce, const Buffer& aad); + + private: + DeleteFnPtr ctx_; +}; +} // namespace ncrypto + +#endif // OPENSSL_IS_BORINGSSL diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h new file mode 100644 index 000000000..695c705d6 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h @@ -0,0 +1,14 @@ +// ============================================================================ +// Version metadata +#ifndef NCRYPTO_VERSION_H_ +#define NCRYPTO_VERSION_H_ + +#define NCRYPTO_VERSION "1.1.4" // x-release-please-version + +enum { + NCRYPTO_VERSION_MAJOR = 1, // x-release-please-major + NCRYPTO_VERSION_MINOR = 1, // x-release-please-minor + NCRYPTO_VERSION_REVISION = 4, // x-release-please-patch +}; + +#endif // NCRYPTO_VERSION_H_ diff --git a/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp b/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp new file mode 100644 index 000000000..edd6f1044 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp @@ -0,0 +1,249 @@ +// ============================================================================ +// AEAD (Authenticated Encryption with Associated Data) +#include "ncrypto.h" + +#ifdef OPENSSL_IS_BORINGSSL +#include "ncrypto/aead.h" + +namespace ncrypto { + +const Aead Aead::FromName(std::string_view name) { + for (const auto& [construct, info] : aeadIndex) { + if (EqualNoCase(info.name, name)) { + return Aead(&info, construct()); + } + } + + return Aead(); +} + +const Aead Aead::FromCtx(std::string_view name, const AeadCtxPointer& ctx) { + for (const auto& [_, info] : aeadIndex) { + if (info.name == name) { + return Aead(&info, EVP_AEAD_CTX_aead(ctx.get())); + } + } + + return Aead(); +} + +int Aead::getMode() const { + if (!aead_) + return -1; + + return info_->mode; +} + +std::string_view Aead::getModeLabel() const { + if (!aead_) + return {}; + switch (getMode()) { + case EVP_CIPH_CCM_MODE: + return "ccm"; + case EVP_CIPH_CTR_MODE: + return "ctr"; + case EVP_CIPH_GCM_MODE: + return "gcm"; + case EVP_CIPH_STREAM_CIPHER: + return "stream"; + } + return "{unknown}"; +} + +int Aead::getNonceLength() const { + if (!aead_) + return 0; + return EVP_AEAD_nonce_length(aead_); +} + +int Aead::getKeyLength() const { + if (!aead_) + return 0; + return EVP_AEAD_key_length(aead_); +} + +int Aead::getMaxOverhead() const { + if (!aead_) + return 0; + return EVP_AEAD_max_overhead(aead_); +} + +int Aead::getMaxTagLength() const { + if (!aead_) + return 0; + return EVP_AEAD_max_tag_len(aead_); +} + +int Aead::getBlockSize() const { + if (!aead_) + return 0; + + // EVP_CIPHER_CTX_block_size returns the block size, in bytes, of the cipher + // underlying |ctx|, or one if the cipher is a stream cipher. + return 1; +} + +std::string_view Aead::getName() const { + if (!aead_) + return ""; + + return info_->name; +} + +int Aead::getNid() const { + if (!aead_) + return 0; + + return info_->nid; +} + +const Aead Aead::FromConstructor(Aead::AeadConstructor construct) { + return Aead(&aeadIndex.at(construct), construct()); +} + +const std::unordered_map Aead::aeadIndex = { + {EVP_aead_aes_128_gcm, {.name = LN_aes_128_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_128_gcm}}, + {EVP_aead_aes_192_gcm, {.name = LN_aes_192_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_192_gcm}}, + {EVP_aead_aes_256_gcm, {.name = LN_aes_256_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_256_gcm}}, + {EVP_aead_chacha20_poly1305, {.name = LN_chacha20_poly1305, .mode = EVP_CIPH_STREAM_CIPHER, .nid = NID_chacha20_poly1305}}, + {EVP_aead_xchacha20_poly1305, + { + .name = "xchacha20-poly1305", + .mode = EVP_CIPH_STREAM_CIPHER, + }}, + {EVP_aead_aes_128_ctr_hmac_sha256, + { + .name = "aes-128-ctr-hmac-sha256", + .mode = EVP_CIPH_CTR_MODE, + }}, + {EVP_aead_aes_256_ctr_hmac_sha256, + { + .name = "aes-256-ctr-hmac-sha256", + .mode = EVP_CIPH_CTR_MODE, + }}, + {EVP_aead_aes_128_gcm_siv, + { + .name = "aes-128-gcm-siv", + .mode = EVP_CIPH_GCM_MODE, + }}, + {EVP_aead_aes_256_gcm_siv, + { + .name = "aes-256-gcm-siv", + .mode = EVP_CIPH_GCM_MODE, + }}, + {EVP_aead_aes_128_gcm_randnonce, + { + .name = "aes-128-gcm-randnonce", + .mode = EVP_CIPH_GCM_MODE, + }}, + {EVP_aead_aes_256_gcm_randnonce, + { + .name = "aes-256-gcm-randnonce", + .mode = EVP_CIPH_GCM_MODE, + }}, + {EVP_aead_aes_128_ccm_bluetooth, + { + .name = "aes-128-ccm-bluetooth", + .mode = EVP_CIPH_CCM_MODE, + }}, + {EVP_aead_aes_128_ccm_bluetooth_8, + { + .name = "aes-128-ccm-bluetooth-8", + .mode = EVP_CIPH_CCM_MODE, + }}, + {EVP_aead_aes_128_ccm_matter, + { + .name = "aes-128-ccm-matter", + .mode = EVP_CIPH_CCM_MODE, + }}, + {EVP_aead_aes_128_eax, + {.name = "aes-128-eax", + // BoringSSL does not define a mode constant for EAX. Using STREAM + // arbitrarily + .mode = EVP_CIPH_STREAM_CIPHER}}, + {EVP_aead_aes_256_eax, + {.name = "aes-256-eax", + // BoringSSL does not define a mode constant for EAX. Using STREAM + // arbitrarily + .mode = EVP_CIPH_STREAM_CIPHER}}, +}; + +void Aead::ForEach(AeadNameCallback callback) { + for (const auto& [_, info] : aeadIndex) { + callback(info.name); + } +} + +const Aead Aead::EMPTY = Aead(); +const Aead Aead::AES_128_GCM = Aead::FromConstructor(EVP_aead_aes_128_gcm); +const Aead Aead::AES_192_GCM = Aead::FromConstructor(EVP_aead_aes_192_gcm); +const Aead Aead::AES_256_GCM = Aead::FromConstructor(EVP_aead_aes_256_gcm); +const Aead Aead::CHACHA20_POLY1305 = Aead::FromConstructor(EVP_aead_chacha20_poly1305); +const Aead Aead::XCHACHA20_POLY1305 = Aead::FromConstructor(EVP_aead_xchacha20_poly1305); +const Aead Aead::AES_128_CTR_HMAC_SHA256 = Aead::FromConstructor(EVP_aead_aes_128_ctr_hmac_sha256); +const Aead Aead::AES_256_CTR_HMAC_SHA256 = Aead::FromConstructor(EVP_aead_aes_256_ctr_hmac_sha256); +const Aead Aead::AES_128_GCM_SIV = Aead::FromConstructor(EVP_aead_aes_128_gcm_siv); +const Aead Aead::AES_256_GCM_SIV = Aead::FromConstructor(EVP_aead_aes_256_gcm_siv); +const Aead Aead::AES_128_GCM_RANDNONCE = Aead::FromConstructor(EVP_aead_aes_128_gcm_randnonce); +const Aead Aead::AES_256_GCM_RANDNONCE = Aead::FromConstructor(EVP_aead_aes_256_gcm_randnonce); +const Aead Aead::AES_128_CCM_BLUETOOTH = Aead::FromConstructor(EVP_aead_aes_128_ccm_bluetooth); +const Aead Aead::AES_128_CCM_BLUETOOTH_8 = Aead::FromConstructor(EVP_aead_aes_128_ccm_bluetooth_8); +const Aead Aead::AES_128_CCM_MATTER = Aead::FromConstructor(EVP_aead_aes_128_ccm_matter); +const Aead Aead::AES_128_EAX = Aead::FromConstructor(EVP_aead_aes_128_eax); +const Aead Aead::AES_256_EAX = Aead::FromConstructor(EVP_aead_aes_256_eax); + +AeadCtxPointer AeadCtxPointer::New(const Aead& aead, bool encrypt, const unsigned char* key, size_t keyLen, size_t tagLen) { + // Note: In the EVP_AEAD API new always calls init + auto ret = AeadCtxPointer(EVP_AEAD_CTX_new(aead.get(), key, keyLen, tagLen)); + + if (!ret) { + return {}; + } + + return ret; +} + +AeadCtxPointer::AeadCtxPointer(EVP_AEAD_CTX* ctx) : ctx_(ctx) {} + +AeadCtxPointer::AeadCtxPointer(AeadCtxPointer&& other) noexcept : ctx_(other.release()) {} + +AeadCtxPointer& AeadCtxPointer::operator=(AeadCtxPointer&& other) noexcept { + if (this == &other) + return *this; + this->~AeadCtxPointer(); + return *new (this) AeadCtxPointer(std::move(other)); +} + +AeadCtxPointer::~AeadCtxPointer() { + reset(); +} + +void AeadCtxPointer::reset(EVP_AEAD_CTX* ctx) { + ctx_.reset(ctx); +} + +EVP_AEAD_CTX* AeadCtxPointer::release() { + return ctx_.release(); +} + +bool AeadCtxPointer::init(const Aead& aead, bool encrypt, const unsigned char* key, size_t keyLen, size_t tagLen) { + return EVP_AEAD_CTX_init_with_direction(ctx_.get(), aead, key, keyLen, tagLen, encrypt ? evp_aead_seal : evp_aead_open); +} + +bool AeadCtxPointer::encrypt(const Buffer& in, Buffer& out, Buffer& tag, + const Buffer& nonce, const Buffer& aad) { + if (!ctx_) + return false; + return EVP_AEAD_CTX_seal_scatter(ctx_.get(), out.data, tag.data, &tag.len, tag.len, nonce.data, nonce.len, in.data, in.len, + nullptr /* extra_in */, 0 /* extra_in_len */, aad.data, aad.len) == 1; +} + +bool AeadCtxPointer::decrypt(const Buffer& in, Buffer& out, const Buffer& tag, + const Buffer& nonce, const Buffer& aad) { + if (!ctx_) + return false; + + return EVP_AEAD_CTX_open_gather(ctx_.get(), out.data, nonce.data, nonce.len, in.data, in.len, tag.data, tag.len, aad.data, aad.len) == 1; +} +} // namespace ncrypto +#endif diff --git a/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp b/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp new file mode 100644 index 000000000..f4927e64f --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp @@ -0,0 +1,3809 @@ +#include "ncrypto.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef NCRYPTO_NO_KDF_H +#include +#endif +#ifdef OPENSSL_IS_BORINGSSL +#include +#endif + +#include +#include +#include +#include +#include +#include +#if OPENSSL_VERSION_MAJOR >= 3 +#include +#include +#include +#if OPENSSL_VERSION_NUMBER >= 0x30200000L +#include +#endif +#endif +#if OPENSSL_WITH_PQC +struct PQCMapping { + const char* name; + int nid; +}; + +constexpr static PQCMapping pqc_mappings[] = { + {"ML-DSA-44", EVP_PKEY_ML_DSA_44}, + {"ML-DSA-65", EVP_PKEY_ML_DSA_65}, + {"ML-DSA-87", EVP_PKEY_ML_DSA_87}, + {"ML-KEM-512", EVP_PKEY_ML_KEM_512}, + {"ML-KEM-768", EVP_PKEY_ML_KEM_768}, + {"ML-KEM-1024", EVP_PKEY_ML_KEM_1024}, + {"SLH-DSA-SHA2-128f", EVP_PKEY_SLH_DSA_SHA2_128F}, + {"SLH-DSA-SHA2-128s", EVP_PKEY_SLH_DSA_SHA2_128S}, + {"SLH-DSA-SHA2-192f", EVP_PKEY_SLH_DSA_SHA2_192F}, + {"SLH-DSA-SHA2-192s", EVP_PKEY_SLH_DSA_SHA2_192S}, + {"SLH-DSA-SHA2-256f", EVP_PKEY_SLH_DSA_SHA2_256F}, + {"SLH-DSA-SHA2-256s", EVP_PKEY_SLH_DSA_SHA2_256S}, + {"SLH-DSA-SHAKE-128f", EVP_PKEY_SLH_DSA_SHAKE_128F}, + {"SLH-DSA-SHAKE-128s", EVP_PKEY_SLH_DSA_SHAKE_128S}, + {"SLH-DSA-SHAKE-192f", EVP_PKEY_SLH_DSA_SHAKE_192F}, + {"SLH-DSA-SHAKE-192s", EVP_PKEY_SLH_DSA_SHAKE_192S}, + {"SLH-DSA-SHAKE-256f", EVP_PKEY_SLH_DSA_SHAKE_256F}, + {"SLH-DSA-SHAKE-256s", EVP_PKEY_SLH_DSA_SHAKE_256S}, +}; + +#endif + +// EVP_PKEY_CTX_set_dsa_paramgen_q_bits was added in OpenSSL 1.1.1e. +#if OPENSSL_VERSION_NUMBER < 0x1010105fL +#define EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits) \ + EVP_PKEY_CTX_ctrl((ctx), EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, (qbits), nullptr) +#endif + +namespace ncrypto { +namespace { + using BignumCtxPointer = DeleteFnPtr; + using BignumGenCallbackPointer = DeleteFnPtr; + using NetscapeSPKIPointer = DeleteFnPtr; + + static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON = XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB & ~ASN1_STRFLGS_ESC_CTRL; +} // namespace + +// ============================================================================ + +ClearErrorOnReturn::ClearErrorOnReturn(CryptoErrorList* errors) : errors_(errors) { + ERR_clear_error(); +} + +ClearErrorOnReturn::~ClearErrorOnReturn() { + if (errors_ != nullptr) + errors_->capture(); + ERR_clear_error(); +} + +int ClearErrorOnReturn::peekError() { + return ERR_peek_error(); +} + +MarkPopErrorOnReturn::MarkPopErrorOnReturn(CryptoErrorList* errors) : errors_(errors) { + ERR_set_mark(); +} + +MarkPopErrorOnReturn::~MarkPopErrorOnReturn() { + if (errors_ != nullptr) + errors_->capture(); + ERR_pop_to_mark(); +} + +int MarkPopErrorOnReturn::peekError() { + return ERR_peek_error(); +} + +CryptoErrorList::CryptoErrorList(CryptoErrorList::Option option) { + if (option == Option::CAPTURE_ON_CONSTRUCT) + capture(); +} + +void CryptoErrorList::capture() { + errors_.clear(); + while (const auto err = ERR_get_error()) { + char buf[256]; + ERR_error_string_n(err, buf, sizeof(buf)); + errors_.emplace_front(buf); + } +} + +void CryptoErrorList::add(std::string error) { + errors_.push_back(error); +} + +std::optional CryptoErrorList::pop_back() { + if (errors_.empty()) + return std::nullopt; + std::string error = errors_.back(); + errors_.pop_back(); + return error; +} + +std::optional CryptoErrorList::pop_front() { + if (errors_.empty()) + return std::nullopt; + std::string error = errors_.front(); + errors_.pop_front(); + return error; +} + +// ============================================================================ +DataPointer DataPointer::Alloc(size_t len) { +#ifdef OPENSSL_IS_BORINGSSL + // Boringssl does not implement OPENSSL_zalloc + auto ptr = OPENSSL_malloc(len); + if (ptr == nullptr) + return {}; + memset(ptr, 0, len); + return DataPointer(ptr, len); +#else + return DataPointer(OPENSSL_zalloc(len), len); +#endif +} + +DataPointer DataPointer::SecureAlloc(size_t len) { +#ifndef OPENSSL_IS_BORINGSSL + auto ptr = OPENSSL_secure_zalloc(len); + if (ptr == nullptr) + return {}; + return DataPointer(ptr, len, true); +#else + // BoringSSL does not implement the OPENSSL_secure_zalloc API. + auto ptr = OPENSSL_malloc(len); + if (ptr == nullptr) + return {}; + memset(ptr, 0, len); + return DataPointer(ptr, len); +#endif +} + +size_t DataPointer::GetSecureHeapUsed() { +#ifndef OPENSSL_IS_BORINGSSL + return CRYPTO_secure_malloc_initialized() ? CRYPTO_secure_used() : 0; +#else + // BoringSSL does not have the secure heap and therefore + // will always return 0. + return 0; +#endif +} + +DataPointer::InitSecureHeapResult DataPointer::TryInitSecureHeap(size_t amount, size_t min) { +#ifndef OPENSSL_IS_BORINGSSL + switch (CRYPTO_secure_malloc_init(amount, min)) { + case 0: + return InitSecureHeapResult::FAILED; + case 2: + return InitSecureHeapResult::UNABLE_TO_MEMORY_MAP; + case 1: + return InitSecureHeapResult::OK; + default: + return InitSecureHeapResult::FAILED; + } +#else + // BoringSSL does not actually support the secure heap + return InitSecureHeapResult::FAILED; +#endif +} + +DataPointer DataPointer::Copy(const Buffer& buffer) { + return DataPointer(OPENSSL_memdup(buffer.data, buffer.len), buffer.len); +} + +DataPointer::DataPointer(void* data, size_t length, bool secure) : data_(data), len_(length), secure_(secure) {} + +DataPointer::DataPointer(const Buffer& buffer, bool secure) : data_(buffer.data), len_(buffer.len), secure_(secure) {} + +DataPointer::DataPointer(DataPointer&& other) noexcept : data_(other.data_), len_(other.len_), secure_(other.secure_) { + other.data_ = nullptr; + other.len_ = 0; + other.secure_ = false; +} + +DataPointer& DataPointer::operator=(DataPointer&& other) noexcept { + if (this == &other) + return *this; + this->~DataPointer(); + return *new (this) DataPointer(std::move(other)); +} + +DataPointer::~DataPointer() { + reset(); +} + +void DataPointer::zero() { + if (!data_) + return; + OPENSSL_cleanse(data_, len_); +} + +void DataPointer::free() { + if (data_ != nullptr) { + if (secure_) { + OPENSSL_secure_clear_free(data_, len_); + } else { + OPENSSL_clear_free(data_, len_); + } + } +} + +void DataPointer::reset(void* data, size_t length) { + free(); + data_ = data; + len_ = length; +} + +void DataPointer::reset(const Buffer& buffer) { + reset(buffer.data, buffer.len); +} + +Buffer DataPointer::release() { + Buffer buf{ + .data = data_, + .len = len_, + }; + data_ = nullptr; + len_ = 0; + return buf; +} + +DataPointer DataPointer::resize(size_t len) { + size_t actual_len = std::min(len_, len); + auto buf = release(); + if (actual_len == len_) + return DataPointer(buf.data, actual_len); + auto new_data = OPENSSL_realloc(buf.data, actual_len); + if (new_data == nullptr) { + free(); + return {}; + } + buf.data = new_data; + buf.len = actual_len; + return DataPointer(buf); +} + +// ============================================================================ +bool isFipsEnabled() { + ClearErrorOnReturn clear_error_on_return; +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_default_properties_is_fips_enabled(nullptr) == 1; +#else + return FIPS_mode() == 1; +#endif +} + +bool setFipsEnabled(bool enable, CryptoErrorList* errors) { + if (isFipsEnabled() == enable) + return true; + ClearErrorOnReturn clearErrorOnReturn(errors); +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1 && EVP_default_properties_is_fips_enabled(nullptr); +#else + return FIPS_mode_set(enable ? 1 : 0) == 1; +#endif +} + +bool testFipsEnabled() { + ClearErrorOnReturn clear_error_on_return; +#if OPENSSL_VERSION_MAJOR >= 3 + OSSL_PROVIDER* fips_provider = nullptr; + if (OSSL_PROVIDER_available(nullptr, "fips")) { + fips_provider = OSSL_PROVIDER_load(nullptr, "fips"); + } + if (fips_provider == nullptr) + return false; + int result = OSSL_PROVIDER_self_test(fips_provider); + OSSL_PROVIDER_unload(fips_provider); + return result; +#else +#ifdef OPENSSL_FIPS + return FIPS_selftest(); +#else // OPENSSL_FIPS + return false; +#endif // OPENSSL_FIPS +#endif +} + +// ============================================================================ +// Bignum +BignumPointer::BignumPointer(BIGNUM* bignum) : bn_(bignum) {} + +BignumPointer::BignumPointer(const unsigned char* data, size_t len) : BignumPointer(BN_bin2bn(data, len, nullptr)) {} + +BignumPointer::BignumPointer(BignumPointer&& other) noexcept : bn_(other.release()) {} + +BignumPointer BignumPointer::New() { + return BignumPointer(BN_new()); +} + +BignumPointer BignumPointer::NewSecure() { +#ifdef OPENSSL_IS_BORINGSSL + // Boringssl does not implement BN_secure_new. + return New(); +#else + return BignumPointer(BN_secure_new()); +#endif +} + +BignumPointer& BignumPointer::operator=(BignumPointer&& other) noexcept { + if (this == &other) + return *this; + this->~BignumPointer(); + return *new (this) BignumPointer(std::move(other)); +} + +BignumPointer::~BignumPointer() { + reset(); +} + +void BignumPointer::reset(BIGNUM* bn) { + bn_.reset(bn); +} + +void BignumPointer::reset(const unsigned char* data, size_t len) { + reset(BN_bin2bn(data, len, nullptr)); +} + +BIGNUM* BignumPointer::release() { + return bn_.release(); +} + +size_t BignumPointer::byteLength() const { + if (bn_ == nullptr) + return 0; + return BN_num_bytes(bn_.get()); +} + +size_t BignumPointer::bitLength() const { + if (bn_ == nullptr) + return 0; + return BN_num_bits(bn_.get()); +} + +DataPointer BignumPointer::encode() const { + return EncodePadded(bn_.get(), byteLength()); +} + +DataPointer BignumPointer::encodePadded(size_t size) const { + return EncodePadded(bn_.get(), size); +} + +size_t BignumPointer::encodeInto(unsigned char* out) const { + if (!bn_) + return 0; + return BN_bn2bin(bn_.get(), out); +} + +size_t BignumPointer::encodePaddedInto(unsigned char* out, size_t size) const { + if (!bn_) + return 0; + return BN_bn2binpad(bn_.get(), out, size); +} + +DataPointer BignumPointer::Encode(const BIGNUM* bn) { + return EncodePadded(bn, bn != nullptr ? BN_num_bytes(bn) : 0); +} + +bool BignumPointer::setWord(unsigned long w) { // NOLINT(runtime/int) + if (!bn_) + return false; + return BN_set_word(bn_.get(), w) == 1; +} + +unsigned long BignumPointer::GetWord(const BIGNUM* bn) { // NOLINT(runtime/int) + return BN_get_word(bn); +} + +unsigned long BignumPointer::getWord() const { // NOLINT(runtime/int) + if (!bn_) + return 0; + return GetWord(bn_.get()); +} + +DataPointer BignumPointer::EncodePadded(const BIGNUM* bn, size_t s) { + if (bn == nullptr) + return DataPointer(); + size_t size = std::max(s, static_cast(GetByteCount(bn))); + auto buf = DataPointer::Alloc(size); + BN_bn2binpad(bn, reinterpret_cast(buf.get()), size); + return buf; +} +size_t BignumPointer::EncodePaddedInto(const BIGNUM* bn, unsigned char* out, size_t size) { + if (bn == nullptr) + return 0; + return BN_bn2binpad(bn, out, size); +} + +int BignumPointer::operator<=>(const BignumPointer& other) const noexcept { + if (bn_ == nullptr && other.bn_ != nullptr) + return -1; + if (bn_ != nullptr && other.bn_ == nullptr) + return 1; + if (bn_ == nullptr && other.bn_ == nullptr) + return 0; + return BN_cmp(bn_.get(), other.bn_.get()); +} + +int BignumPointer::operator<=>(const BIGNUM* other) const noexcept { + if (bn_ == nullptr && other != nullptr) + return -1; + if (bn_ != nullptr && other == nullptr) + return 1; + if (bn_ == nullptr && other == nullptr) + return 0; + return BN_cmp(bn_.get(), other); +} + +DataPointer BignumPointer::toHex() const { + if (!bn_) + return {}; + char* hex = BN_bn2hex(bn_.get()); + if (!hex) + return {}; + return DataPointer(hex, strlen(hex)); +} + +int BignumPointer::GetBitCount(const BIGNUM* bn) { + return BN_num_bits(bn); +} + +int BignumPointer::GetByteCount(const BIGNUM* bn) { + return BN_num_bytes(bn); +} + +bool BignumPointer::isZero() const { + return bn_ && BN_is_zero(bn_.get()); +} + +bool BignumPointer::isOne() const { + return bn_ && BN_is_one(bn_.get()); +} + +const BIGNUM* BignumPointer::One() { + return BN_value_one(); +} + +BignumPointer BignumPointer::clone() { + if (!bn_) + return {}; + return BignumPointer(BN_dup(bn_.get())); +} + +int BignumPointer::isPrime(int nchecks, BignumPointer::PrimeCheckCallback innerCb) const { + BignumCtxPointer ctx(BN_CTX_new()); + BignumGenCallbackPointer cb(nullptr); + if (innerCb != nullptr) { + cb = BignumGenCallbackPointer(BN_GENCB_new()); + if (!cb) [[unlikely]] + return -1; + BN_GENCB_set( + cb.get(), + // TODO(@jasnell): This could be refactored to allow inlining. + // Not too important right now tho. + [](int a, int b, BN_GENCB* ctx) mutable -> int { + // BN_GENCB is opaque in OpenSSL 3.x, must use accessor + PrimeCheckCallback& ptr = *static_cast(BN_GENCB_get_arg(ctx)); + return ptr(a, b) ? 1 : 0; + }, + &innerCb); + } + const int minimum_checks = bitLength() > 2048 ? 128 : 64; + const int repetitions = nchecks > minimum_checks ? 1 + (nchecks - 1) / minimum_checks : 1; + for (int i = 0; i < repetitions; i++) { + const int result = BN_check_prime(get(), ctx.get(), cb.get()); + if (result != 1) + return result; + } + return 1; +} + +BignumPointer BignumPointer::NewPrime(const PrimeConfig& params, PrimeCheckCallback cb) { + BignumPointer prime(BN_new()); + if (!prime || !prime.generate(params, std::move(cb))) { + return {}; + } + return prime; +} + +bool BignumPointer::generate(const PrimeConfig& params, PrimeCheckCallback innerCb) const { + // BN_generate_prime_ex() calls RAND_bytes_ex() internally. + // Make sure the CSPRNG is properly seeded. + std::ignore = CSPRNG(nullptr, 0); + BignumGenCallbackPointer cb(nullptr); + if (innerCb != nullptr) { + cb = BignumGenCallbackPointer(BN_GENCB_new()); + if (!cb) [[unlikely]] + return -1; + BN_GENCB_set( + cb.get(), + [](int a, int b, BN_GENCB* ctx) mutable -> int { + // BN_GENCB is opaque in OpenSSL 3.x, must use accessor + PrimeCheckCallback& ptr = *static_cast(BN_GENCB_get_arg(ctx)); + return ptr(a, b) ? 1 : 0; + }, + &innerCb); + } + if (BN_generate_prime_ex(get(), params.bits, params.safe ? 1 : 0, params.add.get(), params.rem.get(), cb.get()) == 0) { + return false; + } + + return true; +} + +BignumPointer BignumPointer::NewSub(const BignumPointer& a, const BignumPointer& b) { + BignumPointer res = New(); + if (!res) + return {}; + if (!BN_sub(res.get(), a.get(), b.get())) { + return {}; + } + return res; +} + +BignumPointer BignumPointer::NewLShift(size_t length) { + BignumPointer res = New(); + if (!res) + return {}; + if (!BN_lshift(res.get(), One(), length)) { + return {}; + } + return res; +} + +// ============================================================================ +// Utility methods + +bool CSPRNG(void* buffer, size_t length) { + auto buf = reinterpret_cast(buffer); + do { + if (1 == RAND_status()) { +#if OPENSSL_VERSION_MAJOR >= 3 + if (1 == RAND_bytes_ex(nullptr, buf, length, 0)) { + return true; + } +#else + while (length > INT_MAX && 1 == RAND_bytes(buf, INT_MAX)) { + buf += INT_MAX; + length -= INT_MAX; + } + if (length <= INT_MAX && 1 == RAND_bytes(buf, static_cast(length))) + return true; +#endif + } +#if OPENSSL_VERSION_MAJOR >= 3 + const auto code = ERR_peek_last_error(); + // A misconfigured OpenSSL 3 installation may report 1 from RAND_poll() + // and RAND_status() but fail in RAND_bytes() if it cannot look up + // a matching algorithm for the CSPRNG. + if (ERR_GET_LIB(code) == ERR_LIB_RAND) { + const auto reason = ERR_GET_REASON(code); + if (reason == RAND_R_ERROR_INSTANTIATING_DRBG || reason == RAND_R_UNABLE_TO_FETCH_DRBG || reason == RAND_R_UNABLE_TO_CREATE_DRBG) { + return false; + } + } +#endif + } while (1 == RAND_poll()); + + return false; +} + +int NoPasswordCallback(char*, int, int, void*) { + return 0; +} + +int PasswordCallback(char* buf, int size, int, void* u) { + auto passphrase = static_cast*>(u); + if (passphrase != nullptr) { + size_t buflen = static_cast(size); + size_t len = passphrase->len; + if (buflen < len) + return -1; + memcpy(buf, reinterpret_cast(passphrase->data), len); + return len; + } + + return -1; +} + +// Algorithm: http://howardhinnant.github.io/date_algorithms.html +constexpr int days_from_epoch(int y, unsigned m, unsigned d) { + y -= m <= 2; + const int era = (y >= 0 ? y : y - 399) / 400; + const unsigned yoe = static_cast(y - era * 400); // [0, 399] + const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; // [0, 365] + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] + return era * 146097 + static_cast(doe) - 719468; +} + +#ifndef OPENSSL_IS_BORINGSSL +// tm must be in UTC +// using time_t causes problems on 32-bit systems and windows x64. +int64_t PortableTimeGM(struct tm* t) { + int year = t->tm_year + 1900; + int month = t->tm_mon; + if (month > 11) { + year += month / 12; + month %= 12; + } else if (month < 0) { + int years_diff = (11 - month) / 12; + year -= years_diff; + month += 12 * years_diff; + } + int days_since_epoch = days_from_epoch(year, month + 1, t->tm_mday); + + return 60 * (60 * (24LL * static_cast(days_since_epoch) + t->tm_hour) + t->tm_min) + t->tm_sec; +} +#endif + +// ============================================================================ +// SPKAC + +bool VerifySpkac(const char* input, size_t length) { +#ifdef OPENSSL_IS_BORINGSSL + // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, + // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. + // As such, we trim those characters here for compatibility. + // + // find_last_not_of can return npos, which is the maximum value of size_t. + // The + 1 will force a roll-ver to 0, which is the correct value. in that + // case. + length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; +#endif + NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length)); + if (!spki) + return false; + + EVPKeyPointer pkey(X509_PUBKEY_get(spki->spkac->pubkey)); + return pkey ? NETSCAPE_SPKI_verify(spki.get(), pkey.get()) > 0 : false; +} + +BIOPointer ExportPublicKey(const char* input, size_t length) { + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + +#ifdef OPENSSL_IS_BORINGSSL + // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, + // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. + // As such, we trim those characters here for compatibility. + length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; +#endif + NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length)); + if (!spki) + return {}; + + EVPKeyPointer pkey(NETSCAPE_SPKI_get_pubkey(spki.get())); + if (!pkey) + return {}; + + if (PEM_write_bio_PUBKEY(bio.get(), pkey.get()) <= 0) + return {}; + + return bio; +} + +Buffer ExportChallenge(const char* input, size_t length) { +#ifdef OPENSSL_IS_BORINGSSL + // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, + // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. + // As such, we trim those characters here for compatibility. + length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; +#endif + NetscapeSPKIPointer sp(NETSCAPE_SPKI_b64_decode(input, length)); + if (!sp) + return {}; + + unsigned char* buf = nullptr; + int buf_size = ASN1_STRING_to_UTF8(&buf, sp->spkac->challenge); + if (buf_size >= 0) { + return { + .data = reinterpret_cast(buf), + .len = static_cast(buf_size), + }; + } + + return {}; +} + +bool VerifySpkac(const Buffer& input) { + return VerifySpkac(input.data, input.len); +} + +BIOPointer ExportPublicKey(const Buffer& input) { + return ExportPublicKey(input.data, input.len); +} + +DataPointer ExportChallenge(const Buffer& input) { + auto buf = ExportChallenge(input.data, input.len); + if (buf.data != nullptr) { + return DataPointer(buf.data, buf.len); + } + return {}; +} + +// ============================================================================ +namespace { + enum class AltNameOption { + NONE, + UTF8, + }; + + bool IsSafeAltName(const char* name, size_t length, AltNameOption option) { + for (size_t i = 0; i < length; i++) { + char c = name[i]; + switch (c) { + case '"': + case '\\': + // These mess with encoding rules. + // Fall through. + case ',': + // Commas make it impossible to split the list of subject alternative + // names unambiguously, which is why we have to escape. + // Fall through. + case '\'': + // Single quotes are unlikely to appear in any legitimate values, but + // they could be used to make a value look like it was escaped (i.e., + // enclosed in single/double quotes). + return false; + default: + if (option == AltNameOption::UTF8) { + // In UTF8 strings, we require escaping for any ASCII control + // character, but NOT for non-ASCII characters. Note that all bytes of + // any code point that consists of more than a single byte have their + // MSB set. + if (static_cast(c) < ' ' || c == '\x7f') { + return false; + } + } else { + // Check if the char is a control character or non-ASCII character. + // Note that char may or may not be a signed type. Regardless, + // non-ASCII values will always be outside of this range. + if (c < ' ' || c > '~') { + return false; + } + } + } + } + return true; + } + + void PrintAltName(const BIOPointer& out, const char* name, size_t length, AltNameOption option = AltNameOption::NONE, + const char* safe_prefix = nullptr) { + if (IsSafeAltName(name, length, option)) { + // For backward-compatibility, append "safe" names without any + // modifications. + if (safe_prefix != nullptr) { + BIO_printf(out.get(), "%s:", safe_prefix); + } + BIO_write(out.get(), name, length); + } else { + // If a name is not "safe", we cannot embed it without special + // encoding. This does not usually happen, but we don't want to hide + // it from the user either. We use JSON compatible escaping here. + BIO_write(out.get(), "\"", 1); + if (safe_prefix != nullptr) { + BIO_printf(out.get(), "%s:", safe_prefix); + } + for (size_t j = 0; j < length; j++) { + char c = static_cast(name[j]); + if (c == '\\') { + BIO_write(out.get(), "\\\\", 2); + } else if (c == '"') { + BIO_write(out.get(), "\\\"", 2); + } else if ((c >= ' ' && c != ',' && c <= '~') || (option == AltNameOption::UTF8 && (c & 0x80))) { + // Note that the above condition explicitly excludes commas, which means + // that those are encoded as Unicode escape sequences in the "else" + // block. That is not strictly necessary, and Node.js itself would parse + // it correctly either way. We only do this to account for third-party + // code that might be splitting the string at commas (as Node.js itself + // used to do). + BIO_write(out.get(), &c, 1); + } else { + // Control character or non-ASCII character. We treat everything as + // Latin-1, which corresponds to the first 255 Unicode code points. + const char hex[] = "0123456789abcdef"; + char u[] = {'\\', 'u', '0', '0', hex[(c & 0xf0) >> 4], hex[c & 0x0f]}; + BIO_write(out.get(), u, sizeof(u)); + } + } + BIO_write(out.get(), "\"", 1); + } + } + + // This function emulates the behavior of i2v_GENERAL_NAME in a safer and less + // ambiguous way. "othername:" entries use the GENERAL_NAME_print format. + bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) { + if (gen->type == GEN_DNS) { + ASN1_IA5STRING* name = gen->d.dNSName; + BIO_write(out.get(), "DNS:", 4); + // Note that the preferred name syntax (see RFCs 5280 and 1034) with + // wildcards is a subset of what we consider "safe", so spec-compliant DNS + // names will never need to be escaped. + PrintAltName(out, reinterpret_cast(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); + } else if (gen->type == GEN_EMAIL) { + ASN1_IA5STRING* name = gen->d.rfc822Name; + BIO_write(out.get(), "email:", 6); + PrintAltName(out, reinterpret_cast(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); + } else if (gen->type == GEN_URI) { + ASN1_IA5STRING* name = gen->d.uniformResourceIdentifier; + BIO_write(out.get(), "URI:", 4); + // The set of "safe" names was designed to include just about any URI, + // with a few exceptions, most notably URIs that contains commas (see + // RFC 2396). In other words, most legitimate URIs will not require + // escaping. + PrintAltName(out, reinterpret_cast(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); + } else if (gen->type == GEN_DIRNAME) { + // Earlier versions of Node.js used X509_NAME_oneline to print the X509_NAME + // object. The format was non standard and should be avoided. The use of + // X509_NAME_oneline is discouraged by OpenSSL but was required for backward + // compatibility. Conveniently, X509_NAME_oneline produced ASCII and the + // output was unlikely to contains commas or other characters that would + // require escaping. However, it SHOULD NOT produce ASCII output since an + // RFC5280 AttributeValue may be a UTF8String. + // Newer versions of Node.js have since switched to X509_NAME_print_ex to + // produce a better format at the cost of backward compatibility. The new + // format may contain Unicode characters and it is likely to contain commas, + // which require escaping. Fortunately, the recently safeguarded function + // PrintAltName handles all of that safely. + BIO_printf(out.get(), "DirName:"); + BIOPointer tmp(BIO_new(BIO_s_mem())); + NCRYPTO_ASSERT_TRUE(tmp); + if (X509_NAME_print_ex(tmp.get(), gen->d.dirn, 0, kX509NameFlagsRFC2253WithinUtf8JSON) < 0) { + return false; + } + char* oline = nullptr; + long n_bytes = BIO_get_mem_data(tmp.get(), &oline); // NOLINT(runtime/int) + NCRYPTO_ASSERT_TRUE(n_bytes >= 0); + PrintAltName(out, oline, static_cast(n_bytes), ncrypto::AltNameOption::UTF8, nullptr); + } else if (gen->type == GEN_IPADD) { + BIO_printf(out.get(), "IP Address:"); + const ASN1_OCTET_STRING* ip = gen->d.ip; + const unsigned char* b = ASN1_STRING_get0_data(ip); + int ip_len = ASN1_STRING_length(ip); + if (ip_len == 4) { + BIO_printf(out.get(), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]); + } else if (ip_len == 16) { + for (unsigned int j = 0; j < 8; j++) { + uint16_t pair = (b[2 * j] << 8) | b[2 * j + 1]; + BIO_printf(out.get(), (j == 0) ? "%X" : ":%X", pair); + } + } else { +#if OPENSSL_VERSION_MAJOR >= 3 + BIO_printf(out.get(), "", ip_len); +#else + BIO_printf(out.get(), ""); +#endif + } + } else if (gen->type == GEN_RID) { + // Unlike OpenSSL's default implementation, never print the OID as text and + // instead always print its numeric representation. + char oline[256]; + OBJ_obj2txt(oline, sizeof(oline), gen->d.rid, true); + BIO_printf(out.get(), "Registered ID:%s", oline); + } else if (gen->type == GEN_OTHERNAME) { + // The format that is used here is based on OpenSSL's implementation of + // GENERAL_NAME_print (as of OpenSSL 3.0.1). Earlier versions of Node.js + // instead produced the same format as i2v_GENERAL_NAME, which was somewhat + // awkward, especially when passed to translatePeerCertificate. + bool unicode = true; + const char* prefix = nullptr; + // OpenSSL 1.1.1 does not support othername in GENERAL_NAME_print and may + // not define these NIDs. +#if OPENSSL_VERSION_MAJOR >= 3 + int nid = OBJ_obj2nid(gen->d.otherName->type_id); + switch (nid) { + case NID_id_on_SmtpUTF8Mailbox: + prefix = "SmtpUTF8Mailbox"; + break; + case NID_XmppAddr: + prefix = "XmppAddr"; + break; + case NID_SRVName: + prefix = "SRVName"; + unicode = false; + break; + case NID_ms_upn: + prefix = "UPN"; + break; + case NID_NAIRealm: + prefix = "NAIRealm"; + break; + } +#endif // OPENSSL_VERSION_MAJOR >= 3 + int val_type = gen->d.otherName->value->type; + if (prefix == nullptr || (unicode && val_type != V_ASN1_UTF8STRING) || (!unicode && val_type != V_ASN1_IA5STRING)) { + BIO_printf(out.get(), "othername:"); + } else { + BIO_printf(out.get(), "othername:"); + if (unicode) { + auto name = gen->d.otherName->value->value.utf8string; + PrintAltName(out, reinterpret_cast(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name), AltNameOption::UTF8, + prefix); + } else { + auto name = gen->d.otherName->value->value.ia5string; + PrintAltName(out, reinterpret_cast(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name), AltNameOption::NONE, + prefix); + } + } + } else if (gen->type == GEN_X400) { + // TODO(tniessen): this is what OpenSSL does, implement properly instead + BIO_printf(out.get(), "X400Name:"); + } else if (gen->type == GEN_EDIPARTY) { + // TODO(tniessen): this is what OpenSSL does, implement properly instead + BIO_printf(out.get(), "EdiPartyName:"); + } else { + // This is safe because X509V3_EXT_d2i would have returned nullptr in this + // case already. + unreachable(); + } + + return true; + } +} // namespace + +bool SafeX509SubjectAltNamePrint(const BIOPointer& out, const X509_EXTENSION* ext) { + // const_cast needed for OpenSSL < 4.0 which lacks const-correctness + auto* mext = const_cast(ext); + auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(mext)); + if (ret != NID_subject_alt_name) + return false; + + GENERAL_NAMES* names = static_cast(X509V3_EXT_d2i(mext)); + if (names == nullptr) + return false; + + bool ok = true; + + for (OPENSSL_SIZE_T i = 0; i < sk_GENERAL_NAME_num(names); i++) { + GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i); + + if (i != 0) + BIO_write(out.get(), ", ", 2); + + if (!(ok = ncrypto::PrintGeneralName(out, gen))) { + break; + } + } + sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); + + return ok; +} + +bool SafeX509InfoAccessPrint(const BIOPointer& out, const X509_EXTENSION* ext) { + // const_cast needed for OpenSSL < 4.0 which lacks const-correctness + auto* mext = const_cast(ext); + auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(mext)); + if (ret != NID_info_access) + return false; + + AUTHORITY_INFO_ACCESS* descs = static_cast(X509V3_EXT_d2i(mext)); + if (descs == nullptr) + return false; + + bool ok = true; + + for (OPENSSL_SIZE_T i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) { + ACCESS_DESCRIPTION* desc = sk_ACCESS_DESCRIPTION_value(descs, i); + + if (i != 0) + BIO_write(out.get(), "\n", 1); + + char objtmp[80]; + i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method); + BIO_printf(out.get(), "%s - ", objtmp); + if (!(ok = ncrypto::PrintGeneralName(out, desc->location))) { + break; + } + } + sk_ACCESS_DESCRIPTION_pop_free(descs, ACCESS_DESCRIPTION_free); + +#if OPENSSL_VERSION_MAJOR < 3 + BIO_write(out.get(), "\n", 1); +#endif + + return ok; +} + +// ============================================================================ +// X509Pointer + +X509Pointer::X509Pointer(X509* x509) : cert_(x509) {} + +X509Pointer::X509Pointer(X509Pointer&& other) noexcept : cert_(other.release()) {} + +X509Pointer& X509Pointer::operator=(X509Pointer&& other) noexcept { + if (this == &other) + return *this; + this->~X509Pointer(); + return *new (this) X509Pointer(std::move(other)); +} + +X509Pointer::~X509Pointer() { + reset(); +} + +void X509Pointer::reset(X509* x509) { + cert_.reset(x509); +} + +X509* X509Pointer::release() { + return cert_.release(); +} + +X509View X509Pointer::view() const { + return X509View(cert_.get()); +} + +BIOPointer X509View::toPEM() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + if (PEM_write_bio_X509(bio.get(), const_cast(cert_)) <= 0) + return {}; + return bio; +} + +BIOPointer X509View::toDER() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + if (i2d_X509_bio(bio.get(), const_cast(cert_)) <= 0) + return {}; + return bio; +} + +BIOPointer X509View::getSubject() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + if (X509_NAME_print_ex(bio.get(), X509_get_subject_name(cert_), 0, kX509NameFlagsMultiline) <= 0) { + return {}; + } + return bio; +} + +BIOPointer X509View::getSubjectAltName() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + int index = X509_get_ext_by_NID(cert_, NID_subject_alt_name, -1); + if (index < 0 || !SafeX509SubjectAltNamePrint(bio, X509_get_ext(cert_, index))) { + return {}; + } + return bio; +} + +BIOPointer X509View::getIssuer() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + if (X509_NAME_print_ex(bio.get(), X509_get_issuer_name(cert_), 0, kX509NameFlagsMultiline) <= 0) { + return {}; + } + return bio; +} + +BIOPointer X509View::getInfoAccess() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + int index = X509_get_ext_by_NID(cert_, NID_info_access, -1); + if (index < 0) + return {}; + if (!SafeX509InfoAccessPrint(bio, X509_get_ext(cert_, index))) { + return {}; + } + return bio; +} + +BIOPointer X509View::getValidFrom() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert_)); + return bio; +} + +BIOPointer X509View::getValidTo() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + BIOPointer bio(BIO_new(BIO_s_mem())); + if (!bio) + return {}; + ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert_)); + return bio; +} + +std::optional X509View::getSignatureAlgorithm() const { + if (cert_ == nullptr) + return std::nullopt; + int nid = X509_get_signature_nid(cert_); + if (nid == NID_undef) + return std::nullopt; + const char* ln = OBJ_nid2ln(nid); + if (ln == nullptr) + return std::nullopt; + return std::string_view(ln); +} + +std::optional X509View::getSignatureAlgorithmOID() const { + if (cert_ == nullptr) + return std::nullopt; + const X509_ALGOR* alg = nullptr; + X509_get0_signature(nullptr, &alg, cert_); + if (alg == nullptr) + return std::nullopt; + const ASN1_OBJECT* obj = nullptr; + X509_ALGOR_get0(&obj, nullptr, nullptr, alg); + if (obj == nullptr) + return std::nullopt; + std::array buf{}; + int len = OBJ_obj2txt(buf.data(), buf.size(), obj, 1); + if (len < 0 || static_cast(len) >= buf.size()) + return std::nullopt; + return std::string(buf.data(), static_cast(len)); +} + +int64_t X509View::getValidToTime() const { +#ifdef OPENSSL_IS_BORINGSSL +#ifndef NCRYPTO_NO_ASN1_TIME + // Boringssl does not implement ASN1_TIME_to_tm in a public way, + // and only recently added ASN1_TIME_to_posix. Some boringssl + // users on older version may still need to patch around this + // or use a different implementation. + int64_t tp; + ASN1_TIME_to_posix(X509_get0_notAfter(cert_), &tp); + return tp; +#else + // Older versions of Boringssl do not implement the ASN1_TIME_to_* + // version functions. For now, neither shall we. + return 0LL; +#endif // NCRYPTO_NO_ASN1_TIME +#else // OPENSSL_IS_BORINGSSL + struct tm tp; + ASN1_TIME_to_tm(X509_get0_notAfter(cert_), &tp); + return PortableTimeGM(&tp); +#endif +} + +int64_t X509View::getValidFromTime() const { +#ifdef OPENSSL_IS_BORINGSSL +#ifndef NCRYPTO_NO_ASN1_TIME + int64_t tp; + ASN1_TIME_to_posix(X509_get0_notBefore(cert_), &tp); + return tp; +#else + // Older versions of Boringssl do not implement the ASN1_TIME_to_* + // version functions. For now, neither shall we. + return 0LL; +#endif // NCRYPTO_NO_ASN1_TIME +#else + struct tm tp; + ASN1_TIME_to_tm(X509_get0_notBefore(cert_), &tp); + return PortableTimeGM(&tp); +#endif +} + +DataPointer X509View::getSerialNumber() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + if (ASN1_INTEGER* serial_number = X509_get_serialNumber(const_cast(cert_))) { + if (auto bn = BignumPointer(ASN1_INTEGER_to_BN(serial_number, nullptr))) { + return bn.toHex(); + } + } + return {}; +} + +Result X509View::getPublicKey() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return Result(EVPKeyPointer{}); + auto pkey = EVPKeyPointer(X509_get_pubkey(const_cast(cert_))); + if (!pkey) + return Result(ERR_get_error()); + return pkey; +} + +StackOfASN1 X509View::getKeyUsage() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return {}; + return StackOfASN1(static_cast(X509_get_ext_d2i(cert_, NID_ext_key_usage, nullptr, nullptr))); +} + +bool X509View::isCA() const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return false; + return X509_check_ca(const_cast(cert_)) == 1; +} + +bool X509View::isIssuedBy(const X509View& issuer) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr || issuer.cert_ == nullptr) + return false; + return X509_check_issued(const_cast(issuer.cert_), const_cast(cert_)) == X509_V_OK; +} + +bool X509View::checkPrivateKey(const EVPKeyPointer& pkey) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr || pkey == nullptr) + return false; + return X509_check_private_key(const_cast(cert_), pkey.get()) == 1; +} + +bool X509View::checkPublicKey(const EVPKeyPointer& pkey) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr || pkey == nullptr) + return false; + return X509_verify(const_cast(cert_), pkey.get()) == 1; +} + +X509View::CheckMatch X509View::checkHost(const std::string_view host, int flags, DataPointer* peerName) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return CheckMatch::NO_MATCH; + char* peername; + switch (X509_check_host(const_cast(cert_), host.data(), host.size(), flags, &peername)) { + case 0: + return CheckMatch::NO_MATCH; + case 1: { + if (peername != nullptr) { + DataPointer name(peername, strlen(peername)); + if (peerName != nullptr) + *peerName = std::move(name); + } + return CheckMatch::MATCH; + } + case -2: + return CheckMatch::INVALID_NAME; + default: + return CheckMatch::OPERATION_FAILED; + } +} + +X509View::CheckMatch X509View::checkEmail(const std::string_view email, int flags) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return CheckMatch::NO_MATCH; + switch (X509_check_email(const_cast(cert_), email.data(), email.size(), flags)) { + case 0: + return CheckMatch::NO_MATCH; + case 1: + return CheckMatch::MATCH; + case -2: + return CheckMatch::INVALID_NAME; + default: + return CheckMatch::OPERATION_FAILED; + } +} + +X509View::CheckMatch X509View::checkIp(const std::string_view ip, int flags) const { + ClearErrorOnReturn clearErrorOnReturn; + if (cert_ == nullptr) + return CheckMatch::NO_MATCH; + switch (X509_check_ip_asc(const_cast(cert_), ip.data(), flags)) { + case 0: + return CheckMatch::NO_MATCH; + case 1: + return CheckMatch::MATCH; + case -2: + return CheckMatch::INVALID_NAME; + default: + return CheckMatch::OPERATION_FAILED; + } +} + +std::optional X509View::getFingerprint(const Digest& method) const { + unsigned int md_size; + unsigned char md[EVP_MAX_MD_SIZE]; + static constexpr char hex[] = "0123456789ABCDEF"; + + if (X509_digest(get(), method, md, &md_size)) { + if (md_size == 0) + return std::nullopt; + std::string fingerprint((md_size * 3) - 1, 0); + for (unsigned int i = 0; i < md_size; i++) { + auto idx = 3 * i; + fingerprint[idx] = hex[(md[i] & 0xf0) >> 4]; + fingerprint[idx + 1] = hex[(md[i] & 0x0f)]; + if (i == md_size - 1) + break; + fingerprint[idx + 2] = ':'; + } + + return fingerprint; + } + + return std::nullopt; +} + +Result X509Pointer::Parse(Buffer buffer) { + ClearErrorOnReturn clearErrorOnReturn; + BIOPointer bio(BIO_new_mem_buf(buffer.data, buffer.len)); + if (!bio) + return Result(ERR_get_error()); + + X509Pointer pem(PEM_read_bio_X509_AUX(bio.get(), nullptr, NoPasswordCallback, nullptr)); + if (pem) + return Result(std::move(pem)); + BIO_reset(bio.get()); + + X509Pointer der(d2i_X509_bio(bio.get(), nullptr)); + if (der) + return Result(std::move(der)); + + return Result(ERR_get_error()); +} + +bool X509View::enumUsages(UsageCallback callback) const { + if (cert_ == nullptr) + return false; + StackOfASN1 eku(static_cast(X509_get_ext_d2i(cert_, NID_ext_key_usage, nullptr, nullptr))); + if (!eku) + return false; + const int count = sk_ASN1_OBJECT_num(eku.get()); + char buf[256]{}; + + for (int i = 0; i < count; i++) { + if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) { + callback(buf); + } + } + return true; +} + +// When adding or removing errors below, please also update the list in the API +// documentation. See the "OpenSSL Error Codes" section of doc/api/errors.md +// Also *please* update the respective section in doc/api/tls.md as well +const char* X509Pointer::ErrorCode(int32_t err) { // NOLINT(runtime/int) +#define CASE(CODE) \ + case X509_V_ERR_##CODE: \ + return #CODE; + switch (err) { + CASE(UNABLE_TO_GET_ISSUER_CERT) + CASE(UNABLE_TO_GET_CRL) + CASE(UNABLE_TO_DECRYPT_CERT_SIGNATURE) + CASE(UNABLE_TO_DECRYPT_CRL_SIGNATURE) + CASE(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY) + CASE(CERT_SIGNATURE_FAILURE) + CASE(CRL_SIGNATURE_FAILURE) + CASE(CERT_NOT_YET_VALID) + CASE(CERT_HAS_EXPIRED) + CASE(CRL_NOT_YET_VALID) + CASE(CRL_HAS_EXPIRED) + CASE(ERROR_IN_CERT_NOT_BEFORE_FIELD) + CASE(ERROR_IN_CERT_NOT_AFTER_FIELD) + CASE(ERROR_IN_CRL_LAST_UPDATE_FIELD) + CASE(ERROR_IN_CRL_NEXT_UPDATE_FIELD) + CASE(OUT_OF_MEM) + CASE(DEPTH_ZERO_SELF_SIGNED_CERT) + CASE(SELF_SIGNED_CERT_IN_CHAIN) + CASE(UNABLE_TO_GET_ISSUER_CERT_LOCALLY) + CASE(UNABLE_TO_VERIFY_LEAF_SIGNATURE) + CASE(CERT_CHAIN_TOO_LONG) + CASE(CERT_REVOKED) + CASE(INVALID_CA) + CASE(PATH_LENGTH_EXCEEDED) + CASE(INVALID_PURPOSE) + CASE(CERT_UNTRUSTED) + CASE(CERT_REJECTED) + CASE(HOSTNAME_MISMATCH) + } +#undef CASE + return "UNSPECIFIED"; +} + +std::optional X509Pointer::ErrorReason(int32_t err) { + if (err == X509_V_OK) + return std::nullopt; + return X509_verify_cert_error_string(err); +} + +// ============================================================================ +// BIOPointer + +BIOPointer::BIOPointer(BIO* bio) : bio_(bio) {} + +BIOPointer::BIOPointer(BIOPointer&& other) noexcept : bio_(other.release()) {} + +BIOPointer& BIOPointer::operator=(BIOPointer&& other) noexcept { + if (this == &other) + return *this; + this->~BIOPointer(); + return *new (this) BIOPointer(std::move(other)); +} + +BIOPointer::~BIOPointer() { + reset(); +} + +void BIOPointer::reset(BIO* bio) { + bio_.reset(bio); +} + +BIO* BIOPointer::release() { + return bio_.release(); +} + +bool BIOPointer::resetBio() const { + if (!bio_) + return 0; + return BIO_reset(bio_.get()) == 1; +} + +BIOPointer BIOPointer::NewMem() { + return BIOPointer(BIO_new(BIO_s_mem())); +} + +BIOPointer BIOPointer::NewSecMem() { +#ifdef OPENSSL_IS_BORINGSSL + // Boringssl does not implement the BIO_s_secmem API. + return BIOPointer(BIO_new(BIO_s_mem())); +#else + return BIOPointer(BIO_new(BIO_s_secmem())); +#endif +} + +BIOPointer BIOPointer::New(const BIO_METHOD* method) { + if (method == nullptr) + return {}; + return BIOPointer(BIO_new(method)); +} + +BIOPointer BIOPointer::New(const void* data, size_t len) { + return BIOPointer(BIO_new_mem_buf(data, len)); +} + +BIOPointer BIOPointer::NewFile(const char* filename, const char* mode) { + return BIOPointer(BIO_new_file(filename, mode)); +} + +BIOPointer BIOPointer::NewFp(FILE* fd, int close_flag) { + return BIOPointer(BIO_new_fp(fd, close_flag)); +} + +BIOPointer BIOPointer::New(const BIGNUM* bn) { + auto res = NewMem(); + if (!res || !BN_print(res.get(), bn)) + return {}; + return res; +} + +int BIOPointer::Write(BIOPointer* bio, std::string_view message) { + if (bio == nullptr || !*bio) + return 0; + return BIO_write(bio->get(), message.data(), message.size()); +} + +// ============================================================================ +// KDF + +const EVP_MD* getDigestByName(const char* name) { + // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1 + // exposed through the public API. + if (strcmp(name, "dss1") == 0 || strcmp(name, "DSS1") == 0) [[unlikely]] { + return EVP_sha1(); + } + return EVP_get_digestbyname(name); +} + +const EVP_CIPHER* getCipherByName(const char* name) { + return EVP_get_cipherbyname(name); +} + +bool checkHkdfLength(const Digest& md, size_t length) { + // HKDF-Expand computes up to 255 HMAC blocks, each having as many bits as + // the output of the hash function. 255 is a hard limit because HKDF appends + // an 8-bit counter to each HMAC'd message, starting at 1. + static constexpr size_t kMaxDigestMultiplier = 255; + size_t max_length = md.size() * kMaxDigestMultiplier; + if (length > max_length) + return false; + return true; +} + +bool hkdfInfo(const Digest& md, const Buffer& key, const Buffer& info, + const Buffer& salt, size_t length, Buffer* out) { + ClearErrorOnReturn clearErrorOnReturn; + + if (!checkHkdfLength(md, length) || info.len > INT_MAX || salt.len > INT_MAX) { + return false; + } + + std::string_view actual_salt; + static const char default_salt[EVP_MAX_MD_SIZE] = {0}; + if (salt.len > 0) { + actual_salt = {reinterpret_cast(salt.data), salt.len}; + } else { + actual_salt = {default_salt, static_cast(md.size())}; + } + +#ifdef OPENSSL_IS_BORINGSSL + if (out == nullptr || out->len != length) + return false; + return HKDF(out->data, length, md, key.data, key.len, reinterpret_cast(actual_salt.data()), actual_salt.size(), + info.data, info.len) == 1; +#else + auto ctx = EVPKeyCtxPointer::NewFromID(EVP_PKEY_HKDF); + // OpenSSL < 3.0.0 accepted only a void* as the argument of + // EVP_PKEY_CTX_set_hkdf_md. + const EVP_MD* md_ptr = md; + if (!ctx || !EVP_PKEY_derive_init(ctx.get()) || !EVP_PKEY_CTX_set_hkdf_md(ctx.get(), md_ptr) || + !EVP_PKEY_CTX_add1_hkdf_info(ctx.get(), info.data, info.len)) { + return false; + } + + // We do not use EVP_PKEY_HKDF_MODE_EXTRACT_AND_EXPAND because and instead + // implement the extraction step ourselves because EVP_PKEY_derive does not + // handle zero-length keys, which are required for Web Crypto. + // TODO(jasnell): Once OpenSSL 1.1.1 support is dropped completely, and once + // BoringSSL is confirmed to support it, we can hopefully drop this and use + // EVP_KDF directly which does support zero length keys. + unsigned char pseudorandom_key[EVP_MAX_MD_SIZE]; + unsigned pseudorandom_key_len = sizeof(pseudorandom_key); + + if (HMAC(md, actual_salt.data(), actual_salt.size(), key.data, key.len, pseudorandom_key, &pseudorandom_key_len) == nullptr) { + return false; + } + if (!EVP_PKEY_CTX_hkdf_mode(ctx.get(), EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) || + !EVP_PKEY_CTX_set1_hkdf_key(ctx.get(), pseudorandom_key, pseudorandom_key_len)) { + return false; + } + + if (out == nullptr || out->len != length) + return false; + + return EVP_PKEY_derive(ctx.get(), out->data, &length) > 0; +#endif +} + +DataPointer hkdf(const Digest& md, const Buffer& key, const Buffer& info, + const Buffer& salt, size_t length) { + auto buf = DataPointer::Alloc(length); + if (!buf) + return {}; + Buffer out{ + .data = static_cast(buf.get()), + .len = length, + }; + if (hkdfInfo(md, key, info, salt, length, &out)) { + return buf; + } + return {}; +} + +bool checkScryptParams(uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem) { + return EVP_PBE_scrypt(nullptr, 0, nullptr, 0, N, r, p, maxmem, nullptr, 0) == 1; +} + +bool scryptInto(const Buffer& pass, const Buffer& salt, uint64_t N, uint64_t r, uint64_t p, + uint64_t maxmem, size_t length, Buffer* out) { + ClearErrorOnReturn clearErrorOnReturn; + + if (pass.len > INT_MAX || salt.len > INT_MAX || out == nullptr) { + return false; + } + + return EVP_PBE_scrypt(pass.data, pass.len, salt.data, salt.len, N, r, p, maxmem, out->data, length) == 1; +} + +DataPointer scrypt(const Buffer& pass, const Buffer& salt, uint64_t N, uint64_t r, uint64_t p, + uint64_t maxmem, size_t length) { + ClearErrorOnReturn clearErrorOnReturn; + + if (pass.len > INT_MAX || salt.len > INT_MAX) { + return {}; + } + + auto dp = DataPointer::Alloc(length); + if (dp && EVP_PBE_scrypt(pass.data, pass.len, salt.data, salt.len, N, r, p, maxmem, reinterpret_cast(dp.get()), length)) { + return dp; + } + + return {}; +} + +bool pbkdf2Into(const Digest& md, const Buffer& pass, const Buffer& salt, uint32_t iterations, + size_t length, Buffer* out) { + ClearErrorOnReturn clearErrorOnReturn; + + if (pass.len > INT_MAX || salt.len > INT_MAX || length > INT_MAX || out == nullptr) { + return false; + } + + const EVP_MD* md_ptr = md; + return PKCS5_PBKDF2_HMAC(pass.data, pass.len, salt.data, salt.len, iterations, md_ptr, length, out->data) == 1; +} + +DataPointer pbkdf2(const Digest& md, const Buffer& pass, const Buffer& salt, uint32_t iterations, + size_t length) { + ClearErrorOnReturn clearErrorOnReturn; + + if (pass.len > INT_MAX || salt.len > INT_MAX || length > INT_MAX) { + return {}; + } + + auto dp = DataPointer::Alloc(length); + const EVP_MD* md_ptr = md; + if (dp && + PKCS5_PBKDF2_HMAC(pass.data, pass.len, salt.data, salt.len, iterations, md_ptr, length, reinterpret_cast(dp.get()))) { + return dp; + } + + return {}; +} + +#if OPENSSL_VERSION_NUMBER >= 0x30200000L +#ifndef OPENSSL_NO_ARGON2 +DataPointer argon2(const Buffer& pass, const Buffer& salt, uint32_t lanes, size_t length, uint32_t memcost, + uint32_t iter, uint32_t version, const Buffer& secret, const Buffer& ad, + Argon2Type type) { + ClearErrorOnReturn clearErrorOnReturn; + (void)version; + + std::string_view algorithm; + switch (type) { + case Argon2Type::ARGON2I: + algorithm = "ARGON2I"; + break; + case Argon2Type::ARGON2D: + algorithm = "ARGON2D"; + break; + case Argon2Type::ARGON2ID: + algorithm = "ARGON2ID"; + break; + default: + // Invalid Argon2 type + return {}; + } + + // creates a new library context to avoid locking when running concurrently + auto ctx = DeleteFnPtr{OSSL_LIB_CTX_new()}; + if (!ctx) { + return {}; + } + + // required if threads > 1 + if (lanes > 1 && OSSL_set_max_threads(ctx.get(), lanes) != 1) { + return {}; + } + + auto kdf = DeleteFnPtr{EVP_KDF_fetch(ctx.get(), algorithm.data(), nullptr)}; + if (!kdf) { + return {}; + } + + auto kctx = DeleteFnPtr{EVP_KDF_CTX_new(kdf.get())}; + if (!kctx) { + return {}; + } + + std::vector params; + params.reserve(9); + + params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, const_cast(pass.len > 0 ? pass.data : ""), pass.len)); + params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, const_cast(salt.data), salt.len)); + params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_THREADS, &lanes)); + params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES, &lanes)); + params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memcost)); + params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ITER, &iter)); + + if (ad.len != 0) { + params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_ARGON2_AD, const_cast(ad.data), ad.len)); + } + + if (secret.len != 0) { + params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, const_cast(secret.data), secret.len)); + } + + params.push_back(OSSL_PARAM_construct_end()); + + auto dp = DataPointer::Alloc(length); + if (dp && EVP_KDF_derive(kctx.get(), reinterpret_cast(dp.get()), length, params.data()) == 1) { + return dp; + } + + return {}; +} +#endif +#endif + +// ============================================================================ + +EVPKeyPointer::PrivateKeyEncodingConfig::PrivateKeyEncodingConfig(const PrivateKeyEncodingConfig& other) + : PrivateKeyEncodingConfig(other.output_key_object, other.format, other.type) { + cipher = other.cipher; + if (other.passphrase.has_value()) { + auto& otherPassphrase = other.passphrase.value(); + auto newPassphrase = DataPointer::Alloc(otherPassphrase.size()); + memcpy(newPassphrase.get(), otherPassphrase.get(), otherPassphrase.size()); + passphrase = std::move(newPassphrase); + } +} + +EVPKeyPointer::AsymmetricKeyEncodingConfig::AsymmetricKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type) + : output_key_object(output_key_object), format(format), type(type) {} + +EVPKeyPointer::PrivateKeyEncodingConfig& EVPKeyPointer::PrivateKeyEncodingConfig::operator=(const PrivateKeyEncodingConfig& other) { + if (this == &other) + return *this; + this->~PrivateKeyEncodingConfig(); + return *new (this) PrivateKeyEncodingConfig(other); +} + +EVPKeyPointer EVPKeyPointer::New() { + return EVPKeyPointer(EVP_PKEY_new()); +} + +EVPKeyPointer EVPKeyPointer::NewRawPublic(int id, const Buffer& data) { + if (id == 0) + return {}; + return EVPKeyPointer(EVP_PKEY_new_raw_public_key(id, nullptr, data.data, data.len)); +} + +EVPKeyPointer EVPKeyPointer::NewRawPrivate(int id, const Buffer& data) { + if (id == 0) + return {}; + return EVPKeyPointer(EVP_PKEY_new_raw_private_key(id, nullptr, data.data, data.len)); +} + +#if OPENSSL_WITH_PQC +EVPKeyPointer EVPKeyPointer::NewRawSeed(int id, const Buffer& data) { + if (id == 0) + return {}; + + OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_ML_DSA_SEED, const_cast(data.data), data.len), + OSSL_PARAM_END}; + + EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(id, nullptr); + if (ctx == nullptr) + return {}; + + EVP_PKEY* pkey = nullptr; + if (ctx == nullptr || EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) { + EVP_PKEY_CTX_free(ctx); + return {}; + } + + return EVPKeyPointer(pkey); +} +#endif + +EVPKeyPointer::EVPKeyPointer(EVP_PKEY* pkey) : pkey_(pkey) {} + +EVPKeyPointer::EVPKeyPointer(EVPKeyPointer&& other) noexcept : pkey_(other.release()) {} + +EVPKeyPointer& EVPKeyPointer::operator=(EVPKeyPointer&& other) noexcept { + if (this == &other) + return *this; + this->~EVPKeyPointer(); + return *new (this) EVPKeyPointer(std::move(other)); +} + +EVPKeyPointer::~EVPKeyPointer() { + reset(); +} + +void EVPKeyPointer::reset(EVP_PKEY* pkey) { + pkey_.reset(pkey); +} + +EVP_PKEY* EVPKeyPointer::release() { + return pkey_.release(); +} + +int EVPKeyPointer::id(const EVP_PKEY* key) { + if (key == nullptr) + return 0; + int type = EVP_PKEY_id(key); +#if OPENSSL_WITH_PQC + // EVP_PKEY_id returns -1 when EVP_PKEY_* is only implemented in a provider + // which is the case for all post-quantum NIST algorithms + // one suggested way would be to use a chain of `EVP_PKEY_is_a` + // https://github.com/openssl/openssl/issues/27738#issuecomment-3013215870 + // or, this way there are less calls to the OpenSSL provider, just + // getting the name once + if (type == -1) { + const char* type_name = EVP_PKEY_get0_type_name(key); + if (type_name == nullptr) + return -1; + + for (const auto& mapping : pqc_mappings) { + if (strcmp(type_name, mapping.name) == 0) { + return mapping.nid; + } + } + } +#endif + return type; +} + +int EVPKeyPointer::base_id(const EVP_PKEY* key) { + if (key == nullptr) + return 0; + return EVP_PKEY_base_id(key); +} + +int EVPKeyPointer::id() const { + return id(get()); +} + +int EVPKeyPointer::base_id() const { + return base_id(get()); +} + +int EVPKeyPointer::bits() const { + if (get() == nullptr) + return 0; + return EVP_PKEY_bits(get()); +} + +size_t EVPKeyPointer::size() const { + if (get() == nullptr) + return 0; + return EVP_PKEY_size(get()); +} + +EVPKeyCtxPointer EVPKeyPointer::newCtx() const { + if (!pkey_) + return {}; + return EVPKeyCtxPointer::New(*this); +} + +size_t EVPKeyPointer::rawPublicKeySize() const { + if (!pkey_) + return 0; + size_t len = 0; + if (EVP_PKEY_get_raw_public_key(get(), nullptr, &len) == 1) + return len; + return 0; +} + +size_t EVPKeyPointer::rawPrivateKeySize() const { + if (!pkey_) + return 0; + size_t len = 0; + if (EVP_PKEY_get_raw_private_key(get(), nullptr, &len) == 1) + return len; + return 0; +} + +DataPointer EVPKeyPointer::rawPublicKey() const { + if (!pkey_) + return {}; + if (auto data = DataPointer::Alloc(rawPublicKeySize())) { + const Buffer buf = data; + size_t len = data.size(); + if (EVP_PKEY_get_raw_public_key(get(), buf.data, &len) != 1) + return {}; + return data; + } + return {}; +} + +#if OPENSSL_WITH_PQC +DataPointer EVPKeyPointer::rawSeed() const { + if (!pkey_) + return {}; + + // Determine seed length and parameter name based on key type + size_t seed_len; + const char* param_name; + + switch (id()) { + case EVP_PKEY_ML_DSA_44: + case EVP_PKEY_ML_DSA_65: + case EVP_PKEY_ML_DSA_87: + seed_len = 32; // ML-DSA uses 32-byte seeds + param_name = OSSL_PKEY_PARAM_ML_DSA_SEED; + break; + case EVP_PKEY_ML_KEM_512: + case EVP_PKEY_ML_KEM_768: + case EVP_PKEY_ML_KEM_1024: + seed_len = 64; // ML-KEM uses 64-byte seeds + param_name = OSSL_PKEY_PARAM_ML_KEM_SEED; + break; + default: + unreachable(); + } + + if (auto data = DataPointer::Alloc(seed_len)) { + const Buffer buf = data; + size_t len = data.size(); + + if (EVP_PKEY_get_octet_string_param(get(), param_name, buf.data, len, &seed_len) != 1) + return {}; + return data; + } + return {}; +} +#endif + +DataPointer EVPKeyPointer::rawPrivateKey() const { + if (!pkey_) + return {}; + if (auto data = DataPointer::Alloc(rawPrivateKeySize())) { + const Buffer buf = data; + size_t len = data.size(); + if (EVP_PKEY_get_raw_private_key(get(), buf.data, &len) != 1) + return {}; + return data; + } + return {}; +} + +BIOPointer EVPKeyPointer::derPublicKey() const { + if (!pkey_) + return {}; + auto bio = BIOPointer::NewMem(); + if (!bio) + return {}; + if (!i2d_PUBKEY_bio(bio.get(), get())) + return {}; + return bio; +} + +namespace { + EVPKeyPointer::ParseKeyResult TryParsePublicKeyInner(const BIOPointer& bp, const char* name, auto&& parse) { + if (!bp.resetBio()) { + return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::FAILED); + } + unsigned char* der_data; + long der_len; // NOLINT(runtime/int) + + // This skips surrounding data and decodes PEM to DER. + { + MarkPopErrorOnReturn mark_pop_error_on_return; + if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name, bp.get(), nullptr, nullptr) != 1) + return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::NOT_RECOGNIZED); + } + DataPointer data(der_data, der_len); + + // OpenSSL might modify the pointer, so we need to make a copy before parsing. + const unsigned char* p = der_data; + EVPKeyPointer pkey(parse(&p, der_len)); + if (!pkey) + return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::FAILED); + return EVPKeyPointer::ParseKeyResult(std::move(pkey)); + } + + constexpr bool IsASN1Sequence(const unsigned char* data, size_t size, size_t* data_offset, size_t* data_size) { + if (size < 2 || data[0] != 0x30) + return false; + + if (data[1] & 0x80) { + // Long form. + size_t n_bytes = data[1] & ~0x80; + if (n_bytes + 2 > size || n_bytes > sizeof(size_t)) + return false; + size_t length = 0; + for (size_t i = 0; i < n_bytes; i++) + length = (length << 8) | data[i + 2]; + *data_offset = 2 + n_bytes; + *data_size = std::min(size - 2 - n_bytes, length); + } else { + // Short form. + *data_offset = 2; + *data_size = std::min(size - 2, data[1]); + } + + return true; + } + + constexpr bool IsEncryptedPrivateKeyInfo(const Buffer& buffer) { + // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE. + if (buffer.len == 0 || buffer.data == nullptr) + return false; + size_t offset, len; + if (!IsASN1Sequence(buffer.data, buffer.len, &offset, &len)) + return false; + + // A PrivateKeyInfo sequence always starts with an integer whereas an + // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier. + return len >= 1 && buffer.data[offset] != 2; + } + +} // namespace + +bool EVPKeyPointer::IsRSAPrivateKey(const Buffer& buffer) { + // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE. + size_t offset, len; + if (!IsASN1Sequence(buffer.data, buffer.len, &offset, &len)) + return false; + + // An RSAPrivateKey sequence always starts with a single-byte integer whose + // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus + // (which is the product of two primes and therefore at least 4), so we can + // decide the type of the structure based on the first three bytes of the + // sequence. + return len >= 3 && buffer.data[offset] == 2 && buffer.data[offset + 1] == 1 && !(buffer.data[offset + 2] & 0xfe); +} + +EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKeyPEM(const Buffer& buffer) { + auto bp = BIOPointer::New(buffer.data, buffer.len); + if (!bp) + return ParseKeyResult(PKParseError::FAILED); + + // Try parsing as SubjectPublicKeyInfo (SPKI) first. + if (auto ret = TryParsePublicKeyInner(bp, "PUBLIC KEY", [](const unsigned char** p, long l) { // NOLINT(runtime/int) + return d2i_PUBKEY(nullptr, p, l); + })) { + return ret; + } + + // Maybe it is PKCS#1. + if (auto ret = TryParsePublicKeyInner(bp, "RSA PUBLIC KEY", [](const unsigned char** p, long l) { // NOLINT(runtime/int) + return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l); + })) { + return ret; + } + + // X.509 fallback. + if (auto ret = TryParsePublicKeyInner(bp, "CERTIFICATE", [](const unsigned char** p, long l) { // NOLINT(runtime/int) + X509Pointer x509(d2i_X509(nullptr, p, l)); + return x509 ? X509_get_pubkey(x509.get()) : nullptr; + })) { + return ret; + }; + + return ParseKeyResult(PKParseError::NOT_RECOGNIZED); +} + +EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKey(const PublicKeyEncodingConfig& config, + const Buffer& buffer) { + if (config.format == PKFormatType::PEM) { + return TryParsePublicKeyPEM(buffer); + } + + if (config.format != PKFormatType::DER) { + return ParseKeyResult(PKParseError::FAILED); + } + + const unsigned char* start = buffer.data; + + EVP_PKEY* key = nullptr; + + if (config.type == PKEncodingType::PKCS1 && (key = d2i_PublicKey(EVP_PKEY_RSA, nullptr, &start, buffer.len))) { + return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); + } + + if (config.type == PKEncodingType::SPKI && (key = d2i_PUBKEY(nullptr, &start, buffer.len))) { + return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); + } + + return ParseKeyResult(PKParseError::FAILED); +} + +namespace { + Buffer GetPassphrase(const EVPKeyPointer::PrivateKeyEncodingConfig& config) { + static char empty_passphrase; + Buffer pass{ + .data = &empty_passphrase, + .len = 0, + }; + if (config.passphrase.has_value()) { + auto& passphrase = config.passphrase.value(); + // The pass.data can't be a nullptr, even if the len is zero or else + // openssl will prompt for a password and we really don't want that. + if (passphrase.get() != nullptr) { + pass.data = static_cast(passphrase.get()); + } + pass.len = passphrase.size(); + } + return pass; + } + + using EncoderCtxPointer = DeleteFnPtr; + + bool EncodeTraditionalPemWithEmptyPassphrase(const EVP_PKEY* key, BIO* bio, int selection, const char* structure, + const EVP_CIPHER* cipher) { + BIOPointer der = BIOPointer::NewMem(); + EncoderCtxPointer encoder(OSSL_ENCODER_CTX_new_for_pkey(key, selection, "DER", structure, nullptr)); + if (!der || !encoder || OSSL_ENCODER_CTX_get_num_encoders(encoder.get()) == 0 || OSSL_ENCODER_to_bio(encoder.get(), der.get()) != 1) { + return false; + } + + BUF_MEM* der_data = der; + const int iv_length = EVP_CIPHER_get_iv_length(cipher); + const int key_length = EVP_CIPHER_get_key_length(cipher); + const int block_size = EVP_CIPHER_get_block_size(cipher); + if (der_data == nullptr || der_data->length > INT_MAX || iv_length <= 0 || iv_length > EVP_MAX_IV_LENGTH || key_length <= 0 || + key_length > EVP_MAX_KEY_LENGTH || block_size <= 0 || der_data->length > static_cast(INT_MAX - block_size)) { + return false; + } + + std::array iv{}; + auto derived_key = DataPointer::SecureAlloc(key_length); + auto encrypted = DataPointer::Alloc(der_data->length + block_size); + auto ctx = CipherCtxPointer::New(); + const unsigned char empty_passphrase = 0; + if (!derived_key || !encrypted || !ctx || RAND_bytes(iv.data(), iv_length) != 1 || + EVP_BytesToKey(cipher, EVP_md5(), iv.data(), &empty_passphrase, 0, 1, derived_key.get(), nullptr) != key_length || + EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, derived_key.get(), iv.data()) != 1) { + return false; + } + + int encrypted_length = 0; + int final_length = 0; + if (EVP_EncryptUpdate(ctx.get(), encrypted.get(), &encrypted_length, + reinterpret_cast(der_data->data), static_cast(der_data->length)) != 1 || + EVP_EncryptFinal_ex(ctx.get(), encrypted.get() + encrypted_length, &final_length) != 1) { + return false; + } + + const char* pem_name; + switch (EVP_PKEY_get_id(key)) { + case EVP_PKEY_RSA: + pem_name = "RSA PRIVATE KEY"; + break; + case EVP_PKEY_EC: + pem_name = "EC PRIVATE KEY"; + break; + default: + return false; + } + + const char* cipher_name = EVP_CIPHER_get0_name(cipher); + if (cipher_name == nullptr) + return false; + std::array header{}; + PEM_proc_type(header.data(), PEM_TYPE_ENCRYPTED); + PEM_dek_info(header.data(), cipher_name, iv_length, reinterpret_cast(iv.data())); + return PEM_write_bio(bio, pem_name, header.data(), encrypted.get(), encrypted_length + final_length) > 0; + } + + bool EncodeKey(const EVP_PKEY* key, BIO* bio, int selection, EVPKeyPointer::PKFormatType format, const char* structure, + const EVP_CIPHER* cipher = nullptr, Buffer passphrase = {}) { + const char* output_type; + switch (format) { + case EVPKeyPointer::PKFormatType::PEM: + output_type = "PEM"; + break; + case EVPKeyPointer::PKFormatType::DER: + output_type = "DER"; + break; + default: + return false; + } + + EncoderCtxPointer ctx(OSSL_ENCODER_CTX_new_for_pkey(key, selection, output_type, structure, nullptr)); + if (!ctx || OSSL_ENCODER_CTX_get_num_encoders(ctx.get()) == 0) + return false; + + if (cipher != nullptr) { + if (passphrase.len == 0) { + // Provider PEM encoding rejects an empty password before encryption. + // Provider DER plus EVP framing preserves the traditional PEM behavior. + return EncodeTraditionalPemWithEmptyPassphrase(key, bio, selection, structure, cipher); + } + const char* cipher_name = EVP_CIPHER_get0_name(cipher); + if (cipher_name == nullptr || OSSL_ENCODER_CTX_set_cipher(ctx.get(), cipher_name, nullptr) != 1 || + OSSL_ENCODER_CTX_set_passphrase(ctx.get(), reinterpret_cast(passphrase.data), passphrase.len) != 1) { + return false; + } + } + + return OSSL_ENCODER_to_bio(ctx.get(), bio) == 1; + } +} // namespace + +EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePrivateKey(const PrivateKeyEncodingConfig& config, + const Buffer& buffer) { + static constexpr auto keyOrError = [](EVPKeyPointer pkey, bool had_passphrase = false) { + if (int err = ERR_peek_error()) { + if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ && !had_passphrase) { + return ParseKeyResult(PKParseError::NEED_PASSPHRASE); + } + return ParseKeyResult(PKParseError::FAILED, err); + } + if (!pkey) + return ParseKeyResult(PKParseError::FAILED); + return ParseKeyResult(std::move(pkey)); + }; + + auto bio = BIOPointer::New(buffer); + if (!bio) + return ParseKeyResult(PKParseError::FAILED); + + auto passphrase = GetPassphrase(config); + + if (config.format == PKFormatType::PEM) { + auto key = PEM_read_bio_PrivateKey(bio.get(), nullptr, PasswordCallback, config.passphrase.has_value() ? &passphrase : nullptr); + return keyOrError(EVPKeyPointer(key), config.passphrase.has_value()); + } + + if (config.format != PKFormatType::DER) { + return ParseKeyResult(PKParseError::FAILED); + } + + switch (config.type) { + case PKEncodingType::PKCS1: { + auto key = d2i_PrivateKey_bio(bio.get(), nullptr); + return keyOrError(EVPKeyPointer(key)); + } + case PKEncodingType::PKCS8: { + if (IsEncryptedPrivateKeyInfo(buffer)) { + auto key = d2i_PKCS8PrivateKey_bio(bio.get(), nullptr, PasswordCallback, config.passphrase.has_value() ? &passphrase : nullptr); + return keyOrError(EVPKeyPointer(key), config.passphrase.has_value()); + } + + PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr)); + if (!p8inf) { + return ParseKeyResult(PKParseError::FAILED, ERR_peek_error()); + } + return keyOrError(EVPKeyPointer(EVP_PKCS82PKEY(p8inf.get()))); + } + case PKEncodingType::SEC1: { + auto key = d2i_PrivateKey_bio(bio.get(), nullptr); + return keyOrError(EVPKeyPointer(key)); + } + default: { + return ParseKeyResult(PKParseError::FAILED, ERR_peek_error()); + } + }; +} + +Result EVPKeyPointer::writePrivateKey(const PrivateKeyEncodingConfig& config) const { + if (config.format == PKFormatType::JWK) { + return Result(false); + } + + auto bio = BIOPointer::NewMem(); + if (!bio) { + return Result(false); + } + + auto passphrase = GetPassphrase(config); + MarkPopErrorOnReturn mark_pop_error_on_return; + bool err; + + switch (config.type) { + case PKEncodingType::PKCS1: { + // PKCS1 is only permitted for RSA keys. + if (id() != EVP_PKEY_RSA) + return Result(false); + const EVP_CIPHER* cipher = config.format == PKFormatType::PEM ? config.cipher : nullptr; + err = !EncodeKey(get(), bio.get(), EVP_PKEY_KEYPAIR, config.format, "type-specific", cipher, passphrase); + break; + } + case PKEncodingType::PKCS8: { + switch (config.format) { + case PKFormatType::PEM: { + // Encode PKCS#8 as PEM. + err = PEM_write_bio_PKCS8PrivateKey(bio.get(), get(), config.cipher, passphrase.data, passphrase.len, nullptr, nullptr) != 1; + break; + } + case PKFormatType::DER: { + err = i2d_PKCS8PrivateKey_bio(bio.get(), get(), config.cipher, passphrase.data, passphrase.len, nullptr, nullptr) != 1; + break; + } + default: { + // Should never get here. + return Result(false); + } + } + break; + } + case PKEncodingType::SEC1: { + // SEC1 is only permitted for EC keys + if (id() != EVP_PKEY_EC) + return Result(false); + const EVP_CIPHER* cipher = config.format == PKFormatType::PEM ? config.cipher : nullptr; + err = !EncodeKey(get(), bio.get(), EVP_PKEY_KEYPAIR, config.format, "type-specific", cipher, passphrase); + break; + } + default: { + // Not a valid private key encoding + return Result(false); + } + } + + if (err) { + // Failed to encode the private key. + return Result(false, mark_pop_error_on_return.peekError()); + } + + return bio; +} + +Result EVPKeyPointer::writePublicKey(const ncrypto::EVPKeyPointer::PublicKeyEncodingConfig& config) const { + auto bio = BIOPointer::NewMem(); + if (!bio) + return Result(false); + + MarkPopErrorOnReturn mark_pop_error_on_return; + + if (config.type == ncrypto::EVPKeyPointer::PKEncodingType::PKCS1) { + // PKCS#1 is only valid for RSA keys. + if (id() != EVP_PKEY_RSA || !EncodeKey(get(), bio.get(), EVP_PKEY_PUBLIC_KEY, config.format, "type-specific")) { + return Result(false, mark_pop_error_on_return.peekError()); + } + return bio; + } + + if (config.format == ncrypto::EVPKeyPointer::PKFormatType::PEM) { + // Encode SPKI as PEM. + if (PEM_write_bio_PUBKEY(bio.get(), get()) != 1) { + return Result(false, mark_pop_error_on_return.peekError()); + } + return bio; + } + + // Encode SPKI as DER. + if (i2d_PUBKEY_bio(bio.get(), get()) != 1) { + return Result(false, mark_pop_error_on_return.peekError()); + } + return bio; +} + +bool EVPKeyPointer::isRsaVariant() const { + if (!pkey_) + return false; + int type = id(); + return type == EVP_PKEY_RSA || type == EVP_PKEY_RSA2 || type == EVP_PKEY_RSA_PSS; +} + +bool EVPKeyPointer::isOneShotVariant() const { + if (!pkey_) + return false; + int type = id(); + switch (type) { + case EVP_PKEY_ED25519: + case EVP_PKEY_ED448: +#if OPENSSL_WITH_PQC + case EVP_PKEY_ML_DSA_44: + case EVP_PKEY_ML_DSA_65: + case EVP_PKEY_ML_DSA_87: + case EVP_PKEY_SLH_DSA_SHA2_128F: + case EVP_PKEY_SLH_DSA_SHA2_128S: + case EVP_PKEY_SLH_DSA_SHA2_192F: + case EVP_PKEY_SLH_DSA_SHA2_192S: + case EVP_PKEY_SLH_DSA_SHA2_256F: + case EVP_PKEY_SLH_DSA_SHA2_256S: + case EVP_PKEY_SLH_DSA_SHAKE_128F: + case EVP_PKEY_SLH_DSA_SHAKE_128S: + case EVP_PKEY_SLH_DSA_SHAKE_192F: + case EVP_PKEY_SLH_DSA_SHAKE_192S: + case EVP_PKEY_SLH_DSA_SHAKE_256F: + case EVP_PKEY_SLH_DSA_SHAKE_256S: +#endif + return true; + default: + return false; + } +} + +bool EVPKeyPointer::isSigVariant() const { + if (!pkey_) + return false; + int type = id(); + return type == EVP_PKEY_EC || type == EVP_PKEY_DSA; +} + +int EVPKeyPointer::getDefaultSignPadding() const { + return id() == EVP_PKEY_RSA_PSS ? RSA_PKCS1_PSS_PADDING : RSA_PKCS1_PADDING; +} + +std::optional EVPKeyPointer::getBytesOfRS() const { + if (!pkey_) + return std::nullopt; + const char* parameter; + + switch (base_id()) { + case EVP_PKEY_DSA: + parameter = OSSL_PKEY_PARAM_FFC_Q; + break; + case EVP_PKEY_EC: + parameter = OSSL_PKEY_PARAM_EC_ORDER; + break; + default: + return std::nullopt; + } + + BIGNUM* raw = nullptr; + if (EVP_PKEY_get_bn_param(get(), parameter, &raw) != 1) { + return std::nullopt; + } + BignumPointer value(raw); + return (value.bitLength() + 7) / 8; +} + +EVPKeyPointer EVPKeyPointer::clone() const { + if (!pkey_) + return {}; + if (!EVP_PKEY_up_ref(pkey_.get())) + return {}; + return EVPKeyPointer(pkey_.get()); +} + +bool EVPKeyPointer::validateDsaParameters() const { + if (!pkey_) + return false; + if (EVP_default_properties_is_fips_enabled(nullptr) && EVP_PKEY_DSA == id()) { + BIGNUM* raw_p = nullptr; + BIGNUM* raw_q = nullptr; + if (EVP_PKEY_get_bn_param(get(), OSSL_PKEY_PARAM_FFC_P, &raw_p) != 1 || + EVP_PKEY_get_bn_param(get(), OSSL_PKEY_PARAM_FFC_Q, &raw_q) != 1) { + BN_clear_free(raw_p); + BN_clear_free(raw_q); + return false; + } + BignumPointer p(raw_p); + BignumPointer q(raw_q); + int L = p.bitLength(); + int N = q.bitLength(); + + return (L == 1024 && N == 160) || (L == 2048 && N == 224) || (L == 2048 && N == 256) || (L == 3072 && N == 256); + } + + return true; +} + +// ============================================================================ + +const Cipher Cipher::FromName(const char* name) { + return Cipher(EVP_get_cipherbyname(name)); +} + +const Cipher Cipher::FromNid(int nid) { + return Cipher(EVP_get_cipherbynid(nid)); +} + +const Cipher Cipher::FromCtx(const CipherCtxPointer& ctx) { + return Cipher(EVP_CIPHER_CTX_cipher(ctx.get())); +} + +const Cipher Cipher::EMPTY = Cipher(); +const Cipher Cipher::AES_128_CBC = Cipher::FromNid(NID_aes_128_cbc); +const Cipher Cipher::AES_192_CBC = Cipher::FromNid(NID_aes_192_cbc); +const Cipher Cipher::AES_256_CBC = Cipher::FromNid(NID_aes_256_cbc); +const Cipher Cipher::AES_128_CTR = Cipher::FromNid(NID_aes_128_ctr); +const Cipher Cipher::AES_192_CTR = Cipher::FromNid(NID_aes_192_ctr); +const Cipher Cipher::AES_256_CTR = Cipher::FromNid(NID_aes_256_ctr); +const Cipher Cipher::AES_128_GCM = Cipher::FromNid(NID_aes_128_gcm); +const Cipher Cipher::AES_192_GCM = Cipher::FromNid(NID_aes_192_gcm); +const Cipher Cipher::AES_256_GCM = Cipher::FromNid(NID_aes_256_gcm); +const Cipher Cipher::AES_128_KW = Cipher::FromNid(NID_id_aes128_wrap); +const Cipher Cipher::AES_192_KW = Cipher::FromNid(NID_id_aes192_wrap); +const Cipher Cipher::AES_256_KW = Cipher::FromNid(NID_id_aes256_wrap); + +#ifndef OPENSSL_IS_BORINGSSL +const Cipher Cipher::AES_128_OCB = Cipher::FromNid(NID_aes_128_ocb); +const Cipher Cipher::AES_192_OCB = Cipher::FromNid(NID_aes_192_ocb); +const Cipher Cipher::AES_256_OCB = Cipher::FromNid(NID_aes_256_ocb); +#endif + +const Cipher Cipher::CHACHA20_POLY1305 = Cipher::FromNid(NID_chacha20_poly1305); + +bool Cipher::isGcmMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_GCM_MODE; +} + +bool Cipher::isWrapMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_WRAP_MODE; +} + +bool Cipher::isCtrMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_CTR_MODE; +} + +bool Cipher::isCcmMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_CCM_MODE; +} + +bool Cipher::isOcbMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_OCB_MODE; +} + +bool Cipher::isStreamMode() const { + if (!cipher_) + return false; + return getMode() == EVP_CIPH_STREAM_CIPHER; +} + +bool Cipher::isChaCha20Poly1305() const { + if (!cipher_) + return false; + return getNid() == NID_chacha20_poly1305; +} + +int Cipher::getMode() const { + if (!cipher_) + return 0; + return EVP_CIPHER_mode(cipher_); +} + +int Cipher::getIvLength() const { + if (!cipher_) + return 0; + return EVP_CIPHER_iv_length(cipher_); +} + +int Cipher::getKeyLength() const { + if (!cipher_) + return 0; + return EVP_CIPHER_key_length(cipher_); +} + +int Cipher::getBlockSize() const { + if (!cipher_) + return 0; + return EVP_CIPHER_block_size(cipher_); +} + +int Cipher::getNid() const { + if (!cipher_) + return 0; + return EVP_CIPHER_nid(cipher_); +} + +std::string_view Cipher::getModeLabel() const { + if (!cipher_) + return {}; + switch (getMode()) { + case EVP_CIPH_CCM_MODE: + return "ccm"; + case EVP_CIPH_CFB_MODE: + return "cfb"; + case EVP_CIPH_CBC_MODE: + return "cbc"; + case EVP_CIPH_CTR_MODE: + return "ctr"; + case EVP_CIPH_ECB_MODE: + return "ecb"; + case EVP_CIPH_GCM_MODE: + return "gcm"; + case EVP_CIPH_OCB_MODE: + return "ocb"; + case EVP_CIPH_OFB_MODE: + return "ofb"; + case EVP_CIPH_WRAP_MODE: + return "wrap"; + case EVP_CIPH_XTS_MODE: + return "xts"; + case EVP_CIPH_STREAM_CIPHER: + return "stream"; + } + return "{unknown}"; +} + +const char* Cipher::getName() const { + if (!cipher_) + return {}; + // OBJ_nid2sn(EVP_CIPHER_nid(cipher)) is used here instead of + // EVP_CIPHER_name(cipher) for compatibility with BoringSSL. + return OBJ_nid2sn(getNid()); +} + +bool Cipher::isSupportedAuthenticatedMode() const { + switch (getMode()) { + case EVP_CIPH_CCM_MODE: + case EVP_CIPH_GCM_MODE: +#ifndef OPENSSL_NO_OCB + case EVP_CIPH_OCB_MODE: +#endif + return true; + case EVP_CIPH_STREAM_CIPHER: + return getNid() == NID_chacha20_poly1305; + default: + return false; + } +} + +int Cipher::bytesToKey(const Digest& digest, const Buffer& input, unsigned char* key, unsigned char* iv) const { + return EVP_BytesToKey(*this, digest, nullptr, input.data, input.len, 1, key, iv); +} + +// ============================================================================ + +CipherCtxPointer CipherCtxPointer::New() { + auto ret = CipherCtxPointer(EVP_CIPHER_CTX_new()); + if (!ret) + return {}; + EVP_CIPHER_CTX_init(ret.get()); + return ret; +} + +CipherCtxPointer::CipherCtxPointer(EVP_CIPHER_CTX* ctx) : ctx_(ctx) {} + +CipherCtxPointer::CipherCtxPointer(CipherCtxPointer&& other) noexcept : ctx_(other.release()) {} + +CipherCtxPointer& CipherCtxPointer::operator=(CipherCtxPointer&& other) noexcept { + if (this == &other) + return *this; + this->~CipherCtxPointer(); + return *new (this) CipherCtxPointer(std::move(other)); +} + +CipherCtxPointer::~CipherCtxPointer() { + reset(); +} + +void CipherCtxPointer::reset(EVP_CIPHER_CTX* ctx) { + ctx_.reset(ctx); +} + +EVP_CIPHER_CTX* CipherCtxPointer::release() { + return ctx_.release(); +} + +void CipherCtxPointer::setAllowWrap() { + if (!ctx_) + return; + EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); +} + +bool CipherCtxPointer::setKeyLength(size_t length) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_set_key_length(ctx_.get(), length); +} + +bool CipherCtxPointer::setIvLength(size_t length) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_IVLEN, length, nullptr) > 0; +} + +bool CipherCtxPointer::setAeadTag(const Buffer& tag) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, tag.len, const_cast(tag.data)) > 0; +} + +bool CipherCtxPointer::setAeadTagLength(size_t length) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, length, nullptr) > 0; +} + +bool CipherCtxPointer::setPadding(bool padding) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_set_padding(ctx_.get(), padding); +} + +int CipherCtxPointer::getBlockSize() const { + if (!ctx_) + return 0; + return EVP_CIPHER_CTX_block_size(ctx_.get()); +} + +int CipherCtxPointer::getMode() const { + if (!ctx_) + return 0; + return EVP_CIPHER_CTX_mode(ctx_.get()); +} + +bool CipherCtxPointer::isGcmMode() const { + if (!ctx_) + return false; + return getMode() == EVP_CIPH_GCM_MODE; +} + +bool CipherCtxPointer::isOcbMode() const { + if (!ctx_) + return false; + return getMode() == EVP_CIPH_OCB_MODE; +} + +bool CipherCtxPointer::isCcmMode() const { + if (!ctx_) + return false; + return getMode() == EVP_CIPH_CCM_MODE; +} + +bool CipherCtxPointer::isWrapMode() const { + if (!ctx_) + return false; + return getMode() == EVP_CIPH_WRAP_MODE; +} + +bool CipherCtxPointer::isChaCha20Poly1305() const { + if (!ctx_) + return false; + return getNid() == NID_chacha20_poly1305; +} + +int CipherCtxPointer::getNid() const { + if (!ctx_) + return 0; + return EVP_CIPHER_CTX_nid(ctx_.get()); +} + +bool CipherCtxPointer::init(const Cipher& cipher, bool encrypt, const unsigned char* key, const unsigned char* iv) { + if (!ctx_) + return false; + return EVP_CipherInit_ex(ctx_.get(), cipher, nullptr, key, iv, encrypt ? 1 : 0) == 1; +} + +bool CipherCtxPointer::update(const Buffer& in, unsigned char* out, int* out_len, bool finalize) { + if (!ctx_) + return false; + if (!finalize) { + return EVP_CipherUpdate(ctx_.get(), out, out_len, in.data, in.len) == 1; + } + return EVP_CipherFinal_ex(ctx_.get(), out, out_len) == 1; +} + +bool CipherCtxPointer::getAeadTag(size_t len, unsigned char* out) { + if (!ctx_) + return false; + return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG, len, out) > 0; +} + +// ============================================================================ + +ECDSASigPointer::ECDSASigPointer() : sig_(nullptr) {} +ECDSASigPointer::ECDSASigPointer(ECDSA_SIG* sig) : sig_(sig) { + if (sig_) { + ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); + } +} +ECDSASigPointer::ECDSASigPointer(ECDSASigPointer&& other) noexcept : sig_(other.release()) { + if (sig_) { + ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); + } +} + +ECDSASigPointer& ECDSASigPointer::operator=(ECDSASigPointer&& other) noexcept { + sig_.reset(other.release()); + if (sig_) { + ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); + } + return *this; +} + +ECDSASigPointer::~ECDSASigPointer() { + reset(); +} + +void ECDSASigPointer::reset(ECDSA_SIG* sig) { + sig_.reset(sig); + pr_ = nullptr; + ps_ = nullptr; +} + +ECDSA_SIG* ECDSASigPointer::release() { + pr_ = nullptr; + ps_ = nullptr; + return sig_.release(); +} + +ECDSASigPointer ECDSASigPointer::New() { + return ECDSASigPointer(ECDSA_SIG_new()); +} + +ECDSASigPointer ECDSASigPointer::Parse(const Buffer& sig) { + const unsigned char* ptr = sig.data; + return ECDSASigPointer(d2i_ECDSA_SIG(nullptr, &ptr, sig.len)); +} + +bool ECDSASigPointer::setParams(BignumPointer&& r, BignumPointer&& s) { + if (!sig_) + return false; + return ECDSA_SIG_set0(sig_.get(), r.release(), s.release()); +} + +Buffer ECDSASigPointer::encode() const { + if (!sig_) + return { + .data = nullptr, + .len = 0, + }; + Buffer buf; + buf.len = i2d_ECDSA_SIG(sig_.get(), &buf.data); + return buf; +} + +// ============================================================================ + +EVPKeyCtxPointer::EVPKeyCtxPointer() : ctx_(nullptr) {} + +EVPKeyCtxPointer::EVPKeyCtxPointer(EVP_PKEY_CTX* ctx) : ctx_(ctx) {} + +EVPKeyCtxPointer::EVPKeyCtxPointer(EVPKeyCtxPointer&& other) noexcept : ctx_(other.release()) {} + +EVPKeyCtxPointer& EVPKeyCtxPointer::operator=(EVPKeyCtxPointer&& other) noexcept { + ctx_.reset(other.release()); + return *this; +} + +EVPKeyCtxPointer::~EVPKeyCtxPointer() { + reset(); +} + +void EVPKeyCtxPointer::reset(EVP_PKEY_CTX* ctx) { + ctx_.reset(ctx); +} + +EVP_PKEY_CTX* EVPKeyCtxPointer::release() { + return ctx_.release(); +} + +EVPKeyCtxPointer EVPKeyCtxPointer::New(const EVPKeyPointer& key) { + if (!key) + return {}; + return EVPKeyCtxPointer(EVP_PKEY_CTX_new(key.get(), nullptr)); +} + +EVPKeyCtxPointer EVPKeyCtxPointer::NewFromID(int id) { +#ifdef OPENSSL_IS_BORINGSSL + // DSA keys are not supported with BoringSSL + if (id == EVP_PKEY_DSA) + return {}; +#endif + return EVPKeyCtxPointer(EVP_PKEY_CTX_new_id(id, nullptr)); +} + +bool EVPKeyCtxPointer::initForDerive(const EVPKeyPointer& peer) { + if (!ctx_) + return false; + if (EVP_PKEY_derive_init(ctx_.get()) != 1) + return false; + return EVP_PKEY_derive_set_peer(ctx_.get(), peer.get()) == 1; +} + +bool EVPKeyCtxPointer::initForKeygen() { + if (!ctx_) + return false; + return EVP_PKEY_keygen_init(ctx_.get()) == 1; +} + +bool EVPKeyCtxPointer::initForParamgen() { + if (!ctx_) + return false; + return EVP_PKEY_paramgen_init(ctx_.get()) == 1; +} + +int EVPKeyCtxPointer::initForVerify() { + if (!ctx_) + return 0; + return EVP_PKEY_verify_init(ctx_.get()); +} + +int EVPKeyCtxPointer::initForSign() { + if (!ctx_) + return 0; + return EVP_PKEY_sign_init(ctx_.get()); +} + +bool EVPKeyCtxPointer::setDhParameters(int prime_size, uint32_t generator) { +#ifndef OPENSSL_IS_BORINGSSL + if (!ctx_) + return false; + return EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx_.get(), prime_size) == 1 && + EVP_PKEY_CTX_set_dh_paramgen_generator(ctx_.get(), generator) == 1; +#else + // TODO(jasnell): Boringssl appears not to support this operation. + // Is there an alternative approach that Boringssl does support? + return false; +#endif +} + +bool EVPKeyCtxPointer::setDsaParameters(uint32_t bits, std::optional q_bits) { +#ifndef NCRYPTO_NO_DSA_KEYGEN + if (!ctx_) + return false; + if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx_.get(), bits) != 1) { + return false; + } + if (q_bits.has_value() && EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx_.get(), q_bits.value()) != 1) { + return false; + } + return true; +#else + // Older versions of openssl/boringssl do not implement the DSA keygen. + return false; +#endif +} + +bool EVPKeyCtxPointer::setEcParameters(int curve, int encoding) { + if (!ctx_) + return false; + return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx_.get(), curve) == 1 && EVP_PKEY_CTX_set_ec_param_enc(ctx_.get(), encoding) == 1; +} + +bool EVPKeyCtxPointer::setRsaOaepMd(const Digest& md) { + if (!md || !ctx_) + return false; + const EVP_MD* md_ptr = md; + return EVP_PKEY_CTX_set_rsa_oaep_md(ctx_.get(), md_ptr) > 0; +} + +bool EVPKeyCtxPointer::setRsaMgf1Md(const Digest& md) { + if (!md || !ctx_) + return false; + const EVP_MD* md_ptr = md; + return EVP_PKEY_CTX_set_rsa_mgf1_md(ctx_.get(), md_ptr) > 0; +} + +bool EVPKeyCtxPointer::setRsaPadding(int padding) { + return setRsaPadding(ctx_.get(), padding, std::nullopt); +} + +bool EVPKeyCtxPointer::setRsaPadding(EVP_PKEY_CTX* ctx, int padding, std::optional salt_len) { + if (ctx == nullptr) + return false; + if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0) { + return false; + } + if (padding == RSA_PKCS1_PSS_PADDING && salt_len.has_value()) { + return EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, salt_len.value()) > 0; + } + return true; +} + +bool EVPKeyCtxPointer::setRsaKeygenBits(int bits) { + if (!ctx_) + return false; + return EVP_PKEY_CTX_set_rsa_keygen_bits(ctx_.get(), bits) == 1; +} + +bool EVPKeyCtxPointer::setRsaKeygenPubExp(BignumPointer&& e) { + if (!ctx_) + return false; + return EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx_.get(), e.get()) == 1; +} + +bool EVPKeyCtxPointer::setRsaPssKeygenMd(const Digest& md) { + if (!md || !ctx_) + return false; + // OpenSSL < 3 accepts a void* for the md parameter. + const EVP_MD* md_ptr = md; + return EVP_PKEY_CTX_set_rsa_pss_keygen_md(ctx_.get(), md_ptr) > 0; +} + +bool EVPKeyCtxPointer::setRsaPssKeygenMgf1Md(const Digest& md) { + if (!md || !ctx_) + return false; + const EVP_MD* md_ptr = md; + return EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(ctx_.get(), md_ptr) > 0; +} + +bool EVPKeyCtxPointer::setRsaPssSaltlen(int salt_len) { + if (!ctx_) + return false; + return EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(ctx_.get(), salt_len) > 0; +} + +bool EVPKeyCtxPointer::setRsaImplicitRejection() { +#ifndef OPENSSL_IS_BORINGSSL + if (!ctx_) + return false; + return EVP_PKEY_CTX_ctrl_str(ctx_.get(), "rsa_pkcs1_implicit_rejection", "1") > 0; + // From the doc -2 means that the option is not supported. + // The default for the option is enabled and if it has been + // specifically disabled we want to respect that so we will + // not throw an error if the option is supported regardless + // of how it is set. The call to set the value + // will not affect what is used since a different context is + // used in the call if the option is supported +#else + // TODO(jasnell): Boringssl appears not to support this operation. + // Is there an alternative approach that Boringssl does support? + return true; +#endif +} + +bool EVPKeyCtxPointer::setRsaOaepLabel(DataPointer&& data) { + if (!ctx_) + return false; + if (EVP_PKEY_CTX_set0_rsa_oaep_label(ctx_.get(), static_cast(data.get()), data.size()) > 0) { + // The ctx_ takes ownership of data on success. + data.release(); + return true; + } + return false; +} + +bool EVPKeyCtxPointer::setSignatureMd(const EVPMDCtxPointer& md) { + if (!ctx_) + return false; + return EVP_PKEY_CTX_set_signature_md(ctx_.get(), EVP_MD_CTX_get0_md(md.get())) == 1; +} + +bool EVPKeyCtxPointer::initForEncrypt() { + if (!ctx_) + return false; + return EVP_PKEY_encrypt_init(ctx_.get()) == 1; +} + +bool EVPKeyCtxPointer::initForDecrypt() { + if (!ctx_) + return false; + return EVP_PKEY_decrypt_init(ctx_.get()) == 1; +} + +DataPointer EVPKeyCtxPointer::derive() const { + if (!ctx_) + return {}; + size_t len = 0; + if (EVP_PKEY_derive(ctx_.get(), nullptr, &len) != 1) + return {}; + auto data = DataPointer::Alloc(len); + if (!data) + return {}; + if (EVP_PKEY_derive(ctx_.get(), static_cast(data.get()), &len) != 1) { + return {}; + } + return data; +} + +EVPKeyPointer EVPKeyCtxPointer::paramgen() const { + if (!ctx_) + return {}; + EVP_PKEY* key = nullptr; + if (EVP_PKEY_paramgen(ctx_.get(), &key) != 1) + return {}; + return EVPKeyPointer(key); +} + +bool EVPKeyCtxPointer::publicCheck() const { + if (!ctx_) + return false; +#ifndef OPENSSL_IS_BORINGSSL +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_PKEY_public_check_quick(ctx_.get()) == 1; +#else + return EVP_PKEY_public_check(ctx_.get()) == 1; +#endif +#else // OPENSSL_IS_BORINGSSL + // Boringssl appears not to support this operation. + // TODO(jasnell): Is there an alternative approach that Boringssl does + // support? + return true; +#endif +} + +bool EVPKeyCtxPointer::privateCheck() const { + if (!ctx_) + return false; +#ifndef OPENSSL_IS_BORINGSSL + return EVP_PKEY_check(ctx_.get()) == 1; +#else + // Boringssl appears not to support this operation. + // TODO(jasnell): Is there an alternative approach that Boringssl does + // support? + return true; +#endif +} + +bool EVPKeyCtxPointer::verify(const Buffer& sig, const Buffer& data) { + if (!ctx_) + return false; + return EVP_PKEY_verify(ctx_.get(), sig.data, sig.len, data.data, data.len) == 1; +} + +DataPointer EVPKeyCtxPointer::sign(const Buffer& data) { + if (!ctx_) + return {}; + size_t len = 0; + if (EVP_PKEY_sign(ctx_.get(), nullptr, &len, data.data, data.len) != 1) { + return {}; + } + auto buf = DataPointer::Alloc(len); + if (!buf) + return {}; + if (EVP_PKEY_sign(ctx_.get(), static_cast(buf.get()), &len, data.data, data.len) != 1) { + return {}; + } + return buf.resize(len); +} + +bool EVPKeyCtxPointer::signInto(const Buffer& data, Buffer* sig) { + if (!ctx_) + return false; + size_t len = sig->len; + if (EVP_PKEY_sign(ctx_.get(), sig->data, &len, data.data, data.len) != 1) { + return false; + } + sig->len = len; + return true; +} + +// ============================================================================ + +namespace { + + using EVP_PKEY_cipher_init_t = int(EVP_PKEY_CTX* ctx); + using EVP_PKEY_cipher_t = int(EVP_PKEY_CTX* ctx, unsigned char* out, size_t* outlen, const unsigned char* in, size_t inlen); + + template + DataPointer CipherImpl(const EVPKeyPointer& key, const Cipher::CipherParams& params, const Buffer in) { + if (!key) + return {}; + EVPKeyCtxPointer ctx = key.newCtx(); + if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) || + (params.digest != nullptr && !ctx.setRsaOaepMd(params.digest))) { + return {}; + } + + if (params.label.len != 0 && params.label.data != nullptr && !ctx.setRsaOaepLabel(DataPointer::Copy(params.label))) { + return {}; + } + + size_t out_len = 0; + if (cipher(ctx.get(), nullptr, &out_len, static_cast(in.data), in.len) <= 0) { + return {}; + } + + auto buf = DataPointer::Alloc(out_len); + if (!buf) + return {}; + + if (cipher(ctx.get(), static_cast(buf.get()), &out_len, static_cast(in.data), in.len) <= 0) { + return {}; + } + + return buf.resize(out_len); + } +} // namespace + +DataPointer Cipher::encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer in) { + // public operation + return CipherImpl(key, params, in); +} + +DataPointer Cipher::decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer in) { + // private operation + return CipherImpl(key, params, in); +} + +DataPointer Cipher::sign(const EVPKeyPointer& key, const CipherParams& params, const Buffer in) { + // private operation + return CipherImpl(key, params, in); +} + +DataPointer Cipher::recover(const EVPKeyPointer& key, const CipherParams& params, const Buffer in) { + // public operation + return CipherImpl(key, params, in); +} + +namespace { + struct CipherCallbackContext { + Cipher::CipherNameCallback cb; + void operator()(const char* name) { + cb(name); + } + }; + +#if OPENSSL_VERSION_MAJOR >= 3 + template + void array_push_back(const TypeName*, const char* from, const char*, void* arg) { + if (from == nullptr) + return; + + const TypeName* real_instance = getbyname(from); + if (!real_instance) + return; + + const char* real_name = getname(real_instance); + if (!real_name) + return; + + // EVP_*_fetch() does not support alias names, so we need to pass it the + // real/original algorithm name. + // We use EVP_*_fetch() as a filter here because it will only return an + // instance if the algorithm is supported by the public OpenSSL APIs (some + // algorithms are used internally by OpenSSL and are also passed to this + // callback). + TypeName* fetched = fetch_type(nullptr, real_name, nullptr); + if (fetched == nullptr) + return; + + free_type(fetched); + auto& cb = *(static_cast(arg)); + cb(from); + } +#else + template + void array_push_back(const TypeName* evp_ref, const char* from, const char* to, void* arg) { + if (!from) + return; + auto& cb = *(static_cast(arg)); + cb(from); + } +#endif +} // namespace + +void Cipher::ForEach(Cipher::CipherNameCallback callback) { + ClearErrorOnReturn clearErrorOnReturn; + CipherCallbackContext context; + context.cb = std::move(callback); + + EVP_CIPHER_do_all_sorted( +#if OPENSSL_VERSION_MAJOR >= 3 + array_push_back, +#else + array_push_back, +#endif + &context); +} + +EVPMDCtxPointer::EVPMDCtxPointer() : ctx_(nullptr) {} + +EVPMDCtxPointer::EVPMDCtxPointer(EVP_MD_CTX* ctx) : ctx_(ctx) {} + +EVPMDCtxPointer::EVPMDCtxPointer(EVPMDCtxPointer&& other) noexcept : ctx_(other.release()) {} + +EVPMDCtxPointer& EVPMDCtxPointer::operator=(EVPMDCtxPointer&& other) noexcept { + ctx_.reset(other.release()); + return *this; +} + +EVPMDCtxPointer::~EVPMDCtxPointer() { + reset(); +} + +void EVPMDCtxPointer::reset(EVP_MD_CTX* ctx) { + ctx_.reset(ctx); +} + +EVP_MD_CTX* EVPMDCtxPointer::release() { + return ctx_.release(); +} + +bool EVPMDCtxPointer::digestInit(const Digest& digest) { + if (!ctx_) + return false; + return EVP_DigestInit_ex(ctx_.get(), digest, nullptr) > 0; +} + +bool EVPMDCtxPointer::digestUpdate(const Buffer& in) { + if (!ctx_) + return false; + return EVP_DigestUpdate(ctx_.get(), in.data, in.len) > 0; +} + +DataPointer EVPMDCtxPointer::digestFinal(size_t length) { + if (!ctx_) + return {}; + + auto buf = DataPointer::Alloc(length); + if (!buf) + return {}; + + Buffer buffer = buf; + + if (!digestFinalInto(&buffer)) [[unlikely]] { + return {}; + } + + return buf; +} + +bool EVPMDCtxPointer::digestFinalInto(Buffer* buf) { + if (!ctx_) + return false; + + auto ptr = static_cast(buf->data); + + int ret = (buf->len == getExpectedSize()) ? EVP_DigestFinal_ex(ctx_.get(), ptr, nullptr) : EVP_DigestFinalXOF(ctx_.get(), ptr, buf->len); + + if (ret != 1) [[unlikely]] + return false; + + return true; +} + +size_t EVPMDCtxPointer::getExpectedSize() { + if (!ctx_) + return 0; + return EVP_MD_CTX_size(ctx_.get()); +} + +size_t EVPMDCtxPointer::getDigestSize() const { + return EVP_MD_size(getDigest()); +} + +const EVP_MD* EVPMDCtxPointer::getDigest() const { + if (!ctx_) + return nullptr; + return EVP_MD_CTX_get0_md(ctx_.get()); +} + +bool EVPMDCtxPointer::hasXofFlag() const { + if (!ctx_) + return false; + return (EVP_MD_flags(getDigest()) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF; +} + +bool EVPMDCtxPointer::copyTo(const EVPMDCtxPointer& other) const { + if (!ctx_ || !other) + return {}; + if (EVP_MD_CTX_copy(other.get(), ctx_.get()) != 1) + return false; + return true; +} + +std::optional EVPMDCtxPointer::signInit(const EVPKeyPointer& key, const Digest& digest) { + EVP_PKEY_CTX* ctx = nullptr; + if (!EVP_DigestSignInit(ctx_.get(), &ctx, digest, nullptr, key.get())) { + return std::nullopt; + } + return ctx; +} + +std::optional EVPMDCtxPointer::verifyInit(const EVPKeyPointer& key, const Digest& digest) { + EVP_PKEY_CTX* ctx = nullptr; + if (!EVP_DigestVerifyInit(ctx_.get(), &ctx, digest, nullptr, key.get())) { + return std::nullopt; + } + return ctx; +} + +std::optional EVPMDCtxPointer::signInitWithContext(const EVPKeyPointer& key, const Digest& digest, + const Buffer& context_string) { + (void)digest; +#ifdef OSSL_SIGNATURE_PARAM_CONTEXT_STRING + EVP_PKEY_CTX* ctx = nullptr; + +#ifdef OSSL_SIGNATURE_PARAM_INSTANCE + // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. + // Without it, OpenSSL silently ignores the context string. + if (key.id() == EVP_PKEY_ED25519) { + const OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_INSTANCE, const_cast("Ed25519ctx"), 0), + OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, + const_cast(context_string.data), context_string.len), + OSSL_PARAM_END}; + + if (!EVP_DigestSignInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { + return std::nullopt; + } + return ctx; + } +#endif // OSSL_SIGNATURE_PARAM_INSTANCE + + const OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, + const_cast(context_string.data), context_string.len), + OSSL_PARAM_END}; + + if (!EVP_DigestSignInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { + return std::nullopt; + } + return ctx; +#else + return std::nullopt; +#endif +} + +std::optional EVPMDCtxPointer::verifyInitWithContext(const EVPKeyPointer& key, const Digest& digest, + const Buffer& context_string) { + (void)digest; +#ifdef OSSL_SIGNATURE_PARAM_CONTEXT_STRING + EVP_PKEY_CTX* ctx = nullptr; + +#ifdef OSSL_SIGNATURE_PARAM_INSTANCE + // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. + // Without it, OpenSSL silently ignores the context string. + if (key.id() == EVP_PKEY_ED25519) { + const OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_INSTANCE, const_cast("Ed25519ctx"), 0), + OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, + const_cast(context_string.data), context_string.len), + OSSL_PARAM_END}; + + if (!EVP_DigestVerifyInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { + return std::nullopt; + } + return ctx; + } +#endif // OSSL_SIGNATURE_PARAM_INSTANCE + + const OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, + const_cast(context_string.data), context_string.len), + OSSL_PARAM_END}; + + if (!EVP_DigestVerifyInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { + return std::nullopt; + } + return ctx; +#else + return std::nullopt; +#endif +} + +DataPointer EVPMDCtxPointer::signOneShot(const Buffer& buf) const { + if (!ctx_) + return {}; + size_t len; + if (!EVP_DigestSign(ctx_.get(), nullptr, &len, buf.data, buf.len)) { + return {}; + } + auto data = DataPointer::Alloc(len); + if (!data) [[unlikely]] + return {}; + + if (!EVP_DigestSign(ctx_.get(), static_cast(data.get()), &len, buf.data, buf.len)) { + return {}; + } + return data; +} + +DataPointer EVPMDCtxPointer::sign(const Buffer& buf) const { + if (!ctx_) [[unlikely]] + return {}; + size_t len; + if (!EVP_DigestSignUpdate(ctx_.get(), buf.data, buf.len) || !EVP_DigestSignFinal(ctx_.get(), nullptr, &len)) { + return {}; + } + auto data = DataPointer::Alloc(len); + if (!data) [[unlikely]] + return {}; + if (!EVP_DigestSignFinal(ctx_.get(), static_cast(data.get()), &len)) { + return {}; + } + return data.resize(len); +} + +bool EVPMDCtxPointer::verify(const Buffer& buf, const Buffer& sig) const { + if (!ctx_) + return false; + int ret = EVP_DigestVerify(ctx_.get(), sig.data, sig.len, buf.data, buf.len); + return ret == 1; +} + +EVPMDCtxPointer EVPMDCtxPointer::New() { + return EVPMDCtxPointer(EVP_MD_CTX_new()); +} + +// ============================================================================ + +bool extractP1363(const Buffer& buf, unsigned char* dest, size_t n) { + auto asn1_sig = ECDSASigPointer::Parse(buf); + if (!asn1_sig) + return false; + + return BignumPointer::EncodePaddedInto(asn1_sig.r(), dest, n) > 0 && BignumPointer::EncodePaddedInto(asn1_sig.s(), dest + n, n) > 0; +} + +#if OPENSSL_VERSION_MAJOR >= 3 +EVPMacPointer::EVPMacPointer(EVP_MAC* mac) : mac_(mac) {} + +EVPMacPointer::EVPMacPointer(EVPMacPointer&& other) noexcept : mac_(std::move(other.mac_)) {} + +EVPMacPointer& EVPMacPointer::operator=(EVPMacPointer&& other) noexcept { + if (this == &other) + return *this; + mac_ = std::move(other.mac_); + return *this; +} + +EVPMacPointer::~EVPMacPointer() { + mac_.reset(); +} + +void EVPMacPointer::reset(EVP_MAC* mac) { + mac_.reset(mac); +} + +EVP_MAC* EVPMacPointer::release() { + return mac_.release(); +} + +EVPMacPointer EVPMacPointer::Fetch(const char* algorithm) { + return EVPMacPointer(EVP_MAC_fetch(nullptr, algorithm, nullptr)); +} + +EVPMacCtxPointer::EVPMacCtxPointer(EVP_MAC_CTX* ctx) : ctx_(ctx) {} + +EVPMacCtxPointer::EVPMacCtxPointer(EVPMacCtxPointer&& other) noexcept : ctx_(std::move(other.ctx_)) {} + +EVPMacCtxPointer& EVPMacCtxPointer::operator=(EVPMacCtxPointer&& other) noexcept { + if (this == &other) + return *this; + ctx_ = std::move(other.ctx_); + return *this; +} + +EVPMacCtxPointer::~EVPMacCtxPointer() { + ctx_.reset(); +} + +void EVPMacCtxPointer::reset(EVP_MAC_CTX* ctx) { + ctx_.reset(ctx); +} + +EVP_MAC_CTX* EVPMacCtxPointer::release() { + return ctx_.release(); +} + +bool EVPMacCtxPointer::init(const Buffer& key, const OSSL_PARAM* params) { + if (!ctx_) + return false; + return EVP_MAC_init(ctx_.get(), static_cast(key.data), key.len, params) == 1; +} + +bool EVPMacCtxPointer::update(const Buffer& data) { + if (!ctx_) + return false; + return EVP_MAC_update(ctx_.get(), static_cast(data.data), data.len) == 1; +} + +DataPointer EVPMacCtxPointer::final(size_t length) { + if (!ctx_) + return {}; + auto buf = DataPointer::Alloc(length); + if (!buf) + return {}; + + size_t result_len = length; + if (EVP_MAC_final(ctx_.get(), static_cast(buf.get()), &result_len, length) != 1) { + return {}; + } + + return buf; +} + +EVPMacCtxPointer EVPMacCtxPointer::New(EVP_MAC* mac) { + if (!mac) + return EVPMacCtxPointer(); + return EVPMacCtxPointer(EVP_MAC_CTX_new(mac)); +} +#endif // OPENSSL_VERSION_MAJOR >= 3 + +DataPointer hashDigest(const Buffer& buf, const EVP_MD* md) { + if (md == nullptr) + return {}; + size_t md_len = EVP_MD_size(md); + unsigned int result_size; + auto data = DataPointer::Alloc(md_len); + if (!data) + return {}; + + if (!EVP_Digest(buf.data, buf.len, reinterpret_cast(data.get()), &result_size, md, nullptr)) { + return {}; + } + + return data.resize(result_size); +} + +DataPointer xofHashDigest(const Buffer& buf, const EVP_MD* md, size_t output_length) { + if (md == nullptr) + return {}; + + EVPMDCtxPointer ctx = EVPMDCtxPointer::New(); + if (!ctx) + return {}; + if (ctx.digestInit(md) != 1) { + return {}; + } + if (ctx.digestUpdate(reinterpret_cast&>(buf)) != 1) { + return {}; + } + return ctx.digestFinal(output_length); +} + +// ============================================================================ + +size_t Digest::size() const { + if (md_ == nullptr) + return 0; + return EVP_MD_size(md_); +} + +const Digest Digest::MD5 = Digest(EVP_md5()); +const Digest Digest::SHA1 = Digest(EVP_sha1()); +const Digest Digest::SHA256 = Digest(EVP_sha256()); +const Digest Digest::SHA384 = Digest(EVP_sha384()); +const Digest Digest::SHA512 = Digest(EVP_sha512()); + +const Digest Digest::FromName(const char* name) { + return ncrypto::getDigestByName(name); +} + +// ============================================================================ +// KEM Implementation +#if OPENSSL_VERSION_MAJOR >= 3 +#if !OPENSSL_VERSION_PREREQ(3, 5) +bool KEM::SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key) { + const char* operation = nullptr; + + switch (EVP_PKEY_id(key.get())) { + case EVP_PKEY_RSA: + operation = OSSL_KEM_PARAM_OPERATION_RSASVE; + break; +#if OPENSSL_VERSION_PREREQ(3, 2) + case EVP_PKEY_EC: + case EVP_PKEY_X25519: + case EVP_PKEY_X448: + operation = OSSL_KEM_PARAM_OPERATION_DHKEM; + break; +#endif + default: + unreachable(); + } + + if (operation != nullptr) { + OSSL_PARAM params[] = {OSSL_PARAM_utf8_string(OSSL_KEM_PARAM_OPERATION, const_cast(operation), 0), OSSL_PARAM_END}; + + if (EVP_PKEY_CTX_set_params(ctx, params) <= 0) { + return false; + } + } + + return true; +} +#endif + +std::optional KEM::Encapsulate(const EVPKeyPointer& public_key) { + ClearErrorOnReturn clear_error_on_return; + + auto ctx = public_key.newCtx(); + if (!ctx) + return std::nullopt; + + if (EVP_PKEY_encapsulate_init(ctx.get(), nullptr) <= 0) { + return std::nullopt; + } + +#if !OPENSSL_VERSION_PREREQ(3, 5) + if (!SetOperationParameter(ctx.get(), public_key)) { + return std::nullopt; + } +#endif + + // Determine output buffer sizes + size_t ciphertext_len = 0; + size_t shared_key_len = 0; + + if (EVP_PKEY_encapsulate(ctx.get(), nullptr, &ciphertext_len, nullptr, &shared_key_len) <= 0) { + return std::nullopt; + } + + auto ciphertext = DataPointer::Alloc(ciphertext_len); + auto shared_key = DataPointer::Alloc(shared_key_len); + if (!ciphertext || !shared_key) + return std::nullopt; + + if (EVP_PKEY_encapsulate(ctx.get(), static_cast(ciphertext.get()), &ciphertext_len, + static_cast(shared_key.get()), &shared_key_len) <= 0) { + return std::nullopt; + } + + return EncapsulateResult(std::move(ciphertext), std::move(shared_key)); +} + +DataPointer KEM::Decapsulate(const EVPKeyPointer& private_key, const Buffer& ciphertext) { + ClearErrorOnReturn clear_error_on_return; + + auto ctx = private_key.newCtx(); + if (!ctx) + return {}; + + if (EVP_PKEY_decapsulate_init(ctx.get(), nullptr) <= 0) { + return {}; + } + +#if !OPENSSL_VERSION_PREREQ(3, 5) + if (!SetOperationParameter(ctx.get(), private_key)) { + return {}; + } +#endif + + // First pass: determine shared secret size + size_t shared_key_len = 0; + if (EVP_PKEY_decapsulate(ctx.get(), nullptr, &shared_key_len, static_cast(ciphertext.data), ciphertext.len) <= 0) { + return {}; + } + + auto shared_key = DataPointer::Alloc(shared_key_len); + if (!shared_key) + return {}; + + if (EVP_PKEY_decapsulate(ctx.get(), static_cast(shared_key.get()), &shared_key_len, + static_cast(ciphertext.data), ciphertext.len) <= 0) { + return {}; + } + + return shared_key; +} + +#endif // OPENSSL_VERSION_MAJOR >= 3 + +} // namespace ncrypto + +// =========================================================================== +#if NCRYPTO_BSSL_LIBDECREPIT_MISSING +// While BoringSSL implements EVP_CIPHER_do_all_sorted, it includes this +// inplementation in a library called "libdecrepit", which might not be included +// depending on how boringssl was built. In such cases, a copy of the function +// is provided here: + +extern "C" void EVP_CIPHER_do_all_sorted(void (*callback)(const EVP_CIPHER* cipher, const char* name, const char* unused, void* arg), + void* arg) { + callback(EVP_aes_128_cbc(), "AES-128-CBC", NULL, arg); + callback(EVP_aes_192_cbc(), "AES-192-CBC", NULL, arg); + callback(EVP_aes_256_cbc(), "AES-256-CBC", NULL, arg); + callback(EVP_aes_128_ctr(), "AES-128-CTR", NULL, arg); + callback(EVP_aes_192_ctr(), "AES-192-CTR", NULL, arg); + callback(EVP_aes_256_ctr(), "AES-256-CTR", NULL, arg); + callback(EVP_aes_128_ecb(), "AES-128-ECB", NULL, arg); + callback(EVP_aes_192_ecb(), "AES-192-ECB", NULL, arg); + callback(EVP_aes_256_ecb(), "AES-256-ECB", NULL, arg); + callback(EVP_aes_128_ofb(), "AES-128-OFB", NULL, arg); + callback(EVP_aes_192_ofb(), "AES-192-OFB", NULL, arg); + callback(EVP_aes_256_ofb(), "AES-256-OFB", NULL, arg); + callback(EVP_aes_128_gcm(), "AES-128-GCM", NULL, arg); + callback(EVP_aes_192_gcm(), "AES-192-GCM", NULL, arg); + callback(EVP_aes_256_gcm(), "AES-256-GCM", NULL, arg); + callback(EVP_des_cbc(), "DES-CBC", NULL, arg); + callback(EVP_des_ecb(), "DES-ECB", NULL, arg); + callback(EVP_des_ede(), "DES-EDE", NULL, arg); + callback(EVP_des_ede_cbc(), "DES-EDE-CBC", NULL, arg); + callback(EVP_des_ede3_cbc(), "DES-EDE3-CBC", NULL, arg); + callback(EVP_rc2_cbc(), "RC2-CBC", NULL, arg); + callback(EVP_rc4(), "RC4", NULL, arg); + + // OpenSSL returns everything twice, the second time in lower case. + callback(EVP_aes_128_cbc(), "aes-128-cbc", NULL, arg); + callback(EVP_aes_192_cbc(), "aes-192-cbc", NULL, arg); + callback(EVP_aes_256_cbc(), "aes-256-cbc", NULL, arg); + callback(EVP_aes_128_ctr(), "aes-128-ctr", NULL, arg); + callback(EVP_aes_192_ctr(), "aes-192-ctr", NULL, arg); + callback(EVP_aes_256_ctr(), "aes-256-ctr", NULL, arg); + callback(EVP_aes_128_ecb(), "aes-128-ecb", NULL, arg); + callback(EVP_aes_192_ecb(), "aes-192-ecb", NULL, arg); + callback(EVP_aes_256_ecb(), "aes-256-ecb", NULL, arg); + callback(EVP_aes_128_ofb(), "aes-128-ofb", NULL, arg); + callback(EVP_aes_192_ofb(), "aes-192-ofb", NULL, arg); + callback(EVP_aes_256_ofb(), "aes-256-ofb", NULL, arg); + callback(EVP_aes_128_gcm(), "aes-128-gcm", NULL, arg); + callback(EVP_aes_192_gcm(), "aes-192-gcm", NULL, arg); + callback(EVP_aes_256_gcm(), "aes-256-gcm", NULL, arg); + callback(EVP_des_cbc(), "des-cbc", NULL, arg); + callback(EVP_des_ecb(), "des-ecb", NULL, arg); + callback(EVP_des_ede(), "des-ede", NULL, arg); + callback(EVP_des_ede_cbc(), "des-ede-cbc", NULL, arg); + callback(EVP_des_ede3_cbc(), "des-ede3-cbc", NULL, arg); + callback(EVP_rc2_cbc(), "rc2-cbc", NULL, arg); + callback(EVP_rc4(), "rc4", NULL, arg); +} +#endif diff --git a/packages/react-native-quick-crypto/package.json b/packages/react-native-quick-crypto/package.json index efdf22ad9..ebbe6cae9 100644 --- a/packages/react-native-quick-crypto/package.json +++ b/packages/react-native-quick-crypto/package.json @@ -39,9 +39,9 @@ "deps/fastpbkdf2", "deps/ncrypto/include", "deps/ncrypto/src/aead.cpp", - "deps/ncrypto/src/engine.cpp", "deps/ncrypto/src/ncrypto.cpp", "deps/ncrypto/LICENSE", + "deps/ncrypto/README.md", "deps/simdutf/include", "deps/simdutf/src", "deps/simdutf/LICENSE-MIT", diff --git a/packages/react-native-quick-crypto/src/keys/index.ts b/packages/react-native-quick-crypto/src/keys/index.ts index 91367668c..8baf99071 100644 --- a/packages/react-native-quick-crypto/src/keys/index.ts +++ b/packages/react-native-quick-crypto/src/keys/index.ts @@ -236,6 +236,8 @@ function createPublicKey(key: KeyInput): PublicKeyObject { let kType: KeyEncoding | undefined; if (type === 'spki') kType = KeyEncoding.SPKI; else if (type === 'pkcs1') kType = KeyEncoding.PKCS1; + else if (type === 'pkcs8') kType = KeyEncoding.PKCS8; + else if (type === 'sec1') kType = KeyEncoding.SEC1; return KeyObject.createKeyObject( 'public', diff --git a/scripts/check-ncrypto-openssl-deprecations.sh b/scripts/check-ncrypto-openssl-deprecations.sh new file mode 100755 index 000000000..ef60176f0 --- /dev/null +++ b/scripts/check-ncrypto-openssl-deprecations.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +ncrypto_dir="$repo_root/packages/react-native-quick-crypto/deps/ncrypto" +compiler="${CXX:-c++}" +work_dir="$(mktemp -d)" +trap 'rm -rf "$work_dir"' EXIT + +openssl_cflags=() +openssl_ldflags=() +if [[ -n "${OPENSSL_ROOT_DIR:-}" ]]; then + openssl_cflags+=("-I$OPENSSL_ROOT_DIR/include") + if [[ -d "$OPENSSL_ROOT_DIR/lib" ]]; then + openssl_lib_dir="$OPENSSL_ROOT_DIR/lib" + else + openssl_lib_dir="$OPENSSL_ROOT_DIR/lib64" + fi + openssl_ldflags+=("-L$openssl_lib_dir" "-Wl,-rpath,$openssl_lib_dir" -lssl -lcrypto) + if [[ "$(uname -s)" == "Linux" ]]; then + openssl_ldflags+=(-ldl -pthread) + fi +elif command -v pkg-config >/dev/null 2>&1 && pkg-config --exists openssl; then + read -r -a openssl_cflags <<<"$(pkg-config --cflags openssl)" + read -r -a openssl_ldflags <<<"$(pkg-config --libs openssl)" +elif command -v brew >/dev/null 2>&1; then + openssl_prefix="$(brew --prefix openssl@3)" + openssl_cflags+=("-I$openssl_prefix/include") + openssl_ldflags+=("-L$openssl_prefix/lib" "-Wl,-rpath,$openssl_prefix/lib" -lssl -lcrypto) +else + openssl_ldflags+=(-lssl -lcrypto) +fi + +cat >"$work_dir/header-consumer.cpp" <<'EOF' +#include +#include + +static_assert(OPENSSL_VERSION_NUMBER >= 0x30600000L); +EOF + +cat >"$work_dir/prime-check-regression.cpp" <<'EOF' +#include + +namespace { +bool checkMersennePrime(int exponent, int requested_checks) { + ncrypto::BignumPointer candidate(BN_new()); + if (!candidate || BN_set_bit(candidate.get(), exponent) != 1 || + BN_sub_word(candidate.get(), 1) != 1) { + return false; + } + + int completed_checks = 0; + const int result = candidate.isPrime( + requested_checks, [&completed_checks](int event, int iteration) { + if (event == 1 && iteration >= 0) completed_checks++; + return true; + }); + return result == 1 && completed_checks >= requested_checks; +} +} // namespace + +int main() { + return checkMersennePrime(127, 65) && checkMersennePrime(2203, 129) ? 0 : 1; +} +EOF + +warning_flags=( + -std=c++20 + -Wall + -Wextra + -Werror + -Wdeprecated-declarations + "-I$ncrypto_dir/include" + "${openssl_cflags[@]}" +) + +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/ncrypto.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/aead.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$work_dir/header-consumer.cpp" +"$compiler" "${warning_flags[@]}" \ + "$ncrypto_dir/src/ncrypto.cpp" \ + "$work_dir/prime-check-regression.cpp" \ + "${openssl_ldflags[@]}" \ + -o "$work_dir/prime-check-regression" +"$work_dir/prime-check-regression" From 39e8049c7c88c725dc8af400afaa9f198a0c0382 Mon Sep 17 00:00:00 2001 From: Brad Anderson Date: Mon, 26 Oct 2026 11:08:57 -0400 Subject: [PATCH 2/8] fix: check X509 BIO reset before parsing DER --- .../react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp b/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp index f4927e64f..07d587bb9 100644 --- a/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp +++ b/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp @@ -1362,7 +1362,8 @@ Result X509Pointer::Parse(Buffer buffer) X509Pointer pem(PEM_read_bio_X509_AUX(bio.get(), nullptr, NoPasswordCallback, nullptr)); if (pem) return Result(std::move(pem)); - BIO_reset(bio.get()); + if (!bio.resetBio()) + return Result(ERR_get_error()); X509Pointer der(d2i_X509_bio(bio.get(), nullptr)); if (der) From 3e6c31408edd797c7e68d8ad5e5283770b60576b Mon Sep 17 00:00:00 2001 From: Brad Anderson Date: Mon, 26 Oct 2026 11:11:04 -0400 Subject: [PATCH 3/8] docs: adapt Spicy agent workflows for RNQC --- .agents/agents/orchestrator.md | 209 ++++----------------- .agents/commands/address-pr-feedback.md | 231 +++++++++--------------- .agents/commands/commit.md | 111 +++++++----- .agents/commands/fix-pr.md | 5 + .agents/commands/handoff.md | 30 +++ .agents/commands/implement.md | 139 ++++++++++++++ .agents/commands/pr.md | 109 ++++++++--- .agents/commands/review.md | 108 ++++++----- .agents/rules/test-verification.md | 47 +++-- AGENTS.md | 221 ++++++++--------------- 10 files changed, 614 insertions(+), 596 deletions(-) create mode 100644 .agents/commands/fix-pr.md create mode 100644 .agents/commands/handoff.md create mode 100644 .agents/commands/implement.md diff --git a/.agents/agents/orchestrator.md b/.agents/agents/orchestrator.md index c2bae8836..7a13fb65d 100644 --- a/.agents/agents/orchestrator.md +++ b/.agents/agents/orchestrator.md @@ -1,196 +1,67 @@ --- name: orchestrator -description: MUST BE USED for all multi-file operations (3+ files) or cross-domain tasks. Decomposes tasks and coordinates specialist agents. +description: Coordinates complex, cross-domain, or multi-phase work when delegation materially improves correctness or keeps contexts independent. --- -# Pure Orchestrator Agent +# Evidence-Led Orchestrator -**YOU ARE A PURE ORCHESTRATION AGENT. YOU NEVER WRITE CODE.** +Use orchestration for cross-language crypto features, changes with dependent phases, difficult recon, or work that benefits from an independent review. A multi-file documentation update or tightly coupled small fix may be handled directly. Do not delegate merely to satisfy a file count. -## Your Responsibilities +## Responsibilities -1. **Analyze incoming requests** for complexity, dependencies, and architectural impact -2. **Decompose into atomic tasks** that can be parallelized -3. **Assign tasks to appropriate specialists** based on their domain expertise -4. **Monitor progress** and handle inter-agent dependencies -5. **Synthesize results** into coherent deliverables -6. **Maintain architectural integrity** across all work -7. **Track metrics** (token usage, timing, cost) and report them in final summary +1. Establish the goal, scope, repository root, branch, constraints, and delivery boundary. +2. Read the relevant `.agents/rules/*.md` and canonical slash command before action. +3. Separate verified facts, assumptions, decisions, and unverified behavior. +4. Decompose work into the fewest independently committable phases. +5. Coordinate specialists only where their domain expertise changes the outcome. +6. Preserve branch safety, plan state, current verification evidence, and clean handoffs. +7. Require an independent local review and close the plan lifecycle before PR delivery. -## When to Activate +## Planning -Use orchestrator for: +Use early parallel work only for genuinely independent structural discovery. Shared files, APIs, assumptions, generated bindings, and native/TypeScript boundaries make phases dependent; run those phases sequentially with fresh context. -- Tasks touching 3+ files -- Cross-language operations (e.g., TypeScript + C++) -- New feature development with multiple components -- Refactoring that spans multiple domains -- Cryptographic implementations requiring both native and JS layers +Ask structural questions once before implementation when a wrong answer would discard substantial work. Resolve later non-structural choices from the issue, codebase, and established patterns, then record them under **Assumptions**. Stop only when a late discovery invalidates the structure or a required external capability blocks a diff-changing verification. -## Task Decomposition Pattern +For new `/implement` work, keep `plans/todo/-.md` as the source of truth for the live tracker, decisions, assumptions, evidence, and unverified items. Do not create fake retroactive plans for branches already underway. -When you receive a request: +## Model routing -1. **Map all dependencies** +- Bounded implementation and routine verification: Sol at default reasoning. +- General independent review and a failed implementation retry: Sol at high reasoning. +- Initial recon, difficult design, and focused crypto correctness review: Astra. +- Explicit user choices and live provider capabilities override defaults. - - Which layers are affected? (JS, C++, native bridging) - - What are the data flows? - - Are there shared types or interfaces? +These instructions select delegated models; they do not switch the active model. Never silently invoke separately billed tools. Use the minimum useful number of agents. -2. **Identify parallelization opportunities** +## Phase contract - - Which tasks are independent? - - What can run concurrently? - - What must be sequential? +Give each agent a self-contained brief containing: -3. **Create explicit task boundaries** +- Actual repo root from `git rev-parse --show-toplevel`. +- Expected branch and instruction to stop if it differs. +- Exact phase scope and files. +- Relevant issue text, verified recon, rules, and prior corrections. +- Checks selected by changed behavior and affected dependencies. +- Existing evidence that should be reused. +- Required return: paths, commit SHA, checks/results/platforms, deviations, and unfinished work. - - Each specialist gets a clear, focused scope - - Define success criteria - - Specify interfaces/contracts between tasks +Each implementation phase commits through real hooks and leaves a clean tree. Verify the reported result with `git rev-parse HEAD` and `git status --porcelain`. Retry a failed phase once with fresh reviewer-tier context, then stop and report. -4. **Assign to specialists** - - typescript-specialist: TypeScript API surface, types, JS implementations - - cpp-specialist: C++ Nitro Modules, OpenSSL 3.6+ integration, native code - - crypto-specialist: Cryptographic correctness, algorithm implementation, security - - testing-specialist: Test strategies (note: tests run in RN app environment) +## Evidence policy -## Orchestration Examples +Track evidence by commit SHA, exact tool or test, result, and platform. Reuse current evidence; do not ask every phase and reviewer to rerun the same broad suite. -### Example 1: New Crypto Feature (WebCrypto API) +Run the package Jest script only for actual Node-side changes: `cd packages/react-native-quick-crypto && bun run test`. Native runtime changes use the example app and the relevant platform. A full foundational shared-crypto suite requires a stated cross-cutting reason or unexplained failure and one owner. -``` -User Request: "Implement subtle.encrypt/decrypt for AES-GCM" +Documentation-only work needs path, link, command, and consistency validation rather than runtime tests. -Orchestrator analyzes: -- Scope: TypeScript API, C++ implementation, OpenSSL 3.6+ -- Requires: Type definitions, native implementation, bridging +## Review and delivery -Decomposition: -Wave 1 (Foundation): - - crypto-specialist: Review WebCrypto spec, analyze Node.js ncrypto implementation - - typescript-specialist: Define TypeScript types matching WebCrypto API +Use a fresh independent reviewer for the complete `origin/main...HEAD` diff and uncommitted work. The reviewer prints Fix/Skip/Ask decisions and clear Fix items proceed immediately. Local review never waits for a bot. -Wave 2 (Implementation): - - cpp-specialist: Implement AES-GCM using OpenSSL 3.6+ EVP APIs - - typescript-specialist: Create Nitro Module bindings +Before PR delivery, verify commits, clean status, scoped evidence, and any diff-changing runtime behavior. Move the exact completed plan from `plans/todo/` to `plans/done/` in the same branch and remove the ignored progress stub. Then use `/pr` to push and create or update the PR. -Wave 3 (Validation): - - crypto-specialist: Verify algorithm correctness, edge cases - - testing-specialist: Design test strategy for RN environment -``` +## Final report -### Example 2: Refactoring to Modern C++ - -``` -User Request: "Migrate hash functions from OpenSSL 1.1.1 to 3.6+" - -Orchestrator analyzes: -- Scope: Multiple C++ files, OpenSSL API changes -- Requires: Understanding deprecations, modern patterns - -Decomposition: -Wave 1 (Research): - - cpp-specialist: Identify all OpenSSL 1.1.1 usage patterns - - crypto-specialist: Map deprecated APIs to OpenSSL 3.6+ equivalents - -Wave 2 (Migration): - - cpp-specialist: Update to EVP_* APIs, modernize C++ patterns - -Wave 3 (Validation): - - crypto-specialist: Ensure cryptographic correctness maintained - - testing-specialist: Verify no regressions -``` - -### Example 3: Node.js Polyfill Feature - -``` -User Request: "Add support for crypto.pbkdf2" - -Orchestrator analyzes: -- Scope: Node.js compatibility, OpenSSL integration -- Requires: API compatibility, native implementation - -Decomposition: -Wave 1 (Specification): - - crypto-specialist: Review Node.js API and ncrypto implementation - - typescript-specialist: Define TypeScript API matching Node.js - -Wave 2 (Implementation): - - cpp-specialist: Implement using OpenSSL 3.6+ PBKDF2 - - typescript-specialist: Create JS wrapper with Node.js semantics - -Wave 3 (Compatibility): - - crypto-specialist: Verify output matches Node.js - - testing-specialist: Create compatibility test suite -``` - -## Communication Protocol - -### Input Format - -You receive tasks in natural language. Extract: - -- Goal (what needs to be accomplished) -- Constraints (compatibility, performance, security) -- Context (related code, dependencies) - -### Output Format - -Provide: - -1. **Task Analysis**: What needs to be done and why -2. **Dependency Map**: What depends on what -3. **Wave Plan**: Sequential waves of parallel tasks -4. **Specialist Assignments**: Who does what -5. **Success Criteria**: How to validate completion -6. **Metrics Summary**: Token usage, timing, estimated cost - -## Rules You Must Follow - -1. **Never commit to main** - always create a feature branch (`feat/`, `fix/`, `refactor/`) before the first commit -2. **Never write code yourself** - always delegate to specialists -3. **Always parallelize independent tasks** - maximize efficiency -4. **Enforce architectural rules** from `.agents/rules/*.md` -5. **Track all metrics** - token usage, timing, cost estimates -6. **Validate completeness** - ensure all requirements met before marking done -7. **Report clearly** - synthesize specialist work into coherent summary - -## Available Specialists - -- **typescript-specialist**: TypeScript code, types, API surface, Nitro bindings -- **cpp-specialist**: C++20 code, OpenSSL integration, smart pointers, modern patterns -- **crypto-specialist**: Cryptographic correctness, algorithm implementation, security analysis -- **testing-specialist**: Test strategy design (acknowledges tests run in RN app) - -## Specialist Selection Logic - -``` -if (task involves TypeScript types or JS API): - assign typescript-specialist - -if (task involves C++ or OpenSSL): - assign cpp-specialist - -if (task involves cryptographic algorithms or security): - assign crypto-specialist - -if (task involves test design or validation strategy): - assign testing-specialist - -if (task spans multiple domains): - decompose and assign to multiple specialists in waves -``` - -## Success Metrics - -Track and report: - -- Total tokens used across all specialists -- Time elapsed (wall clock) -- Estimated cost (if applicable) -- Number of files modified -- Test coverage (when applicable) -- Security considerations addressed - -Remember: You are the conductor, not the musician. Your job is to ensure the symphony of specialists produces harmonious, high-quality code. +Report outcome, changed files or behavior, commit and PR identifiers, current checks by SHA/tool/platform, decisions, and genuine unverified residue. Do not report token, timing, or cost metrics unless the user asks for them. diff --git a/.agents/commands/address-pr-feedback.md b/.agents/commands/address-pr-feedback.md index c12704d38..dd974d70b 100644 --- a/.agents/commands/address-pr-feedback.md +++ b/.agents/commands/address-pr-feedback.md @@ -1,213 +1,148 @@ # /address-pr-feedback - Address PR Feedback -Fetch and address all review bot feedback on the current PR. +Fetch, validate, and resolve all unaddressed feedback on the current PR. Invoking this workflow authorizes replies, the commits needed for fixes, and the qualified push of those commits. Do not reply to PR feedback outside an explicitly invoked feedback workflow. -## Instructions +Do not require CodeRabbit or any other reviewer to exist or finish. Process the feedback that is present; local `/review` remains independent. -### 1. Identify the PR +## 1. Identify and register the PR ```bash -gh pr view --json number,url,state --jq '{number, url, state}' +gh pr view --json number,url,state,author,headRefName,headRefOid --jq '{number,url,state,author,headRefName,headRefOid}' ``` -If no PR exists for the current branch, abort with a message. +Abort if the branch has no open PR. Register its URL with the host thread if a PR-link tool is available. -### 2. Check that review bots are done - -CodeRabbit reviews asynchronously. Before addressing feedback, verify it has finished. +Capture the number: ```bash -# Get all reviews on the PR -gh pr view --json reviews --jq '.reviews[] | {author: .author.login, state: .state}' - -# Check PR comments for bot activity (MUST use --paginate for large PRs) -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate \ - --jq '[.[] | .user.login] | unique' +PR=$(gh pr view --json number --jq .number) ``` -**CodeRabbit**: Look for a PR comment containing "Walkthrough" or a review with `coderabbitai[bot]` as author. If not present, inform the user: - -> "CodeRabbit hasn't reviewed this PR yet. Wait for its review or run `@coderabbitai review` as a PR comment, then re-run this command." - -**If the bot hasn't finished, stop here.** Do not proceed to fixing issues with incomplete feedback. - -### 3. Fetch ALL review comments +## 2. Fetch all three feedback sources -**CRITICAL**: Always use `--paginate` with `gh api` for review comments. The default page size is 30, which is easily exceeded when CodeRabbit posts 16+ inline comments plus replies. Without `--paginate`, you will miss comments from later review passes. +Always paginate every endpoint. These are separate datasets and none substitutes for another. -#### 3a. Inline review comments +### Inline review comments and replies ```bash -# Get ALL review comments — MUST use --paginate -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate --jq '.[] | { - id: .id, +gh api "repos/{owner}/{repo}/pulls/$PR/comments" --paginate --jq '.[] | { + id, author: .user.login, - path: .path, - line: .line, - body: .body, - in_reply_to_id: .in_reply_to_id, - created_at: .created_at + path, + line, + body, + in_reply_to_id, + commit_id, + created_at }' ``` -To identify **new unaddressed root comments**, filter by: - -- `in_reply_to_id == null` (root comment, not a reply) -- `user.login == "coderabbitai[bot]"` -- No reply from the PR author (`gh pr view --json author --jq '.author.login'`) exists with matching `in_reply_to_id` - -Useful shortcut to see how many batches exist: +### Review bodies ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate \ - --jq '.[] | select(.user.login == "coderabbitai[bot]") | select(.in_reply_to_id == null) | .created_at' \ - | sort | uniq -c | sort -rn +gh api "repos/{owner}/{repo}/pulls/$PR/reviews" --paginate --jq '.[] | { + id, + author: .user.login, + state, + body, + commit_id, + submitted_at +}' ``` -Each unique timestamp cluster represents one review pass. +Read every non-empty review body. Findings outside the diff, summaries, and multi-item reviews often exist only here. -#### 3b. Outside-diff-range comments (in review body) - -CodeRabbit posts "outside diff range" comments in the **review body**, not as inline comments. These are easy to miss. - -```bash -# Get ALL CodeRabbit reviews with non-empty bodies (includes CHANGES_REQUESTED and COMMENTED states) -gh api "repos/{owner}/{repo}/pulls/{pr}/reviews" --paginate \ - --jq '.[] | select(.user.login == "coderabbitai[bot]") | select(.body | length > 0) | {id: .id, state: .state, submitted_at: .submitted_at}' -``` - -Then fetch each review body: +### General PR comments ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/reviews/{review_id}" --jq '.body' +gh api "repos/{owner}/{repo}/issues/$PR/comments" --paginate --jq '.[] | { + id, + author: .user.login, + body, + created_at +}' ``` -Look for the `⚠️ Outside diff range comments (N)` section in the body. Parse these — they contain file paths, line numbers, and the same comment format as inline comments. +Identify unaddressed root findings. An inline entry with `in_reply_to_id != null` is a reply, not a new root. Account for existing author replies so reruns do not process settled threads or the workflow's own prior replies as findings. -Also look for these sections in review bodies: +## 3. Validate every claim -- **"🧹 Nitpick comments (N)"** — valid code quality items -- **"♻️ Duplicate comments (N)"** — re-raised from prior reviews -- **"🤖 Prompt for AI Agents"** — structured fix instructions +Open the current file and enough context to verify the comment's mechanism and conclusion. Compare the comment's commit to current HEAD when staleness matters. A confident reviewer comment is evidence to investigate, not ground truth. -#### 3c. General PR comments +Classify each item: -```bash -gh api "repos/{owner}/{repo}/issues/{pr}/comments" --paginate \ - --jq '.[] | {id: .id, author: .user.login, body: .body, created_at: .created_at}' -``` +1. **Fix:** Valid and has a clear repository-consistent correction. +2. **Dismiss:** Incorrect, out of scope, or no change is warranted; explain the evidence. +3. **Stale:** Current code already resolves or removes the concern. +4. **Ask:** Two defensible responses materially change behavior or blast radius and repository evidence cannot decide. -### 4. Identify actionable feedback +Use Ask only for genuine user-choice ambiguity. Resolve naming, factoring, and discoverable conventions autonomously. -Collect ALL comments from: +## 4. Print decisions, then act -- Inline review comments (3a) -- Outside-diff-range / nitpick / duplicate comments from review bodies (3b) -- General PR comments (3c) +Print: -Filter to unaddressed items from `coderabbitai[bot]`. +| # | Source | File:Line | Summary | Decision | Rationale | +|---|---|---|---|---|---| +| 1 | Inline / Review body / General | `path:42` | Brief claim | Fix / Dismiss / Stale / Ask | Verified reason | -**Before applying any fix**, first verify the finding against the current code and decide whether a code change is actually needed. If the finding is not valid or no change is required, do not modify code for that item and briefly explain why it was skipped. +If there are no Ask rows, immediately execute every decision without waiting. If Ask rows exist, continue all independent Fix, Dismiss, and Stale items through verification, push when needed, and replies; then ask only the unresolved choices. -For each comment, determine: +## 5. Fix, gate, commit, push, verify SHA -1. **Valid concern** — fix it -2. **False positive** — reply explaining why -3. **Stale** — code was already changed/removed since the comment was posted -4. **Ambiguous** — ask the user which direction to take +The order is mandatory: -### 5. Present decisions for approval +**fix → scoped gates → commit → push → verify remote SHA → reply** -**STOP and present a table** before making any changes. The user must approve the plan first. +Do not post early replies. For fixes: -| # | Source | File:Line | Comment Summary | Decision | Rationale | -| --- | --------------- | -------------------- | ---------------------------- | --------------------- | ----------------- | -| 1 | CR inline | `path/to/file.ts:42` | Brief summary of the comment | Fix / Dismiss / Stale | Why this decision | -| 2 | CR nitpick | `path/to/file.ts:10` | Brief summary | Fix / Dismiss / Stale | Why | -| 3 | CR outside-diff | `path/to/file.ts:78` | Brief summary | Fix / Dismiss / Stale | Why | +1. Edit the validated scope. +2. Run checks selected by the changed behavior and affected toolchains. +3. Reuse still-current evidence and rerun only checks invalidated by the fix. +4. Run Node Jest only for actual Node-side changes with `cd packages/react-native-quick-crypto && bun run test`. +5. Build or drive the example app when native runtime behavior requires it; docs-only fixes need no runtime retest. +6. Stage explicit paths and commit through `/commit`. +7. Push normally, never with `--no-verify`. -Wait for the user to: +Verify local and remote SHAs: -- **Approve all** — proceed with all decisions as proposed -- **Override specific rows** — change the decision for individual items (e.g., "dismiss #3 instead of fixing") -- **Ask questions** — clarify any items before approving - -**Do not proceed to step 6 until the user approves.** - -### 6. Apply fixes locally (do NOT reply to bots yet) - -**CRITICAL — DO NOT reply to bot threads in this step.** Bot replies must happen _after_ push so the bot can verify against the actual remote. Replying with "Fixed" before the commit is on the remote causes the bot to re-flag the comment as unfixed (it reads the remote, not your working tree). - -For each item that needs a code change: +```bash +BRANCH=$(git branch --show-current) +LOCAL_SHA=$(git rev-parse HEAD) +REMOTE_SHA=$(git rev-parse "origin/$BRANCH") +PR_SHA=$(gh pr view "$PR" --json headRefOid --jq .headRefOid) +test "$LOCAL_SHA" = "$REMOTE_SHA" +test "$LOCAL_SHA" = "$PR_SHA" +``` -1. Read the file and understand the context around the flagged line. -2. Apply the fix. +If no code or documentation changed because every item is Dismiss or Stale, skip commit and push, use the current PR head SHA, and proceed to replies. -Do not post any thread replies, PR comments, or "Fixed" messages yet. Just edit code. +## 6. Reply after verification -### 7. Run quality gates +Reference the verified SHA and concise evidence. -After all fixes are applied: +For inline roots, reply on the existing thread: ```bash -bun tsc +gh api "repos/{owner}/{repo}/pulls/$PR/comments" -X POST -f body="Fixed in — " -F in_reply_to= ``` -All must pass before committing. - -### 8. Commit and push +Use the same mechanism for Dismiss or Stale with the reason instead of claiming a fix. -If any code changes were made: +Review-body findings have no inline thread. Post one consolidated top-level comment keyed to review IDs: ```bash -git add -git commit -m "fix: address PR review feedback from CodeRabbit" -git push +gh pr comment "$PR" --body-file ``` -**Verify the push landed before moving on.** Confirm `git log origin/ -1` matches your local HEAD, or check `gh api repos/{owner}/{repo}/pulls/{pr} --jq .head.sha`. The bots will read this SHA when re-evaluating, so the reply in step 9 must reference code that is actually on it. - -### 9. Reply to bot threads - -Now that the fix is on the remote, post replies. Reference the new commit SHA in "Fixed" replies so the bot can verify and so the timeline is auditable later. - -**Reply rules:** - -1. **Inline review comments (3a)** — reply on the conversation thread: - - ```bash - gh api "repos/{owner}/{repo}/pulls/{pr}/comments/{comment_id}/replies" \ - -X POST -f body="@coderabbitai Fixed in — " - ``` - -2. **Review-body / outside-diff items (3b)** — no inline thread exists. Post a top-level PR comment: - - ```bash - gh pr comment {pr} --body "@coderabbitai Addressed in : - - Fixed: - - Dismissed: " - ``` - -3. **General PR comments (3c)** — issue comments don't support threaded replies. Post a new PR comment referencing the original: - ```bash - gh pr comment {pr} --body "@coderabbitai Re: comment {comment_id} — Fixed in — " - ``` - -**CodeRabbit replies MUST start with `@coderabbitai`** or the bot will not see them. - -For false positives / stale, use the same reply mechanism with an explanation instead of "Fixed": +General issue comments do not support review threading. Post a new PR comment that references the original comment ID: ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/comments/{comment_id}/replies" \ - -X POST -f body="@coderabbitai " +gh pr comment "$PR" --body "Re: comment — addressed at — " ``` -### 10. Report summary +Do not require an `@coderabbitai` prefix unless that reviewer specifically requires it. -Present a summary to the user: +## 7. Report -- **Fixed**: List of issues that were fixed with brief descriptions -- **Dismissed**: List of false positives with reasoning -- **Stale**: Comments on code that was already changed/removed -- **Needs input**: Any ambiguous items requiring user decision -- **Quality gates**: Pass/fail status +Report Fixed, Dismissed, Stale, Needs input, checks with SHA/platform, pushed SHA, and reply status. If feedback changed PR scope or delivery, update the PR body through `--body-file`. diff --git a/.agents/commands/commit.md b/.agents/commands/commit.md index 06b8f8f81..f747cb5ad 100644 --- a/.agents/commands/commit.md +++ b/.agents/commands/commit.md @@ -1,54 +1,65 @@ -# Commit Changes +# /commit - Commit Changes -Stage and commit the current changes with a well-crafted message. +Stage and commit only the current task's changes. Standalone `/commit` does not push. ## Instructions -When activated, commit the current working tree changes: - -1. **Sync with remote**: - - Run `git fetch origin main` to get latest upstream - - Run `git log HEAD..origin/main --oneline` to check if main has moved ahead - - If it has, warn the user but don't rebase automatically - -2. **Ensure we're not on main**: - - Run `git branch --show-current` - - If on `main`, create a new feature branch: - - Look at the staged/unstaged changes to infer a branch name - - Run `git checkout -b feat/` - - Inform the user of the new branch name - -3. **Review changes**: - - Run `git diff --stat` and `git diff --staged --stat` to see what's changed - - If nothing is staged, run `git add -A` to stage everything - - Run `git diff --staged --stat` to confirm what will be committed - -4. **Run code quality checks before committing**: - - **C++ files**: If any `.cpp`/`.hpp`/`.h` files are staged, run: - ```bash - clang-format -i - ``` - Then re-stage them with `git add`. - - **TypeScript files**: If any `.ts`/`.tsx` files are staged, run: - ```bash - npx prettier --write - ``` - Then re-stage them with `git add`. - - **Type check**: Run `cd packages/react-native-quick-crypto && bun tsc --noEmit` to verify types. - -5. **Generate commit message**: - - Use conventional commit format: `type: short description` - - Types: `feat`, `fix`, `refactor`, `chore`, `docs`, `test` - - If the change is substantial, add a body paragraph separated by a blank line - - Body should explain **what** changed and **why**, not how (the diff shows how) - - Keep the subject line under 72 characters - -6. **Commit** (with 120000ms timeout — pre-commit hooks run lint-staged, clang-format, tsc, and bob build): - ```bash - git commit -m "" - ``` - **NEVER use `--no-verify`.** Pre-commit hooks exist to catch errors. If they fail, fix the issue. - -7. **Report** the commit hash and summary to the user - -If the user provides arguments (e.g., `/commit "fix: resolve race condition"`), use that as the commit message instead of generating one. +### 1. Synchronize and guard the branch + +```bash +git fetch origin main +git branch --show-current +git log HEAD..origin/main --oneline +git status --short +``` + +Never commit on `main`. If the task started on `main`, create a correctly named `feat/`, `fix/`, or `refactor/` branch before committing and report it. If `origin/main` moved ahead, report that fact but do not rebase automatically. + +### 2. Define the commit scope + +Review both staged and unstaged changes: + +```bash +git diff --stat +git diff --staged --stat +git diff +git diff --staged +``` + +Preserve unrelated edits. Stage explicit task paths with `git add ...`; never default to `git add -A`. If ownership of a changed path is genuinely unclear, leave it unstaged and report it. + +### 3. Run relevant pre-commit checks + +Format and verify what the commit changes: + +- C++ files: run `clang-format -i` on the explicit changed `.cpp`, `.cc`, `.cxx`, `.hpp`, and `.h` paths, then stage them again. +- TypeScript or JavaScript files: run the repository's Bun-backed Prettier/lint scripts for the affected workspace, then stage resulting task-file edits. +- TypeScript API or implementation: run the relevant `bun tsc`. +- Node-side behavior: run `cd packages/react-native-quick-crypto && bun run test` only when actual Node-side code changed. +- ncrypto/OpenSSL changes: run `scripts/check-ncrypto-openssl-deprecations.sh` and other affected native checks. +- Documentation-only changes: run link/path/command consistency checks and `git diff --check`; no runtime test is required. + +Reuse current evidence when it covers the staged diff. Do not run a broad suite by default. + +### 4. Confirm the index + +```bash +git diff --staged --stat +git diff --staged +``` + +Abort if nothing is staged. Confirm no unrelated file entered the index. + +### 5. Commit through mandatory hooks + +Use a conventional message with a subject under 72 characters. If the user supplied a message, use it. A body should explain what and why. + +```bash +git commit -m ": " +``` + +Allow at least 120 seconds. The tracked hook runs `bun lint-staged`, C++ `clang-format --dry-run --Werror`, `bun tsc`, and `bun --filter="react-native-quick-crypto" prepare`. Never use `--no-verify` or `-n`; fix failures and retry normally. + +### 6. Report + +Report the commit SHA, subject, staged paths, checks run, and any uncommitted paths deliberately left alone. Do not push unless a separately invoked workflow such as `/pr`, `/implement`, or `/address-pr-feedback` authorizes it. diff --git a/.agents/commands/fix-pr.md b/.agents/commands/fix-pr.md new file mode 100644 index 000000000..9201bd2be --- /dev/null +++ b/.agents/commands/fix-pr.md @@ -0,0 +1,5 @@ +# /fix-pr - Address PR Feedback + +This is a short alias for `/address-pr-feedback`. + +Read `.agents/commands/address-pr-feedback.md` completely, then execute that canonical workflow without adding or omitting steps. diff --git a/.agents/commands/handoff.md b/.agents/commands/handoff.md new file mode 100644 index 000000000..d660b61ed --- /dev/null +++ b/.agents/commands/handoff.md @@ -0,0 +1,30 @@ +# /handoff - Session Handoff + +Produce a concise, self-contained handoff so the next session can resume without trusting conversation history. + +## Gather + +Read the current branch, recent commits, working tree, linked issue or PR, and the exact active plan if one exists: + +```bash +git branch --show-current +git log --oneline -10 +git status --short +gh pr view --json number,url,state,title,headRefOid 2>/dev/null || true +``` + +Check `.agents/progress/claude-progress.md` and its referenced plan, but do not assume a stale or missing stub describes the branch. + +## Output + +Include only relevant sections: + +- **State:** branch, HEAD SHA, clean or exact uncommitted paths, issue, PR URL/state/head SHA, and active plan phase. +- **Completed:** concrete work with commit SHAs or file paths. +- **Verified:** exact scoped checks, tools or tests, result, commit SHA, and platform. Distinguish native build, installed-app, simulator/device, Node-side, and documentation evidence. +- **Unverified:** every claim or runtime behavior not actually exercised, why it matters, and what would settle it. +- **Decisions:** non-obvious choices and rationale. +- **Next actions:** ordered commands or files that let the next session continue without a clarification round. +- **Sibling dependencies:** related repository branch, SHA, PR, unpublished change, or external dependency when relevant. + +State whether subagent reports were independently checked. Do not report a test as current if relevant edits occurred after its recorded SHA. Do not hide failures or imply a push, PR update, device run, or review happened when it did not. diff --git a/.agents/commands/implement.md b/.agents/commands/implement.md new file mode 100644 index 000000000..81dc965ea --- /dev/null +++ b/.agents/commands/implement.md @@ -0,0 +1,139 @@ +# /implement - Implement an Issue End-to-End + +Take one GitHub issue from recon through an open PR with minimal human intervention. `$ARGUMENTS` is a bare issue number, `#N`, or a full issue URL. With no argument, ask for the issue and stop. + +Invoking `/implement` explicitly authorizes the qualified push and PR creation or update at the end of this workflow. It does not authorize bypassing hooks, shipping known failures, overwriting unrelated work, or guessing through a structural product decision. + +## 1. Read the issue + +Use the issue API rather than search snippets: + +```bash +gh issue view --json number,title,body,labels,comments,state,closedByPullRequestsReferences +``` + +Normalize the returned number. If the issue is closed or already has a closing PR, stop and report it. Derive a lowercase, hyphenated slug of at most five words and use the exact `-` identifier for both the branch and plan. + +## 2. Fresh recon + +Use one fresh Astra recon subagent. Give it the complete issue text and comments plus the actual repository root returned by: + +```bash +git rev-parse --show-toplevel +``` + +Recon must read `AGENTS.md`, the relevant `.agents/rules/*.md`, Node.js `$REPOS/node/deps/ncrypto` before new crypto implementation, and the actual files it cites. It must not edit. + +Require the report to include: + +1. Verified files and line anchors, with each claim based on opening the file. +2. Existing repository patterns to mirror. +3. Two to five independently committable phases and their dependencies. +4. Targeted tests and affected toolchains. +5. Native platforms and driveable example-app checks. +6. Structural questions only. +7. Security and compatibility risks. +8. Explicitly unverified claims. + +Recount issue-provided file lists or quantities instead of trusting them. Mark inference as inference. If recon finds no change to make, stop and report. + +## 3. Resolve structural forks once + +Ask before code only when a wrong answer would discard substantial work: an API contract, a new cross-layer shape, a user-visible behavior the issue does not define, or designs with materially different security or compatibility impact. Present two or three concrete options with the recommendation first. + +Naming, file placement, factoring, and choices established by repository patterns are not structural questions. After this point, record reasonable decisions under **Assumptions** and continue. If a late discovery truly invalidates the chosen structure, stop and report rather than layering work onto it. + +## 4. Guard the checkout and create the tracker + +Before creating a branch: + +```bash +git status --porcelain +git rev-parse --show-toplevel +git fetch origin main +git show-ref --verify --quiet refs/heads//- +``` + +The working tree must be clean. Do not stash or absorb unrelated edits. Confirm the real repository root and stop if the branch already exists. Create `/-` from `origin/main`, where type is `fix`, `feat`, or `refactor`. + +Run `mkdir -p plans/todo`, then create `plans/todo/-.md` with: + +- Problem and intended outcome. +- **Live tracker** checklist for every implementation, qualification, review, and delivery phase. +- **Decisions** for user-selected structural choices. +- **Assumptions** for non-structural choices made during execution. +- **Evidence** entries containing commit SHA, exact tool or test, result, and platform. +- **Unverified** items with the condition that would settle each one. + +Point the ignored `.agents/progress/claude-progress.md` stub at the active plan and commit the plan. Never manufacture a retroactive tracker for an already-running branch merely to claim this workflow was followed. + +## 5. Implement sequentially with fresh context + +Run each dependent phase in order with one fresh Sol subagent at default reasoning. Parallelize only early work that is structurally independent and cannot overlap files or assumptions. + +Each phase prompt must include the actual repo root, expected branch, the plan path, that phase only, relevant recon evidence, prior corrections, applicable rules, and the targeted verification policy. Require the phase agent to: + +1. Confirm the repository root and branch before editing. +2. Re-open every file and verify recon claims. +3. Implement only its assigned phase. +4. Add or update tests selected by changed behavior and dependencies. +5. Run affected checks without repeating still-current evidence. +6. Update the plan tracker, decisions, assumptions, and evidence. +7. Stage only its files and make a conventional commit through the real hooks. +8. Return changed paths, commit SHA, exact checks and platforms, deviations, and unfinished work. + +After every phase, independently verify: + +```bash +git rev-parse HEAD +git status --porcelain +``` + +The SHA must have advanced and the tree must be clean. If the phase fails to commit, leaves changes, or reports unverified required behavior, retry once with a fresh Sol reviewer-tier subagent at high reasoning using the failure output and first report. Stop after the second failure. + +When a phase corrects recon, update the plan and all later prompts. Do not propagate a disproven premise. + +## 6. Qualify the branch + +Select checks from the actual diff and reuse valid phase evidence keyed by SHA, tool or test, and platform. + +- Run relevant TypeScript, lint, formatting, generated-code, C++, OpenSSL, and native checks for every changed toolchain. +- Run `cd packages/react-native-quick-crypto && bun run test` only when actual Node-side code changed. Do not substitute bare `bun test`. +- Test native runtime behavior in the example app. Attach to an existing RNQC app and Metro first; do not restart another project or take over its port. Use `/tmp/rnqc-metro.log` for RNQC Metro diagnostics. +- Build and install the example app when a native change requires a rebuild. Drive the affected tests or flow when feasible and record the platform. +- Do not rerun broad suites per phase. A full foundational shared-crypto suite requires a stated cross-cutting reason or unexplained failure, one owner, and one reusable result. +- Documentation-only changes need link and consistency checks, not a runtime retest. + +A missing credential, unavailable platform, or unverified behavior blocks delivery only when a failure could require changing the diff. Stop and state the exact check needed. If the user explicitly directs shipment, disclose the unverified behavior and residual risk in the PR. + +Qualification fixes go to a fresh Sol implementation subagent and must be committed. Retry at most twice. + +## 7. Independent local review + +Use a fresh reviewer that did not implement the branch: Sol at high reasoning for general review, or Astra for focused difficult crypto correctness review. Follow `.agents/commands/review.md`, including `git fetch origin`, the `origin/main...HEAD` diff, uncommitted state, and every changed toolchain. + +Classify findings as Fix, Skip, or Ask. Apply clear Fix items immediately and continue independent fixes. Under `/implement`, do not add another approval round: resolve Ask items from the issue, code, and established decisions when possible and record the result under **Assumptions**. Stop only for a genuine unresolved structural choice. Commit review fixes and rerun only invalidated checks. + +Local review is required even if a review bot exists; it never waits for a bot. + +## 8. Complete the plan before the PR + +When implementation, qualification, and local review are complete, move the exact tracker in the same branch: + +```bash +mkdir -p plans/done +git mv plans/todo/-.md plans/done/-.md +rm -f .agents/progress/claude-progress.md +``` + +Carry any genuinely outstanding verification item with an owner and disclosure. Commit the plan move before opening the PR. If more than one plan could match, move none and stop for disambiguation. Work that is not implemented remains in `plans/todo/`. + +## 9. Finish with /pr + +Read and execute `.agents/commands/pr.md` completely. Recompute scope, verification, and delivery from the actual diff rather than recon. Use `Closes #`, push the qualified commits, reuse an existing PR for the branch when present, and create one otherwise. + +If the host exposes a PR-link registration tool, register the full PR URL with the current thread immediately after creating or taking ownership of the PR. + +## Final report + +Keep the report concise: changed behavior, PR URL or exact blocker, independent review findings and dispositions, assumptions, verification evidence by SHA/tool/platform, and explicitly unverified residue. diff --git a/.agents/commands/pr.md b/.agents/commands/pr.md index e7d690c3b..71cd46347 100644 --- a/.agents/commands/pr.md +++ b/.agents/commands/pr.md @@ -1,38 +1,93 @@ -# /pr - Create Pull Request +# /pr - Create or Update a Pull Request -Create a pull request for the current branch. +Create or update the PR for the current branch. Invoking `/pr` authorizes the qualified push required for this workflow. ## Instructions -When activated, create a pull request for the current branch: +### 1. Establish accurate scope -1. **Verify branch state**: - - Run `git branch --show-current` to get the current branch name - - Ensure we're not on `main` (abort if so) - - Run `git log main..HEAD --oneline` to see commits to include +```bash +git fetch origin +BRANCH=$(git branch --show-current) +git status --short +git log origin/main..HEAD --oneline +git diff --stat origin/main...HEAD +git diff --name-only origin/main...HEAD +``` -2. **Push the branch** (if not already pushed): - - Run `git push -u origin ` +Abort on `main`. The working tree must be clean before push. Use `origin/main`, not a potentially stale local `main`, and use the three-dot diff for PR scope. -3. **Check for related issues**: - - Look at the branch name for issue numbers (e.g., `fix/896-buffer-import` references #896) - - Check commit messages for issue references - - Run `gh issue list --state open --limit 20` to see recent open issues that might be related - - If the PR resolves an issue, note it for the body +### 2. Confirm qualification -4. **Generate PR title and body**: - - Title: Use conventional commit format based on the primary change (e.g., `fix: import Buffer from react-native-quick-crypto`) - - Body should include: - - **Summary**: Brief description of what this PR does - - **Changes**: Bullet list of key changes - - **Testing**: How to test the changes (if applicable) - - **Issue references**: Add `Fixes #XXX` or `Closes #XXX` for any issues this PR resolves (these will auto-close the issues when merged) +Review current evidence for the actual HEAD and every changed toolchain. A qualified branch has: -5. **Create the PR**: - ```bash - gh pr create --title "" --body "<body>" --base main --assignee @me - ``` +- Required commits created through mandatory hooks. +- Relevant scoped checks passing at the current SHA. +- Native behavior built and exercised on the relevant platform when the diff requires it. +- No unverified runtime behavior that could change the diff, unless the user explicitly directed shipment and the PR discloses the gap and risk. +- An independent local review completed without waiting for a bot. -6. **Report the PR URL** to the user +Do not rerun still-current broad evidence merely to open the PR. -If the user provides arguments (e.g., `/pr "Custom title"`), use that as the PR title instead of generating one. +### 3. Complete the exact plan lifecycle + +If the branch identifier is `<type>/<N>-<slug>`, look only for `plans/todo/<N>-<slug>.md`. Do not fuzzy-match or create a retroactive plan. + +If that exact plan exists and the implementation is complete: + +```bash +mkdir -p plans/done +git mv plans/todo/<N>-<slug>.md plans/done/<N>-<slug>.md +rm -f .agents/progress/claude-progress.md +``` + +Carry genuinely outstanding verification items with an owner, then commit the move through `/commit` before pushing. If multiple candidates exist or the work is incomplete, move none and report the mismatch. + +### 4. Reuse an existing PR + +Check for a PR whose head is the current branch: + +```bash +gh pr list --head "$BRANCH" --state all --json number,url,state,title,headRefOid +``` + +Reuse an open PR instead of creating a duplicate. If the only matching PR is closed or merged, stop and report before creating another. + +### 5. Build the PR description from the actual diff + +Write the body to a temporary Markdown file and pass it with `--body-file`. Include: + +- **Summary:** outcome and rationale. +- **Changes:** concrete branch changes. +- **Testing:** exact commands, results, commit SHA, and native platform. Distinguish reused evidence from checks run during PR preparation. +- **Delivery:** what merging actually delivers. Agent/docs changes take effect in the repository on merge; CI changes alter validation on merge; package TypeScript/C++/Nitro changes reach consumers only after an npm release; native changes additionally require the consuming app to rebuild and ship. Example-app-only changes do not publish the library. +- **Not verified:** only explicit residue and risk, if shipment was authorized despite it. +- **Issue:** `Fixes #N` or `Closes #N` when the PR resolves the issue. + +Derive issue references from the exact branch identifier, issue context, and commits. Do not attach unrelated recent issues. + +### 6. Push and create or update + +```bash +git push -u origin "$BRANCH" +``` + +Never use `--no-verify`. Verify the remote branch SHA matches local HEAD before continuing. + +For an existing open PR, update it: + +```bash +gh pr edit <number> --title "<title>" --body-file <body-file> +``` + +Otherwise create it: + +```bash +gh pr create --title "<title>" --body-file <body-file> --base main --assignee @me +``` + +Use a conventional-commit-style title unless the user supplied one. + +### 7. Register and report + +Immediately register the full PR URL with the host thread when a PR-link tool is available. Report the URL, pushed SHA, qualification evidence, and any disclosed unverified behavior. diff --git a/.agents/commands/review.md b/.agents/commands/review.md index c2c23a5f7..ef41ecf9c 100644 --- a/.agents/commands/review.md +++ b/.agents/commands/review.md @@ -1,59 +1,81 @@ -# /review - Code Review Branch Commits +# /review - Review Branch Changes -Review all commits on the current branch since diverging from main. +Review every branch change since the merge base with current `origin/main`, including uncommitted work. -## Prerequisites +## Independence -**IMPORTANT**: A reviewer should not be the same "person" who wrote the code. Before starting, check if this is a fresh context/session: +The reviewer must not be the agent that wrote the changes. If this session implemented or materially shaped the diff, use one fresh reviewer: Sol at high reasoning for general work or Astra for a focused difficult crypto-correctness review. Give it the actual changed-file list, applicable rules, and current verification evidence. Do not create extra reviewers unless the diff has genuinely independent domains that one reviewer cannot cover well. -- **If there is prior conversation history in this session** (e.g., you helped write the code being reviewed), do NOT review it yourself — your context is biased. Instead, spawn a fresh reviewer: - - Launch a subagent (synchronously — `run_in_background: false`) with a prompt telling it to perform the full review defined in the **Instructions** section below on the current branch, and to return its findings as: a summary, positives, and a severity-ranked list of issues (each with `file:line`, description, and a proposed action). Paste the Instructions criteria into the prompt so the subagent doesn't need to re-read this file. - - Pick the subagent type by what the diff actually touches: `crypto-specialist` for crypto/algorithm changes, `cpp-specialist` for `cpp/`, `typescript-specialist` for TS-only changes, `general-purpose` otherwise. Spawn more than one in parallel when the diff spans domains. - - **Scope the prompt to THIS branch's actual changes, not the generic template.** Before spawning, run `git diff --stat origin/main...HEAD` (three dots — see step 3) and put the concrete context into the prompt: what the branch does, which subsystem it touches (this repo spans C++/OpenSSL under `packages/react-native-quick-crypto/cpp`, the TypeScript package under `src/`, the Expo config plugin, the `example/` RN app and its test suites, `docs/`, and CI workflows — name the ones actually changed), and the list of changed files. Tell the subagent to open and review **every** changed file, including non-C++ ones (`.ts`, `.tsx`, podspec, Gradle, `.github/workflows`, `.agents/`), and to validate **each** changed toolchain rather than assuming one check covers the diff. - - The subagent starts with a clean context and did NOT write the code, so its review is unbiased. - - When it returns, relay its review to the user verbatim, then run the **Follow-up** fix-plan step yourself (the subagent can't interact with the user). -- **If this is a fresh context** (no prior history — you did not write this code), perform the review directly. +Local review is required and is not contingent on CodeRabbit or any other bot existing or finishing. ## Instructions -When activated, perform a full code review of the commits since branching from main: +### 1. Establish accurate scope -1. **Sync the base**: Run `git fetch origin` first. Local `main` is often stale (a PR merged upstream but not pulled locally), which silently drags already-merged commits into the review scope and balloons the diff. Use `origin/main` as the base for everything below. -2. **Get the commits**: Run `git log origin/main..HEAD --oneline` to see all commits on this branch -3. **Get the full diff**: Run `git diff origin/main...HEAD` to see all changes. **Three dots.** For `diff`, two dots compares the two endpoints, so anything merged into `origin/main` since the branch point shows up as an inverse diff — as if this branch deleted it. Three dots diffs against the merge-base, which is what you want. Note that step 2's `git log` takes **two** dots: the same syntax means different things for `log` and `diff`. -4. **Also check the working tree**: run `git status --short` and `git diff`. Uncommitted changes are in scope — review them alongside the commits, and say which findings apply to uncommitted work. -5. **For each file changed**, read enough context to understand the changes -6. **Review for**: - - Correctness and logic errors - - Consistency with existing patterns in the codebase - - TypeScript best practices - - C++ best practices (if touching native code) - - Cryptographic correctness (if touching crypto code) - - Potential bugs or edge cases - - Missing error handling - - Code clarity and maintainability -7. **Provide a structured review** with: - - Summary of what the branch does - - Positives (what's done well) - - Issues & suggestions (ranked by severity) - - Recommended actions (if any) +```bash +git fetch origin +git log origin/main..HEAD --oneline +git diff --stat origin/main...HEAD +git diff --name-only origin/main...HEAD +git diff origin/main...HEAD +git status --short +git diff +git diff --staged +``` -Verify the toolchains the diff actually touches: `bun tsc` for TypeScript, `bun run test` (in `packages/react-native-quick-crypto` — `run` matters, bare `bun test` is Bun's own runner, not the package's jest) if node-side code changed, `clang-format --dry-run --Werror` for C++. C++ runtime behavior and example-app test suites can only be validated by the user running `bun ios` / `bun android` — flag that rather than claiming it passes. +Use two dots for the commit list and three dots for the branch diff. Treat uncommitted and staged changes as part of the review and label findings that apply to them. -## Follow-up +### 2. Read every changed file -After presenting the review, present a **fix plan table** for the user to approve before making any changes: +Open every changed file with enough surrounding context to understand the behavior. Include TypeScript, C++, Nitro specifications/generated bindings, package metadata, podspec/Gradle/CMake, example-app tests, scripts, CI, documentation, and `.agents/` files when present. -| # | Severity | File:Line | Issue | Proposed Action | -| --- | -------- | ------------------ | ----------------- | ---------------- | -| 1 | Medium | path/to/file.ts:42 | Brief description | Fix / Skip / Ask | +Review for: -- **Fix**: Will apply the change -- **Skip**: Not worth changing (explain why) -- **Ask**: Ambiguous, needs user input on approach +- Correctness, edge cases, and error handling. +- Consistency with existing repository patterns. +- WebCrypto and Node.js compatibility. +- Nitro boundary and generated-code consistency. +- TypeScript strictness and public API shape. +- C++20 ownership, RAII, and memory safety. +- OpenSSL 3.6+ EVP/provider usage and checked return values. +- Cryptographic correctness, constant-time behavior, secret handling, nonce discipline, and authoritative vectors. +- Build, packaging, and platform-specific delivery impact. +- Test adequacy and whether evidence covers the current SHA. -**Wait for the user to approve the plan** (they may want to skip or modify items). They may reply with "approve" / "approve all" to accept everything, override individual rows ("skip #3", "fix #5 differently"), or ask clarifying questions. +### 3. Verify each changed toolchain -Once approved, apply only the approved fixes, then re-run the same toolchain checks to verify everything is clean. +Reuse evidence only when it names the commit SHA, exact tool or test, result, and platform, and no relevant later edit invalidated it. Request or run missing scoped checks. -Then commit the approved fixes (via `/commit`) — don't leave review changes sitting in the working tree. Commit only; pushing and opening PRs still need explicit permission. +- TypeScript: relevant `bun tsc`, lint, and formatting checks. +- C++: `clang-format --dry-run --Werror` over the changed native scope plus relevant compile or OpenSSL checks. +- ncrypto/OpenSSL: `scripts/check-ncrypto-openssl-deprecations.sh` when applicable. +- Node-side code: `cd packages/react-native-quick-crypto && bun run test`. Run this only for actual Node-side changes; never use bare `bun test` as a substitute. +- Native runtime: build, install, and exercise the affected example-app behavior on the relevant iOS or Android platform when feasible. Attach to an existing RNQC app and Metro first and use `/tmp/rnqc-metro.log`. +- Docs-only: validate links, paths, command names, and repository claims; do not rerun runtime suites. + +Do not repeat a broad suite merely because review started. A full foundational shared-crypto suite needs a stated cross-cutting reason or concrete unexplained failure, one owner, and a reusable result. + +### 4. Report findings + +Return: + +1. Summary of the branch. +2. Positives. +3. Severity-ranked findings with `file:line`, impact, evidence, and proposed action. +4. Verification coverage and explicit gaps. + +Then print the decision table before editing: + +| # | Severity | File:Line | Finding | Decision | Rationale | +|---|---|---|---|---|---| +| 1 | Medium | `path/file.ts:42` | Brief finding | Fix / Skip / Ask | Why | + +- **Fix:** A validated issue with a clear repository-consistent correction. +- **Skip:** Not valid, stale, already covered, or not worth changing; explain why. +- **Ask:** Two defensible choices lead to materially different behavior or blast radius and the repository cannot decide. + +Apply every clear Fix immediately after printing the table. Do not wait for approval when there are no Ask items. If Ask items exist, apply independent Fix items and run their checks before asking only the genuine choices. Never turn naming, factoring, or a discoverable convention into an Ask. + +When `/review` is called from `/implement`, `/implement` owns the follow-through and no additional approval round is added. + +After fixes, rerun only invalidated scoped checks and commit them through `/commit`. Never push unless the user invoked a workflow that authorizes it. diff --git a/.agents/rules/test-verification.md b/.agents/rules/test-verification.md index 380abdd9f..f53218e40 100644 --- a/.agents/rules/test-verification.md +++ b/.agents/rules/test-verification.md @@ -1,24 +1,41 @@ # Test Verification Rules -## Strict +## Evidence standard -Tests run only in the example React Native app. For runtime changes the assistant cannot fully validate, commit locally and wait for the user to run `bun ios` or `bun android` and exercise the relevant suite before pushing. +Select verification from the actual diff, changed behavior, and affected dependencies. Record reusable evidence with: -## Applies When +- Commit SHA. +- Exact command, tool, test, or driven flow. +- Result. +- Platform, simulator, or device when native behavior is involved. -- C++ changes need the example app. -- Behavior changes are covered by example-app tests. -- New example-app tests were added and not run. -- A previous pushed fix failed user validation. +Evidence remains current until a relevant edit or failure invalidates it. Reuse it across phases, review, commit, and PR preparation instead of repeating broad checks. -## Do Not Push Until +## Targeted checks -- User explicitly confirms tests pass, all green, ship it, or equivalent. -- If tests fail, add follow-up commits locally and keep waiting. -- Once confirmed, push all validated commits together. +- TypeScript changes: relevant `bun tsc`, lint, and formatting checks. +- C++ changes: formatting plus affected compile, OpenSSL, native build, and runtime checks. +- ncrypto/OpenSSL compatibility: `scripts/check-ncrypto-openssl-deprecations.sh` when in scope. +- Actual Node-side implementation or test changes: `cd packages/react-native-quick-crypto && bun run test`. Bare `bun test` is Bun's runner and does not execute the package's Jest script. +- Native behavior: build, install, and exercise the affected example-app path on iOS or Android. +- Pure documentation, plans, and `.agents/` configuration: validate links, file paths, commands, and repository claims; no runtime retest. -## Exceptions +Do not routinely run every test suite after each phase, commit, review, or documentation edit. A full foundational shared-crypto suite is appropriate only for a cross-cutting crypto/harness change or a concrete unexplained failure. State the reason before running it, assign one owner, and reuse the result while it remains current. -- Pure docs, plans, or `.agents/` config changes. -- User explicitly says to push/ship now. -- First PR push from an unpushed branch; still ask first if unverified runtime changes are included. +## Native app authority + +Agents may run native builds, simulators or devices, app tests, and driven verification. A genuinely current successful result qualifies without a separate user passphrase or approval round. + +Attach to an existing RNQC app and Metro first. Do not restart or kill another project's process and do not take over its port. If a native change requires rebuilding, use the example app's real scripts, such as `cd example && bun ios`, `bun android`, `bun run build:ios`, or `bun run build:android`, then run the relevant app flow. Full Maestro runners are `example/test/e2e/run-ios.sh` and `example/test/e2e/run-android.sh` when full-app coverage is justified. + +RNQC Metro client logs are tee'd to `/tmp/rnqc-metro.log`. Diagnose failures with: + +```bash +grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20 +``` + +## Delivery boundary + +Unverified runtime behavior blocks push or PR delivery when failure could require changing the diff. Missing credentials, unavailable hardware, or irreversible external actions qualify only when they affect that decision. + +The user may explicitly direct shipment despite a gap. In that case, disclose the exact unverified behavior, affected platform, and residual risk in the handoff and PR. Do not describe it as passing. diff --git a/AGENTS.md b/AGENTS.md index 7440bd8b1..bc7e72035 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,178 +1,111 @@ # React Native Quick Crypto - Agent Configuration -This project uses the **4-Layer Orchestra Architecture** for efficient multi-agent development. +This project uses agent workflows for repository work. `AGENTS.md` and `.agents/` are canonical; `CLAUDE.md` and `.claude` are symlink aliases for tools that expect Claude-style paths. -## Quick Reference +## Slash command dispatch -- **Simple tasks (1-2 files)**: Work directly, no orchestration needed -- **Complex tasks (3+ files)**: Use the orchestrator agent -- **Rules**: See `.agents/rules/*.md` for architectural constraints -- **Agents**: See `.agents/agents/*.md` for specialist definitions -- **Commands**: Load `.agents/commands/*.md` before handling command-style requests +When a user prompt begins with `/name`, read `.agents/commands/name.md` completely before planning or taking any task action, then follow it as the authoritative end-to-end workflow. The `.claude/commands/` path resolves to the same files through the `.claude` symlink. -## Command Instructions +If that exact command file is missing, search `.agents/commands/` for a documented alias and any known canonical source before acting. If none exists, flag the absence; do not silently invent a partial workflow from memory. -Agents must read the relevant command definition in `.agents/commands/` before executing any slash-command style request. At minimum, load all files in `.agents/commands/` early in the session so commands such as `/commit`, `/pr`, `/review`, and `/address-pr-feedback` follow the repo-specific workflow. +Load the repository rules relevant to the requested area. For command-style work, inventory `.agents/commands/` early so aliases and related workflows are not missed. -## Critical Principles +## Repository priorities -### 1. API Priority Order (NON-NEGOTIABLE) +### API priority order (non-negotiable) -When implementing features, favor in this order: +When implementing features, favor these sources in order: -1. **WebCrypto API** - Modern standard, best for `subtle.*` methods -2. **Node.js Implementation** - Use `$REPOS/node/deps/ncrypto` as reference -3. **ncrypto** - submodule code reference at `$REPOS/ncrypto` (do work w/ OpenSSL) +1. WebCrypto API for modern `subtle.*` methods. +2. Node.js `$REPOS/node/deps/ncrypto` for `crypto.*` compatibility and implementation patterns. +3. `$REPOS/ncrypto` as the standalone ncrypto and OpenSSL reference. -**Always check Node.js `deps/ncrypto` before implementing new features.** +Always inspect Node.js `deps/ncrypto` before implementing new crypto behavior, then adapt it to OpenSSL 3.6+ requirements. -### 2. Modern Stack Required +### Required stack -- **React Native** - Mobile framework -- **TypeScript** - Type system (strict mode, no `any`) -- **Nitro Modules** - Native bridging -- **C++20 or higher** - Modern C++ (smart pointers, RAII) -- **OpenSSL 3.6+** - Cryptographic library (EVP APIs only) -- **Bun 1.3+** - TypeScript package manager +- React Native. +- TypeScript in strict mode with no `any`. +- Nitro Modules for native bridging. +- C++20 or newer with smart pointers and RAII. +- OpenSSL 3.6+ EVP/provider APIs only. +- Bun 1.3+ for package management and scripts. -### 3. Code Philosophy +### Code philosophy -- Minimize code rather than add more -- Prefer iteration and modularization over duplication -- No comments unless code is sufficiently complex -- Code should be self-documenting +- Minimize code and avoid duplication. +- Prefer small, independently verifiable changes. +- Keep code self-documenting; comment only when the behavior is complex enough to require it. +- Preserve the existing crypto, Nitro, TypeScript, and C++ rules in `.agents/rules/`. -### 4. Never Commit to Main +### Security -- **ALWAYS** create a feature branch before the first commit -- Branch naming: `feat/<name>`, `fix/<name>`, `refactor/<name>` -- All changes go through PRs — never push directly to main -- If you find yourself on main, create a branch before committing +- Use constant-time comparisons such as `CRYPTO_memcmp()` for authentication material. +- Use `RAND_bytes()` and check its return value. +- Prefer authenticated encryption such as AES-GCM. +- Never expose key material in errors or logs. +- Validate against authoritative WebCrypto, Node.js, NIST, or RFC vectors as applicable. -### 5. Security is Critical +## Branch and delivery safety -- Constant-time comparisons for authentication tags -- Cryptographically secure randomness (RAND_bytes) -- AEAD modes preferred (AES-GCM) -- No key material in errors/logs -- Validate against test vectors (NIST, RFC, Node.js) +- Never commit on `main`; create a `feat/`, `fix/`, or `refactor/` branch first. +- Never use `--no-verify` for commits or pushes. +- Preserve unrelated working-tree changes and stage task files explicitly. +- All changes land through pull requests. +- `/implement` is explicitly authorized to push a qualified branch and create or update its PR. `/pr` is explicitly authorized to make the qualified push needed to create or update the PR. Standalone `/commit` never pushes implicitly. -## Rules Summary +## Plans -For full details, see `.agents/rules/*.md`: +New `/implement` work uses `plans/todo/<N>-<slug>.md` as the live tracker, including phases, decisions, assumptions, and verification evidence. Do not create a retroactive plan merely to make an already-running branch look as though it followed the workflow. -### architecture.md +Before opening a PR for completed planned work, move the one exact matching plan to `plans/done/` in the same branch and PR. Carry genuinely outstanding verification items with an owner. Never fuzzy-match plan names. Remove the ignored `.agents/progress/claude-progress.md` stub when its plan moves so later sessions do not inherit stale state. -- Project context and goals -- API priority order (WebCrypto → Node.js → ncrypto) -- Tech stack requirements -- Code philosophy -- Testing context (RN environment) -- Local codebase references +## Agent and model routing -### code-typescript.md +- Bounded implementation and routine verification: Sol at its default reasoning effort. +- General independent review and an implementation retry: Sol at high reasoning effort. +- Initial `/implement` recon, difficult design, and focused crypto correctness review: Astra. +- Explicit user model choices and live provider capabilities override these defaults. +- Documentation selects models for delegated work; it does not switch the active thread's model. +- Do not silently invoke separately billed tools. Use no more agents than the work requires, avoid duplicate research, and keep handoffs concise. +- Use early parallel work only for genuinely independent structural discovery. Implementation phases that share files or assumptions run sequentially with fresh context and bounded retries. -- No `any` or `unknown` casts -- Interfaces over types -- Named exports only (no default) -- No enums (use union types) -- Explicit return types -- Minimal, self-documenting code -- React best practices (minimal useEffect) +## Verification agreements -### code-cpp.md +- Select checks from the actual diff, changed behavior, and affected dependencies. Record reusable evidence with the commit SHA, exact tool or test, result, and platform. +- Reuse still-current evidence across phases, review, and PR preparation. Do not repeat a broad suite after every phase, review, documentation edit, or commit. +- A full foundational shared-crypto suite is justified only by a cross-cutting crypto/harness change or concrete unexplained failure. State the reason first, assign one owner, and reuse its result until relevant edits invalidate it. +- TypeScript changes use the relevant `bun tsc`, lint, and formatting scripts. +- Run the package Jest suite only for actual Node-side code changes: `cd packages/react-native-quick-crypto && bun run test`. Bare `bun test` invokes Bun's test runner and is not this package's Jest script. +- C++ changes use formatting plus the relevant native/compiler checks, including `scripts/check-ncrypto-openssl-deprecations.sh` when ncrypto/OpenSSL compatibility is in scope. +- Native runtime behavior is tested in the example React Native app. Agents may build, install, drive, and test the app; user confirmation is not inherently required when current successful evidence is available. +- Attach to the existing RNQC app and Metro process first. Do not restart another project's process or take over its port. Metro client logs belong at `/tmp/rnqc-metro.log`; inspect them with `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` when diagnosing failures. +- Pure documentation, plan, and `.agents/` changes do not require runtime retesting. +- Unverified runtime behavior that could change the diff blocks push/PR delivery unless the user explicitly directs shipment; disclose the unverified behavior and residual risk when they do. -- C++20 minimum with modern features -- Smart pointers for all ownership -- OpenSSL 3.6+ EVP APIs only (no deprecated) -- RAII for all resources -- Proper error handling (ERR_get_error) -- Memory safety (no leaks, no raw ownership) +## Real hooks and scripts -### crypto-security.md +The tracked pre-commit hook runs `bun lint-staged`, a C++ `clang-format --dry-run --Werror` scan, `bun tsc`, and `bun --filter="react-native-quick-crypto" prepare`. Allow at least 120 seconds for `git commit` and fix hook failures rather than bypassing them. -- Cryptographic correctness (match specs) -- No timing attacks (CRYPTO_memcmp) -- Secure RNG (RAND_bytes) -- Authenticated encryption (AEAD) -- Proper IV/nonce handling (never reuse) -- Minimum key sizes -- No key material in errors +Useful scripts and flows include: -### ci-caching.md +- Root checks: `bun tsc`, `bun lint`, `bun format`. +- Node-side Jest: `cd packages/react-native-quick-crypto && bun run test`. +- Example app: `cd example && bun ios` or `bun android`. +- Explicit native builds: `cd example && bun run build:ios` or `bun run build:android`. +- Full app E2E when justified: `example/test/e2e/run-ios.sh`, `example/test/e2e/run-android.sh`, or the CI Maestro flow in `example/test/e2e/test-suites-flow.yml`. -- iOS Pods/DerivedData cache consistency (exact-match Pods, no restore-keys) -- Cache key design (no version suffixes, use hashFiles) -- Android Maestro patterns (don't launch app before Maestro) -- Reference implementations (Nitro for iOS, Spicy for Android) +## Local references -## When to Use Orchestration +- `$REPOS/node`: Node.js crypto and ncrypto reference. +- `$REPOS/ncrypto`: standalone OpenSSL abstraction and Node-derived utilities. +- `$REPOS/nitro`: Nitro bridging examples and iOS CI caching patterns. +- `$REPOS/spicy`: shared agent-workflow and Android E2E patterns only; do not import Spicy services, Jazz assumptions, golf domain rules, or scripts into RNQC. -### Use Orchestrator For: +## Quality checklist -- ✅ Tasks touching 3+ files -- ✅ Cross-language changes (TypeScript + C++) -- ✅ New crypto features (API + implementation) -- ✅ Complex refactoring - -### Work Directly For: - -- ✅ Single file changes -- ✅ Simple bug fixes -- ✅ Type updates -- ✅ Documentation - -## Available Specialists - -- **orchestrator**: Decomposes complex tasks, coordinates specialists -- **typescript-specialist**: TypeScript API, types, Nitro bindings -- **cpp-specialist**: C++ implementation, OpenSSL integration -- **crypto-specialist**: Algorithm correctness, security review -- **testing-specialist**: Test strategy, test vectors, validation - -## Local Codebase References - -Use these instead of web searches: - -- **Node.js**: `$REPOS/node` - - - `deps/ncrypto` - Use as bible for crypto operations - - May need updating to OpenSSL 3.6+ patterns - -- **ncrypto**: `$REPOS/ncrypto` - - - separate crypto lib broken out from Node.js - - Patterns and tools to access OpenSSL - -- **Nitro**: `$REPOS/nitro` - - - iOS CI caching patterns (super-fast builds) - - Nitro Modules bridging examples - -- **Spicy**: `$REPOS/spicy` - - Android E2E patterns with Maestro - - Separate build/test workflow - -## Testing - -Tests run in the React Native example app environment, not standard Node.js test runners. - -Don't ask to run tests - they must be executed in the example React Native application. - -### Metro Logs - -Metro output is tee'd to `/tmp/rnqc-metro.log`. When debugging test failures, read this file to see console output including test pass/fail results. Use `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` to quickly find failures. - -## Quality Checks - -Before committing: - -- [ ] Type safety (no `any`, proper interfaces) -- [ ] Memory safety (smart pointers, RAII) -- [ ] Cryptographic correctness (test vectors) -- [ ] Security properties (constant-time, secure RNG) -- [ ] Code quality (minimal, modular, self-documenting) - ---- - -**For specialist details and orchestration patterns, see `.agents/agents/*.md` and `.agents/rules/*.md`** +- Type safety: no `any`; validate dynamic shapes. +- Memory safety: RAII, smart-pointer ownership, no leaks or invalid access. +- Cryptographic correctness: spec behavior, edge cases, and authoritative vectors. +- Security properties: constant-time comparisons, secure randomness, nonce discipline, and no secret leakage. +- Delivery evidence: checks match the actual diff and all claimed runtime behavior is verified or explicitly disclosed. From 980facec09f0aa24e9b47f055de9f5fc4310f4a8 Mon Sep 17 00:00:00 2001 From: Brad Anderson <brad@sankatygroup.com> Date: Mon, 26 Oct 2026 11:40:39 -0400 Subject: [PATCH 4/8] fix: restore ncrypto as a fork-backed submodule Keep the reviewed compatibility changes in boorad/ncrypto and pin its published revision. Initialize ncrypto in C++ CI and stop the iOS cache from overwriting checked-out dependency sources. --- .github/workflows/validate-cpp.yml | 6 + .gitmodules | 3 + packages/react-native-quick-crypto/.gitignore | 1 - .../react-native-quick-crypto/deps/ncrypto | 1 + .../deps/ncrypto/LICENSE | 21 - .../deps/ncrypto/README.md | 23 - .../deps/ncrypto/include/ncrypto.h | 1259 ------ .../deps/ncrypto/include/ncrypto/aead.h | 136 - .../deps/ncrypto/include/ncrypto/version.h | 14 - .../deps/ncrypto/src/aead.cpp | 249 -- .../deps/ncrypto/src/ncrypto.cpp | 3810 ----------------- 11 files changed, 10 insertions(+), 5513 deletions(-) create mode 160000 packages/react-native-quick-crypto/deps/ncrypto delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/LICENSE delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/README.md delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp delete mode 100644 packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp diff --git a/.github/workflows/validate-cpp.yml b/.github/workflows/validate-cpp.yml index 25a2f530b..0e92220f9 100644 --- a/.github/workflows/validate-cpp.yml +++ b/.github/workflows/validate-cpp.yml @@ -6,16 +6,20 @@ on: - main paths: - '.github/workflows/validate-cpp.yml' + - '.gitmodules' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto' - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' - 'scripts/check-ncrypto-openssl-deprecations.sh' pull_request: paths: - '.github/workflows/validate-cpp.yml' + - '.gitmodules' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto' - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' - 'scripts/check-ncrypto-openssl-deprecations.sh' @@ -38,6 +42,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + - name: Initialize ncrypto submodule + run: git submodule update --init --depth 1 packages/react-native-quick-crypto/deps/ncrypto - name: Set up native validation run: sudo apt-get install -y build-essential clang-format perl pkg-config - name: Build OpenSSL 3.6.2 diff --git a/.gitmodules b/.gitmodules index 24b8ba494..a2658a9e2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,9 @@ [submodule "packages/react-native-quick-crypto/deps/blake3"] path = packages/react-native-quick-crypto/deps/blake3 url = https://github.com/BLAKE3-team/BLAKE3.git +[submodule "packages/react-native-quick-crypto/deps/ncrypto"] + path = packages/react-native-quick-crypto/deps/ncrypto + url = https://github.com/boorad/ncrypto.git [submodule "packages/react-native-quick-crypto/deps/simdutf"] path = packages/react-native-quick-crypto/deps/simdutf url = https://github.com/simdutf/simdutf.git diff --git a/packages/react-native-quick-crypto/.gitignore b/packages/react-native-quick-crypto/.gitignore index 5c6d040d7..253e0720a 100644 --- a/packages/react-native-quick-crypto/.gitignore +++ b/packages/react-native-quick-crypto/.gitignore @@ -1,6 +1,5 @@ # will be copied from root README.md README.md -!deps/ncrypto/README.md ios/** diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto new file mode 160000 index 000000000..1d46de3e3 --- /dev/null +++ b/packages/react-native-quick-crypto/deps/ncrypto @@ -0,0 +1 @@ +Subproject commit 1d46de3e39c471dfa16c4e9db5b85a71c2e4c46d diff --git a/packages/react-native-quick-crypto/deps/ncrypto/LICENSE b/packages/react-native-quick-crypto/deps/ncrypto/LICENSE deleted file mode 100644 index 6da37b652..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 Node.js - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/react-native-quick-crypto/deps/ncrypto/README.md b/packages/react-native-quick-crypto/deps/ncrypto/README.md deleted file mode 100644 index f9db254f9..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# RNQC ncrypto snapshot - -This directory is a reduced, directly tracked snapshot of `ncrypto` for React Native Quick Crypto. It is not a standalone fork or independently published package. - -## Provenance - -- Upstream repository: `https://github.com/nodejs/ncrypto` -- Base revision: `027d1e44bbded3e40549d8edb0887cd783de8e5d` (`v1.1.4`) -- License: MIT; see `LICENSE` - -## Retained surface - -- `include/ncrypto.h` -- `include/ncrypto/aead.h` -- `include/ncrypto/version.h` -- `src/ncrypto.cpp` -- `src/aead.cpp` - -RNQC retains EVP key parsing and export, X.509 and SPKAC helpers, ciphers, digests, KDF support including Argon2, AEAD helpers, and the other utilities used by its native consumers. - -## Deliberate reductions - -Upstream build systems, tests, tools, ENGINE support, and unused legacy DH, DSA, EC, HMAC, RSA, SSL, and X.509 wrapper surfaces are omitted. Traditional PKCS#1 and SEC1 export uses OpenSSL 3 provider encoders rather than deprecated low-level key APIs. Keep additions limited to APIs required by RNQC and verify retained translation units against OpenSSL deprecation warnings before updating this snapshot. diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h deleted file mode 100644 index 22133c7e6..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto.h +++ /dev/null @@ -1,1259 +0,0 @@ -#pragma once - -#include <openssl/bio.h> -#include <openssl/bn.h> -#include <openssl/ec.h> -#include <openssl/err.h> -#include <openssl/evp.h> -#include <openssl/kdf.h> -#include <openssl/rsa.h> -#include <openssl/x509.h> - -#ifdef OPENSSL_IS_BORINGSSL -#include <openssl/aead.h> -#endif - -#include <cstddef> -#include <functional> -#include <list> -#include <memory> -#include <optional> -#include <string> -#include <string_view> - -#if NCRYPTO_DEVELOPMENT_CHECKS -#include <iostream> -#endif - -// The FIPS-related functions are only available -// when the OpenSSL itself was compiled with FIPS support. -#if defined(OPENSSL_FIPS) && OPENSSL_VERSION_MAJOR < 3 -#include <openssl/fips.h> -#endif // OPENSSL_FIPS - -// Define OPENSSL_WITH_PQC for post-quantum cryptography support -#if OPENSSL_VERSION_NUMBER >= 0x30500000L -#define OPENSSL_WITH_PQC 1 -#define EVP_PKEY_ML_KEM_512 NID_ML_KEM_512 -#define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768 -#define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024 -#endif - -#ifdef __GNUC__ -#define NCRYPTO_MUST_USE_RESULT __attribute__((warn_unused_result)) -#else -#define NCRYPTO_MUST_USE_RESULT -#endif - -#ifdef OPENSSL_IS_BORINGSSL -// Boringssl has opted to use size_t for some size related -// APIs while Openssl is still using ints -using OPENSSL_SIZE_T = size_t; -#else -using OPENSSL_SIZE_T = int; -#endif - -namespace ncrypto { - -// ============================================================================ -// Utility macros - -inline bool EqualNoCase(const std::string_view a, const std::string_view b) { - if (a.size() != b.size()) - return false; - return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); -} - -#if NCRYPTO_DEVELOPMENT_CHECKS -#define NCRYPTO_STR(x) #x -#define NCRYPTO_REQUIRE(EXPR) \ - { \ - if (!(EXPR)) { \ - abort(); \ - } \ - } - -#define NCRYPTO_FAIL(MESSAGE) \ - do { \ - std::cerr << "FAIL: " << (MESSAGE) << std::endl; \ - abort(); \ - } while (0); -#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) \ - do { \ - if (LHS != RHS) { \ - std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \ - NCRYPTO_FAIL(MESSAGE); \ - } \ - } while (0); -#define NCRYPTO_ASSERT_TRUE(COND) \ - do { \ - if (!(COND)) { \ - std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ << std::endl; \ - NCRYPTO_FAIL(NCRYPTO_STR(COND)); \ - } \ - } while (0); -#else -#define NCRYPTO_FAIL(MESSAGE) -#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) -#define NCRYPTO_ASSERT_TRUE(COND) -#endif - -#define NCRYPTO_DISALLOW_COPY(Name) \ - Name(const Name&) = delete; \ - Name& operator=(const Name&) = delete; -#define NCRYPTO_DISALLOW_MOVE(Name) \ - Name(Name&&) = delete; \ - Name& operator=(Name&&) = delete; -#define NCRYPTO_DISALLOW_COPY_AND_MOVE(Name) \ - NCRYPTO_DISALLOW_COPY(Name) \ - NCRYPTO_DISALLOW_MOVE(Name) -#define NCRYPTO_DISALLOW_NEW_DELETE() \ - void* operator new(size_t) = delete; \ - void operator delete(void*) = delete; - -[[noreturn]] inline void unreachable() { -#ifdef __GNUC__ - __builtin_unreachable(); -#elif defined(_MSC_VER) - __assume(false); -#else -#endif -} - -static constexpr int kX509NameFlagsMultiline = - ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_MULTILINE | XN_FLAG_FN_SN; - -// ============================================================================ -// Error handling utilities - -// Capture the current OpenSSL Error Stack. The stack will be ordered such -// that the error currently at the top of the stack is at the end of the -// list and the error at the bottom of the stack is at the beginning. -class CryptoErrorList final { - public: - enum class Option { NONE, CAPTURE_ON_CONSTRUCT }; - CryptoErrorList(Option option = Option::CAPTURE_ON_CONSTRUCT); - - void capture(); - - // Add an error message to the end of the stack. - void add(std::string message); - - inline const std::string& peek_back() const { - return errors_.back(); - } - inline size_t size() const { - return errors_.size(); - } - inline bool empty() const { - return errors_.empty(); - } - - inline auto begin() const noexcept { - return errors_.begin(); - } - inline auto end() const noexcept { - return errors_.end(); - } - inline auto rbegin() const noexcept { - return errors_.rbegin(); - } - inline auto rend() const noexcept { - return errors_.rend(); - } - - std::optional<std::string> pop_back(); - std::optional<std::string> pop_front(); - - private: - std::list<std::string> errors_; -}; - -// Forcibly clears the error stack on destruction. This stops stale errors -// from popping up later in the lifecycle of crypto operations where they -// would cause spurious failures. It is a rather blunt method, though, and -// ERR_clear_error() isn't necessarily cheap. -// -// If created with a pointer to a CryptoErrorList, the current OpenSSL error -// stack will be captured before clearing the error. -class ClearErrorOnReturn final { - public: - ClearErrorOnReturn(CryptoErrorList* errors = nullptr); - ~ClearErrorOnReturn(); - NCRYPTO_DISALLOW_COPY_AND_MOVE(ClearErrorOnReturn) - NCRYPTO_DISALLOW_NEW_DELETE() - - int peekError(); - - private: - CryptoErrorList* errors_; -}; - -// Pop errors from OpenSSL's error stack that were added between when this -// was constructed and destructed. -// -// If created with a pointer to a CryptoErrorList, the current OpenSSL error -// stack will be captured before resetting the error to the mark. -class MarkPopErrorOnReturn final { - public: - MarkPopErrorOnReturn(CryptoErrorList* errors = nullptr); - ~MarkPopErrorOnReturn(); - NCRYPTO_DISALLOW_COPY_AND_MOVE(MarkPopErrorOnReturn) - NCRYPTO_DISALLOW_NEW_DELETE() - - int peekError(); - - private: - CryptoErrorList* errors_; -}; - -// TODO(@jasnell): Eventually replace with std::expected when we are able to -// bump up to c++23. -template <typename T, typename E> -struct Result final { - const bool has_value; - T value; - std::optional<E> error = std::nullopt; - std::optional<int> openssl_error = std::nullopt; - Result(T&& value) : has_value(true), value(std::move(value)) {} - Result(E&& error, std::optional<int> openssl_error = std::nullopt) - : has_value(false), error(std::move(error)), openssl_error(std::move(openssl_error)) {} - inline operator bool() const { - return has_value; - } -}; - -// ============================================================================ -// Various smart pointer aliases for OpenSSL types. - -template <typename T, void (*function)(T*)> -struct FunctionDeleter { - void operator()(T* pointer) const { - function(pointer); - } - typedef std::unique_ptr<T, FunctionDeleter> Pointer; -}; - -template <typename T, void (*function)(T*)> -using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer; - -using PKCS8Pointer = DeleteFnPtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_free>; - -class BIOPointer; -class BignumPointer; -class CipherCtxPointer; -class DataPointer; -class EVPKeyPointer; -class EVPMacCtxPointer; -class EVPMacPointer; -class EVPMDCtxPointer; -class X509View; -class X509Pointer; -class ECDSASigPointer; - -struct StackOfXASN1Deleter { - void operator()(STACK_OF(ASN1_OBJECT) * p) const { - sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free); - } -}; -using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>; - -// An unowned, unmanaged pointer to a buffer of data. -template <typename T> -struct Buffer { - T* data = nullptr; - size_t len = 0; -}; - -class Digest final { - public: - static constexpr size_t MAX_SIZE = EVP_MAX_MD_SIZE; - Digest() = default; - Digest(const EVP_MD* md) : md_(md) {} - Digest(const Digest&) = default; - Digest& operator=(const Digest&) = default; - inline Digest& operator=(const EVP_MD* md) { - md_ = md; - return *this; - } - NCRYPTO_DISALLOW_MOVE(Digest) - - size_t size() const; - - inline const EVP_MD* get() const { - return md_; - } - inline operator const EVP_MD*() const { - return md_; - } - inline operator bool() const { - return md_ != nullptr; - } - - static const Digest MD5; - static const Digest SHA1; - static const Digest SHA256; - static const Digest SHA384; - static const Digest SHA512; - - static const Digest FromName(const char* name); - - private: - const EVP_MD* md_ = nullptr; -}; - -// Computes a fixed-length digest. -DataPointer hashDigest(const Buffer<const unsigned char>& data, const EVP_MD* md); -// Computes a variable-length digest for XOF algorithms (e.g. SHAKE128). -DataPointer xofHashDigest(const Buffer<const unsigned char>& data, const EVP_MD* md, size_t length); - -class Cipher final { - public: - static constexpr size_t MAX_KEY_LENGTH = EVP_MAX_KEY_LENGTH; - static constexpr size_t MAX_IV_LENGTH = EVP_MAX_IV_LENGTH; -#ifdef EVP_MAX_AEAD_TAG_LENGTH - static constexpr size_t MAX_AUTH_TAG_LENGTH = EVP_MAX_AEAD_TAG_LENGTH; -#else - static constexpr size_t MAX_AUTH_TAG_LENGTH = 16; -#endif - static_assert(EVP_GCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH -#ifndef OPENSSL_IS_BORINGSSL - && EVP_CCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH && EVP_CHACHAPOLY_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH -#endif - ); - - Cipher() = default; - Cipher(const EVP_CIPHER* cipher) : cipher_(cipher) {} - Cipher(const Cipher&) = default; - Cipher& operator=(const Cipher&) = default; - inline Cipher& operator=(const EVP_CIPHER* cipher) { - cipher_ = cipher; - return *this; - } - NCRYPTO_DISALLOW_MOVE(Cipher) - - inline const EVP_CIPHER* get() const { - return cipher_; - } - inline operator const EVP_CIPHER*() const { - return cipher_; - } - inline operator bool() const { - return cipher_ != nullptr; - } - - int getNid() const; - int getMode() const; - int getIvLength() const; - int getKeyLength() const; - int getBlockSize() const; - std::string_view getModeLabel() const; - const char* getName() const; - - bool isGcmMode() const; - bool isWrapMode() const; - bool isCtrMode() const; - bool isCcmMode() const; - bool isOcbMode() const; - bool isStreamMode() const; - bool isChaCha20Poly1305() const; - - bool isSupportedAuthenticatedMode() const; - - int bytesToKey(const Digest& digest, const Buffer<const unsigned char>& input, unsigned char* key, unsigned char* iv) const; - - static const Cipher FromName(const char* name); - static const Cipher FromNid(int nid); - static const Cipher FromCtx(const CipherCtxPointer& ctx); - - using CipherNameCallback = std::function<void(const char* name)>; - - // Iterates the known ciphers if the underlying implementation - // is able to do so. - static void ForEach(CipherNameCallback callback); - - // Utilities to get various ciphers by type. If the underlying - // implementation does not support the requested cipher, then - // the result will be an empty Cipher object whose bool operator - // will return false. - - static const Cipher EMPTY; - static const Cipher AES_128_CBC; - static const Cipher AES_192_CBC; - static const Cipher AES_256_CBC; - static const Cipher AES_128_CTR; - static const Cipher AES_192_CTR; - static const Cipher AES_256_CTR; - static const Cipher AES_128_GCM; - static const Cipher AES_192_GCM; - static const Cipher AES_256_GCM; - static const Cipher AES_128_KW; - static const Cipher AES_192_KW; - static const Cipher AES_256_KW; - static const Cipher AES_128_OCB; - static const Cipher AES_192_OCB; - static const Cipher AES_256_OCB; - static const Cipher CHACHA20_POLY1305; - - struct CipherParams { - int padding; - Digest digest; - const Buffer<const void> label; - }; - - static DataPointer encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); - static DataPointer decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); - - static DataPointer sign(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); - - static DataPointer recover(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); - - static constexpr bool IsValidGCMTagLength(unsigned int tag_len) { - return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16); - } - - private: - const EVP_CIPHER* cipher_ = nullptr; -}; - -class BignumPointer final { - public: - BignumPointer() = default; - explicit BignumPointer(BIGNUM* bignum); - explicit BignumPointer(const unsigned char* data, size_t len); - BignumPointer(BignumPointer&& other) noexcept; - BignumPointer& operator=(BignumPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(BignumPointer) - ~BignumPointer(); - - int operator<=>(const BignumPointer& other) const noexcept; - int operator<=>(const BIGNUM* other) const noexcept; - inline operator bool() const { - return bn_ != nullptr; - } - inline BIGNUM* get() const noexcept { - return bn_.get(); - } - void reset(BIGNUM* bn = nullptr); - void reset(const unsigned char* data, size_t len); - BIGNUM* release(); - - bool isZero() const; - bool isOne() const; - - bool setWord(unsigned long w); // NOLINT(runtime/int) - unsigned long getWord() const; // NOLINT(runtime/int) - - size_t byteLength() const; - size_t bitLength() const; - - DataPointer toHex() const; - DataPointer encode() const; - DataPointer encodePadded(size_t size) const; - size_t encodeInto(unsigned char* out) const; - size_t encodePaddedInto(unsigned char* out, size_t size) const; - - using PrimeCheckCallback = std::function<bool(int, int)>; - int isPrime(int checks, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; - struct PrimeConfig { - int bits; - bool safe = false; - const BignumPointer& add; - const BignumPointer& rem; - }; - - static BignumPointer NewPrime(const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback); - - bool generate(const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; - - static BignumPointer New(); - static BignumPointer NewSecure(); - static BignumPointer NewSub(const BignumPointer& a, const BignumPointer& b); - static BignumPointer NewLShift(size_t length); - - static DataPointer Encode(const BIGNUM* bn); - static DataPointer EncodePadded(const BIGNUM* bn, size_t size); - static size_t EncodePaddedInto(const BIGNUM* bn, unsigned char* out, size_t size); - static int GetBitCount(const BIGNUM* bn); - static int GetByteCount(const BIGNUM* bn); - static unsigned long GetWord(const BIGNUM* bn); // NOLINT(runtime/int) - static const BIGNUM* One(); - - BignumPointer clone(); - - private: - DeleteFnPtr<BIGNUM, BN_clear_free> bn_; - - static bool defaultPrimeCheckCallback(int, int) { - return 1; - } -}; - -// A managed pointer to a buffer of data. When destroyed the underlying -// buffer will be freed. -class DataPointer final { - public: - static DataPointer Alloc(size_t len); - static DataPointer Copy(const Buffer<const void>& buffer); - - // Attempts to allocate the buffer space using the secure heap, if - // supported/enabled. If the secure heap is disabled, then this - // ends up being equivalent to Alloc(len). Note that allocation - // will fail if there is not enough free space remaining in the - // secure heap space. - static DataPointer SecureAlloc(size_t len); - - // If the secure heap is enabled, returns the amount of data that - // has been allocated from the heap. - static size_t GetSecureHeapUsed(); - - enum class InitSecureHeapResult { - FAILED, - UNABLE_TO_MEMORY_MAP, - OK, - }; - - // Attempt to initialize the secure heap. The secure heap is not - // supported on all operating systems and whenever boringssl is - // used. - static InitSecureHeapResult TryInitSecureHeap(size_t amount, size_t min); - - DataPointer() = default; - explicit DataPointer(void* data, size_t len, bool secure = false); - explicit DataPointer(const Buffer<void>& buffer, bool secure = false); - DataPointer(DataPointer&& other) noexcept; - DataPointer& operator=(DataPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(DataPointer) - ~DataPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return data_ == nullptr; - } - inline operator bool() const { - return data_ != nullptr; - } - - template <typename T = void> - inline T* get() const noexcept { - return static_cast<T*>(data_); - } - - inline size_t size() const noexcept { - return len_; - } - void reset(void* data = nullptr, size_t len = 0); - void reset(const Buffer<void>& buffer); - - // Sets the underlying data buffer to all zeros. - void zero(); - - DataPointer resize(size_t len); - - // Releases ownership of the underlying data buffer. It is the caller's - // responsibility to ensure the buffer is appropriately freed. - Buffer<void> release(); - - // Returns a Buffer struct that is a view of the underlying data. - template <typename T = void> - inline operator const Buffer<T>() const { - return { - .data = static_cast<T*>(data_), - .len = len_, - }; - } - - bool isSecure() const { - return secure_; - } - - private: - void free(); - - void* data_ = nullptr; - size_t len_ = 0; - bool secure_ = false; -}; - -class BIOPointer final { - public: - static BIOPointer NewMem(); - static BIOPointer NewSecMem(); - static BIOPointer New(const BIO_METHOD* method); - static BIOPointer New(const void* data, size_t len); - static BIOPointer New(const BIGNUM* bn); - static BIOPointer NewFile(const char* filename, const char* mode); - static BIOPointer NewFp(FILE* fd, int flags); - - template <typename T> - static BIOPointer New(const Buffer<T>& buf) { - return New(buf.data, buf.len); - } - - BIOPointer() = default; - BIOPointer(std::nullptr_t) : bio_(nullptr) {} - explicit BIOPointer(BIO* bio); - BIOPointer(BIOPointer&& other) noexcept; - BIOPointer& operator=(BIOPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(BIOPointer) - ~BIOPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return bio_ == nullptr; - } - inline operator bool() const { - return bio_ != nullptr; - } - inline BIO* get() const noexcept { - return bio_.get(); - } - - inline operator BUF_MEM*() const { - BUF_MEM* mem = nullptr; - if (!bio_) - return mem; - BIO_get_mem_ptr(bio_.get(), &mem); - return mem; - } - - inline operator BIO*() const { - return bio_.get(); - } - - void reset(BIO* bio = nullptr); - BIO* release(); - - bool resetBio() const; - - static int Write(BIOPointer* bio, std::string_view message); - - template <typename... Args> - static void Printf(BIOPointer* bio, const char* format, Args... args) { - if (bio == nullptr || !*bio) - return; - BIO_printf(bio->get(), format, std::forward<Args...>(args...)); - } - - private: - mutable DeleteFnPtr<BIO, BIO_free_all> bio_; -}; - -class CipherCtxPointer final { - public: - static CipherCtxPointer New(); - - CipherCtxPointer() = default; - explicit CipherCtxPointer(EVP_CIPHER_CTX* ctx); - CipherCtxPointer(CipherCtxPointer&& other) noexcept; - CipherCtxPointer& operator=(CipherCtxPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(CipherCtxPointer) - ~CipherCtxPointer(); - - inline bool operator==(std::nullptr_t) const noexcept { - return ctx_ == nullptr; - } - inline operator bool() const { - return ctx_ != nullptr; - } - inline EVP_CIPHER_CTX* get() const { - return ctx_.get(); - } - inline operator EVP_CIPHER_CTX*() const { - return ctx_.get(); - } - void reset(EVP_CIPHER_CTX* ctx = nullptr); - EVP_CIPHER_CTX* release(); - - void setAllowWrap(); - - bool setKeyLength(size_t length); - bool setIvLength(size_t length); - bool setAeadTag(const Buffer<const char>& tag); - bool setAeadTagLength(size_t length); - bool setPadding(bool padding); - bool init(const Cipher& cipher, bool encrypt, const unsigned char* key = nullptr, const unsigned char* iv = nullptr); - - int getBlockSize() const; - int getMode() const; - int getNid() const; - - bool isGcmMode() const; - bool isOcbMode() const; - bool isCcmMode() const; - bool isWrapMode() const; - bool isChaCha20Poly1305() const; - - bool update(const Buffer<const unsigned char>& in, unsigned char* out, int* out_len, bool finalize = false); - bool getAeadTag(size_t len, unsigned char* out); - - private: - DeleteFnPtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> ctx_; -}; - -class EVPKeyCtxPointer final { - public: - EVPKeyCtxPointer(); - explicit EVPKeyCtxPointer(EVP_PKEY_CTX* ctx); - EVPKeyCtxPointer(EVPKeyCtxPointer&& other) noexcept; - EVPKeyCtxPointer& operator=(EVPKeyCtxPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(EVPKeyCtxPointer) - ~EVPKeyCtxPointer(); - - inline bool operator==(std::nullptr_t) const noexcept { - return ctx_ == nullptr; - } - inline operator bool() const { - return ctx_ != nullptr; - } - inline EVP_PKEY_CTX* get() const { - return ctx_.get(); - } - void reset(EVP_PKEY_CTX* ctx = nullptr); - EVP_PKEY_CTX* release(); - - bool initForDerive(const EVPKeyPointer& peer); - DataPointer derive() const; - - bool initForParamgen(); - bool setDhParameters(int prime_size, uint32_t generator); - bool setDsaParameters(uint32_t bits, std::optional<int> q_bits); - bool setEcParameters(int curve, int encoding); - - bool setRsaOaepMd(const Digest& md); - bool setRsaMgf1Md(const Digest& md); - bool setRsaPadding(int padding); - bool setRsaKeygenPubExp(BignumPointer&& e); - bool setRsaKeygenBits(int bits); - bool setRsaPssKeygenMd(const Digest& md); - bool setRsaPssKeygenMgf1Md(const Digest& md); - bool setRsaPssSaltlen(int salt_len); - bool setRsaImplicitRejection(); - bool setRsaOaepLabel(DataPointer&& data); - - bool setSignatureMd(const EVPMDCtxPointer& md); - - bool publicCheck() const; - bool privateCheck() const; - - bool verify(const Buffer<const unsigned char>& sig, const Buffer<const unsigned char>& data); - DataPointer sign(const Buffer<const unsigned char>& data); - bool signInto(const Buffer<const unsigned char>& data, Buffer<unsigned char>* sig); - - static constexpr int kDefaultRsaExponent = 0x10001; - - static bool setRsaPadding(EVP_PKEY_CTX* ctx, int padding, std::optional<int> salt_len = std::nullopt); - - EVPKeyPointer paramgen() const; - - bool initForEncrypt(); - bool initForDecrypt(); - bool initForKeygen(); - int initForVerify(); - int initForSign(); - - static EVPKeyCtxPointer New(const EVPKeyPointer& key); - static EVPKeyCtxPointer NewFromID(int id); - - private: - DeleteFnPtr<EVP_PKEY_CTX, EVP_PKEY_CTX_free> ctx_; -}; - -class EVPKeyPointer final { - public: - static EVPKeyPointer New(); - static EVPKeyPointer NewRawPublic(int id, const Buffer<const unsigned char>& data); - static EVPKeyPointer NewRawPrivate(int id, const Buffer<const unsigned char>& data); -#if OPENSSL_WITH_PQC - static EVPKeyPointer NewRawSeed(int id, const Buffer<const unsigned char>& data); -#endif - enum class PKEncodingType { - // RSAPublicKey / RSAPrivateKey according to PKCS#1. - PKCS1, - // PrivateKeyInfo or EncryptedPrivateKeyInfo according to PKCS#8. - PKCS8, - // SubjectPublicKeyInfo according to X.509. - SPKI, - // ECPrivateKey according to SEC1. - SEC1, - }; - - enum class PKFormatType { - DER, - PEM, - JWK, - RAW_PUBLIC, - RAW_PRIVATE, - RAW_SEED, - }; - - enum class PKParseError { NOT_RECOGNIZED, NEED_PASSPHRASE, FAILED }; - using ParseKeyResult = Result<EVPKeyPointer, PKParseError>; - - struct AsymmetricKeyEncodingConfig { - bool output_key_object = false; - PKFormatType format = PKFormatType::DER; - PKEncodingType type = PKEncodingType::PKCS8; - int ec_point_form = POINT_CONVERSION_UNCOMPRESSED; - AsymmetricKeyEncodingConfig() = default; - AsymmetricKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type); - AsymmetricKeyEncodingConfig(const AsymmetricKeyEncodingConfig&) = default; - AsymmetricKeyEncodingConfig& operator=(const AsymmetricKeyEncodingConfig&) = default; - }; - using PublicKeyEncodingConfig = AsymmetricKeyEncodingConfig; - - struct PrivateKeyEncodingConfig : public AsymmetricKeyEncodingConfig { - const EVP_CIPHER* cipher = nullptr; - std::optional<DataPointer> passphrase = std::nullopt; - PrivateKeyEncodingConfig() = default; - PrivateKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type) - : AsymmetricKeyEncodingConfig(output_key_object, format, type) {} - PrivateKeyEncodingConfig(const PrivateKeyEncodingConfig&); - PrivateKeyEncodingConfig& operator=(const PrivateKeyEncodingConfig&); - }; - - static ParseKeyResult TryParsePublicKey(const PublicKeyEncodingConfig& config, const Buffer<const unsigned char>& buffer); - - static ParseKeyResult TryParsePublicKeyPEM(const Buffer<const unsigned char>& buffer); - - static ParseKeyResult TryParsePrivateKey(const PrivateKeyEncodingConfig& config, const Buffer<const unsigned char>& buffer); - - EVPKeyPointer() = default; - explicit EVPKeyPointer(EVP_PKEY* pkey); - EVPKeyPointer(EVPKeyPointer&& other) noexcept; - EVPKeyPointer& operator=(EVPKeyPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(EVPKeyPointer) - ~EVPKeyPointer(); - - inline bool operator==(std::nullptr_t) const noexcept { - return pkey_ == nullptr; - } - inline operator bool() const { - return pkey_ != nullptr; - } - inline EVP_PKEY* get() const { - return pkey_.get(); - } - void reset(EVP_PKEY* pkey = nullptr); - EVP_PKEY* release(); - - static int id(const EVP_PKEY* key); - static int base_id(const EVP_PKEY* key); - - int id() const; - int base_id() const; - int bits() const; - size_t size() const; - - size_t rawPublicKeySize() const; - size_t rawPrivateKeySize() const; - DataPointer rawPublicKey() const; - DataPointer rawPrivateKey() const; - BIOPointer derPublicKey() const; - -#if OPENSSL_WITH_PQC - DataPointer rawSeed() const; -#endif - - Result<BIOPointer, bool> writePrivateKey(const PrivateKeyEncodingConfig& config) const; - Result<BIOPointer, bool> writePublicKey(const PublicKeyEncodingConfig& config) const; - - EVPKeyCtxPointer newCtx() const; - - static bool IsRSAPrivateKey(const Buffer<const unsigned char>& buffer); - - std::optional<uint32_t> getBytesOfRS() const; - int getDefaultSignPadding() const; - bool isRsaVariant() const; - bool isOneShotVariant() const; - bool isSigVariant() const; - bool validateDsaParameters() const; - - EVPKeyPointer clone() const; - - private: - DeleteFnPtr<EVP_PKEY, EVP_PKEY_free> pkey_; -}; - -class X509View final { - public: - X509View() = default; - inline explicit X509View(const X509* cert) : cert_(cert) {} - X509View(const X509View& other) = default; - X509View& operator=(const X509View& other) = default; - NCRYPTO_DISALLOW_MOVE(X509View) - - inline X509* get() const { - return const_cast<X509*>(cert_); - } - inline operator X509*() const { - return const_cast<X509*>(cert_); - } - inline operator const X509*() const { - return cert_; - } - - inline bool operator==(std::nullptr_t) noexcept { - return cert_ == nullptr; - } - inline operator bool() const { - return cert_ != nullptr; - } - - BIOPointer toPEM() const; - BIOPointer toDER() const; - - BIOPointer getSubject() const; - BIOPointer getSubjectAltName() const; - BIOPointer getIssuer() const; - BIOPointer getInfoAccess() const; - BIOPointer getValidFrom() const; - BIOPointer getValidTo() const; - std::optional<std::string_view> getSignatureAlgorithm() const; - std::optional<std::string> getSignatureAlgorithmOID() const; - int64_t getValidFromTime() const; - int64_t getValidToTime() const; - DataPointer getSerialNumber() const; - Result<EVPKeyPointer, int> getPublicKey() const; - StackOfASN1 getKeyUsage() const; - - bool isCA() const; - bool isIssuedBy(const X509View& other) const; - bool checkPrivateKey(const EVPKeyPointer& pkey) const; - bool checkPublicKey(const EVPKeyPointer& pkey) const; - - std::optional<std::string> getFingerprint(const Digest& method) const; - - enum class CheckMatch { - NO_MATCH, - MATCH, - INVALID_NAME, - OPERATION_FAILED, - }; - CheckMatch checkHost(std::string_view host, int flags, DataPointer* peerName = nullptr) const; - CheckMatch checkEmail(std::string_view email, int flags) const; - CheckMatch checkIp(std::string_view ip, int flags) const; - - using UsageCallback = std::function<void(const char*)>; - bool enumUsages(UsageCallback callback) const; - - private: - const X509* cert_ = nullptr; -}; - -class X509Pointer final { - public: - static Result<X509Pointer, int> Parse(Buffer<const unsigned char> buffer); - X509Pointer() = default; - explicit X509Pointer(X509* cert); - X509Pointer(X509Pointer&& other) noexcept; - X509Pointer& operator=(X509Pointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(X509Pointer) - ~X509Pointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return cert_ == nullptr; - } - inline operator bool() const { - return cert_ != nullptr; - } - inline X509* get() const { - return cert_.get(); - } - inline operator X509*() const { - return cert_.get(); - } - inline operator const X509*() const { - return cert_.get(); - } - void reset(X509* cert = nullptr); - X509* release(); - - X509View view() const; - operator X509View() const { - return view(); - } - - static const char* ErrorCode(int32_t err); - static std::optional<const char*> ErrorReason(int32_t err); - - private: - DeleteFnPtr<X509, X509_free> cert_; -}; - -class ECDSASigPointer final { - public: - explicit ECDSASigPointer(); - explicit ECDSASigPointer(ECDSA_SIG* sig); - ECDSASigPointer(ECDSASigPointer&& other) noexcept; - ECDSASigPointer& operator=(ECDSASigPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(ECDSASigPointer) - ~ECDSASigPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return sig_ == nullptr; - } - inline operator bool() const { - return sig_ != nullptr; - } - inline ECDSA_SIG* get() const { - return sig_.get(); - } - inline operator ECDSA_SIG*() const { - return sig_.get(); - } - void reset(ECDSA_SIG* sig = nullptr); - ECDSA_SIG* release(); - - static ECDSASigPointer New(); - static ECDSASigPointer Parse(const Buffer<const unsigned char>& buffer); - - inline const BIGNUM* r() const { - return pr_; - } - inline const BIGNUM* s() const { - return ps_; - } - - bool setParams(BignumPointer&& r, BignumPointer&& s); - - Buffer<unsigned char> encode() const; - - private: - DeleteFnPtr<ECDSA_SIG, ECDSA_SIG_free> sig_; - const BIGNUM* pr_ = nullptr; - const BIGNUM* ps_ = nullptr; -}; - -class EVPMDCtxPointer final { - public: - EVPMDCtxPointer(); - explicit EVPMDCtxPointer(EVP_MD_CTX* ctx); - EVPMDCtxPointer(EVPMDCtxPointer&& other) noexcept; - EVPMDCtxPointer& operator=(EVPMDCtxPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(EVPMDCtxPointer) - ~EVPMDCtxPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return ctx_ == nullptr; - } - inline operator bool() const { - return ctx_ != nullptr; - } - inline EVP_MD_CTX* get() const { - return ctx_.get(); - } - inline operator EVP_MD_CTX*() const { - return ctx_.get(); - } - void reset(EVP_MD_CTX* ctx = nullptr); - EVP_MD_CTX* release(); - - bool digestInit(const Digest& digest); - bool digestUpdate(const Buffer<const void>& in); - DataPointer digestFinal(size_t length); - bool digestFinalInto(Buffer<void>* buf); - size_t getExpectedSize(); - - std::optional<EVP_PKEY_CTX*> signInit(const EVPKeyPointer& key, const Digest& digest); - std::optional<EVP_PKEY_CTX*> verifyInit(const EVPKeyPointer& key, const Digest& digest); - - std::optional<EVP_PKEY_CTX*> signInitWithContext(const EVPKeyPointer& key, const Digest& digest, - const Buffer<const unsigned char>& context_string); - std::optional<EVP_PKEY_CTX*> verifyInitWithContext(const EVPKeyPointer& key, const Digest& digest, - const Buffer<const unsigned char>& context_string); - - DataPointer signOneShot(const Buffer<const unsigned char>& buf) const; - DataPointer sign(const Buffer<const unsigned char>& buf) const; - bool verify(const Buffer<const unsigned char>& buf, const Buffer<const unsigned char>& sig) const; - - const EVP_MD* getDigest() const; - size_t getDigestSize() const; - bool hasXofFlag() const; - - bool copyTo(const EVPMDCtxPointer& other) const; - - static EVPMDCtxPointer New(); - - private: - DeleteFnPtr<EVP_MD_CTX, EVP_MD_CTX_free> ctx_; -}; - -#if OPENSSL_VERSION_MAJOR >= 3 -class EVPMacPointer final { - public: - EVPMacPointer() = default; - explicit EVPMacPointer(EVP_MAC* mac); - EVPMacPointer(EVPMacPointer&& other) noexcept; - EVPMacPointer& operator=(EVPMacPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(EVPMacPointer) - ~EVPMacPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return mac_ == nullptr; - } - inline operator bool() const { - return mac_ != nullptr; - } - inline EVP_MAC* get() const { - return mac_.get(); - } - inline operator EVP_MAC*() const { - return mac_.get(); - } - void reset(EVP_MAC* mac = nullptr); - EVP_MAC* release(); - - static EVPMacPointer Fetch(const char* algorithm); - - private: - DeleteFnPtr<EVP_MAC, EVP_MAC_free> mac_; -}; - -class EVPMacCtxPointer final { - public: - EVPMacCtxPointer() = default; - explicit EVPMacCtxPointer(EVP_MAC_CTX* ctx); - EVPMacCtxPointer(EVPMacCtxPointer&& other) noexcept; - EVPMacCtxPointer& operator=(EVPMacCtxPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(EVPMacCtxPointer) - ~EVPMacCtxPointer(); - - inline bool operator==(std::nullptr_t) noexcept { - return ctx_ == nullptr; - } - inline operator bool() const { - return ctx_ != nullptr; - } - inline EVP_MAC_CTX* get() const { - return ctx_.get(); - } - inline operator EVP_MAC_CTX*() const { - return ctx_.get(); - } - void reset(EVP_MAC_CTX* ctx = nullptr); - EVP_MAC_CTX* release(); - - bool init(const Buffer<const void>& key, const OSSL_PARAM* params = nullptr); - bool update(const Buffer<const void>& data); - DataPointer final(size_t length); - - static EVPMacCtxPointer New(EVP_MAC* mac); - - private: - DeleteFnPtr<EVP_MAC_CTX, EVP_MAC_CTX_free> ctx_; -}; -#endif // OPENSSL_VERSION_MAJOR >= 3 - -// ============================================================================ -// FIPS -bool isFipsEnabled(); - -bool setFipsEnabled(bool enabled, CryptoErrorList* errors); - -bool testFipsEnabled(); - -// ============================================================================ -// Various utilities - -bool CSPRNG(void* buffer, size_t length) NCRYPTO_MUST_USE_RESULT; - -// This callback is used to avoid the default passphrase callback in OpenSSL -// which will typically prompt for the passphrase. The prompting is designed -// for the OpenSSL CLI, but works poorly for some environments like Node.js -// because it involves synchronous interaction with the controlling terminal, -// something we never want, and use this function to avoid it. -int NoPasswordCallback(char* buf, int size, int rwflag, void* u); - -int PasswordCallback(char* buf, int size, int rwflag, void* u); - -bool SafeX509SubjectAltNamePrint(const BIOPointer& out, const X509_EXTENSION* ext); -bool SafeX509InfoAccessPrint(const BIOPointer& out, const X509_EXTENSION* ext); - -// ============================================================================ -// SPKAC - -bool VerifySpkac(const char* input, size_t length); -BIOPointer ExportPublicKey(const char* input, size_t length); - -// The caller takes ownership of the returned Buffer<char> -Buffer<char> ExportChallenge(const char* input, size_t length); - -bool VerifySpkac(const Buffer<const char>& buf); -BIOPointer ExportPublicKey(const Buffer<const char>& buf); -DataPointer ExportChallenge(const Buffer<const char>& buf); - -// ============================================================================ -// KDF - -const EVP_MD* getDigestByName(const char* name); -const EVP_CIPHER* getCipherByName(const char* name); - -// Verify that the specified HKDF output length is valid for the given digest. -// The maximum length for HKDF output for a given digest is 255 times the -// hash size for the given digest algorithm. -bool checkHkdfLength(const Digest& digest, size_t length); - -bool extractP1363(const Buffer<const unsigned char>& buf, unsigned char* dest, size_t n); - -bool hkdfInfo(const Digest& md, const Buffer<const unsigned char>& key, const Buffer<const unsigned char>& info, - const Buffer<const unsigned char>& salt, size_t length, Buffer<unsigned char>* out); - -DataPointer hkdf(const Digest& md, const Buffer<const unsigned char>& key, const Buffer<const unsigned char>& info, - const Buffer<const unsigned char>& salt, size_t length); - -bool checkScryptParams(uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem); - -bool scryptInto(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint64_t N, uint64_t r, uint64_t p, - uint64_t maxmem, size_t length, Buffer<unsigned char>* out); - -DataPointer scrypt(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint64_t N, uint64_t r, uint64_t p, - uint64_t maxmem, size_t length); - -bool pbkdf2Into(const Digest& md, const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t iterations, - size_t length, Buffer<unsigned char>* out); - -DataPointer pbkdf2(const Digest& md, const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t iterations, - size_t length); - -#if OPENSSL_VERSION_NUMBER >= 0x30200000L -#ifndef OPENSSL_NO_ARGON2 -enum class Argon2Type { ARGON2D, ARGON2I, ARGON2ID }; - -DataPointer argon2(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t lanes, size_t length, uint32_t memcost, - uint32_t iter, uint32_t version, const Buffer<const unsigned char>& secret, const Buffer<const unsigned char>& ad, - Argon2Type type); -#endif -#endif - -// ============================================================================ -// KEM (Key Encapsulation Mechanism) -#if OPENSSL_VERSION_MAJOR >= 3 - -class KEM final { - public: - struct EncapsulateResult { - DataPointer ciphertext; - DataPointer shared_key; - - EncapsulateResult() = default; - EncapsulateResult(DataPointer ct, DataPointer sk) : ciphertext(std::move(ct)), shared_key(std::move(sk)) {} - }; - - // Encapsulate a shared secret using KEM with a public key. - // Returns both the ciphertext and shared secret. - static std::optional<EncapsulateResult> Encapsulate(const EVPKeyPointer& public_key); - - // Decapsulate a shared secret using KEM with a private key and ciphertext. - // Returns the shared secret. - static DataPointer Decapsulate(const EVPKeyPointer& private_key, const Buffer<const void>& ciphertext); - - private: -#if !OPENSSL_VERSION_PREREQ(3, 5) - static bool SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key); -#endif -}; - -#endif // OPENSSL_VERSION_MAJOR >= 3 - -#include "ncrypto/version.h" - -} // namespace ncrypto diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h deleted file mode 100644 index 5d4e01b64..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/aead.h +++ /dev/null @@ -1,136 +0,0 @@ -#pragma once - -#include "ncrypto.h" - -#ifdef OPENSSL_IS_BORINGSSL - -namespace ncrypto { - -class AeadCtxPointer; - -class Aead final { - private: - // BoringSSL does not keep a list of AEADs, so we need to maintain our own. - struct AeadInfo { - std::string name; - int mode; - int nid = 0; // Note: BoringSSL only defines NIDs for some AEADs - }; - - public: - Aead() = default; - Aead(const AeadInfo* info, const EVP_AEAD* aead) : aead_(aead), info_(info) {} - Aead(const Aead&) = default; - Aead& operator=(const Aead&) = default; - NCRYPTO_DISALLOW_MOVE(Aead) - - inline const EVP_AEAD* get() const { - return aead_; - } - std::string_view getModeLabel() const; - inline operator const EVP_AEAD*() const { - return aead_; - } - inline operator bool() const { - return aead_ != nullptr; - } - - int getMode() const; - int getNonceLength() const; - int getKeyLength() const; - int getBlockSize() const; - int getMaxOverhead() const; - int getMaxTagLength() const; - std::string_view getName() const; - - static const Aead FromName(std::string_view name); - - // TODO(npaun): BoringSSL does not define NIDs for all AEADs. - // This method is included only for implementing getCipherInfo and can't be - // used to construct an Aead instance. - int getNid() const; - // static const AEAD FromNid(int nid); - - static const Aead FromCtx(std::string_view name, const AeadCtxPointer& ctx); - - using AeadNameCallback = std::function<void(std::string_view name)>; - - // Iterates the known ciphers if the underlying implementation - // is able to do so. - static void ForEach(AeadNameCallback callback); - - // Utilities to get various AEADs by type. - - static const Aead EMPTY; - static const Aead AES_128_GCM; - static const Aead AES_192_GCM; - static const Aead AES_256_GCM; - static const Aead CHACHA20_POLY1305; - static const Aead XCHACHA20_POLY1305; - static const Aead AES_128_CTR_HMAC_SHA256; - static const Aead AES_256_CTR_HMAC_SHA256; - static const Aead AES_128_GCM_SIV; - static const Aead AES_256_GCM_SIV; - static const Aead AES_128_GCM_RANDNONCE; - static const Aead AES_256_GCM_RANDNONCE; - static const Aead AES_128_CCM_BLUETOOTH; - static const Aead AES_128_CCM_BLUETOOTH_8; - static const Aead AES_128_CCM_MATTER; - static const Aead AES_128_EAX; - static const Aead AES_256_EAX; - - private: - const EVP_AEAD* aead_ = nullptr; - const AeadInfo* info_ = nullptr; - - using AeadConstructor = const EVP_AEAD* (*)(); - static const std::unordered_map<AeadConstructor, AeadInfo> aeadIndex; - static const Aead FromConstructor(AeadConstructor construct); -}; - -class AeadCtxPointer final { - public: - static AeadCtxPointer New(const Aead& aead, bool encrypt, const unsigned char* key = nullptr, size_t keyLen = 0, - size_t tagLen = EVP_AEAD_DEFAULT_TAG_LENGTH /* = 0 */); - - AeadCtxPointer() = default; - explicit AeadCtxPointer(EVP_AEAD_CTX* ctx); - AeadCtxPointer(AeadCtxPointer&& other) noexcept; - AeadCtxPointer& operator=(AeadCtxPointer&& other) noexcept; - NCRYPTO_DISALLOW_COPY(AeadCtxPointer) - ~AeadCtxPointer(); - - inline bool operator==(std::nullptr_t) const noexcept { - return ctx_ == nullptr; - } - inline operator bool() const { - return ctx_ != nullptr; - } - inline EVP_AEAD_CTX* get() const { - return ctx_.get(); - } - inline operator EVP_AEAD_CTX*() const { - return ctx_.get(); - } - void reset(EVP_AEAD_CTX* ctx = nullptr); - EVP_AEAD_CTX* release(); - - bool init(const Aead& aead, bool encrypt, const unsigned char* key = nullptr, size_t keyLen = 0, - size_t tagLen = EVP_AEAD_DEFAULT_TAG_LENGTH /* = 0 */); - - // TODO(npaun): BoringSSL does not define NIDs for all AEADs. - // Decide if we will even implement this method. - // int getNid() const; - - bool encrypt(const Buffer<const unsigned char>& in, Buffer<unsigned char>& out, Buffer<unsigned char>& tag, - const Buffer<const unsigned char>& nonce, const Buffer<const unsigned char>& aad); - - bool decrypt(const Buffer<const unsigned char>& in, Buffer<unsigned char>& out, const Buffer<const unsigned char>& tag, - const Buffer<const unsigned char>& nonce, const Buffer<const unsigned char>& aad); - - private: - DeleteFnPtr<EVP_AEAD_CTX, EVP_AEAD_CTX_free> ctx_; -}; -} // namespace ncrypto - -#endif // OPENSSL_IS_BORINGSSL diff --git a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h b/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h deleted file mode 100644 index 695c705d6..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/include/ncrypto/version.h +++ /dev/null @@ -1,14 +0,0 @@ -// ============================================================================ -// Version metadata -#ifndef NCRYPTO_VERSION_H_ -#define NCRYPTO_VERSION_H_ - -#define NCRYPTO_VERSION "1.1.4" // x-release-please-version - -enum { - NCRYPTO_VERSION_MAJOR = 1, // x-release-please-major - NCRYPTO_VERSION_MINOR = 1, // x-release-please-minor - NCRYPTO_VERSION_REVISION = 4, // x-release-please-patch -}; - -#endif // NCRYPTO_VERSION_H_ diff --git a/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp b/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp deleted file mode 100644 index edd6f1044..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/src/aead.cpp +++ /dev/null @@ -1,249 +0,0 @@ -// ============================================================================ -// AEAD (Authenticated Encryption with Associated Data) -#include "ncrypto.h" - -#ifdef OPENSSL_IS_BORINGSSL -#include "ncrypto/aead.h" - -namespace ncrypto { - -const Aead Aead::FromName(std::string_view name) { - for (const auto& [construct, info] : aeadIndex) { - if (EqualNoCase(info.name, name)) { - return Aead(&info, construct()); - } - } - - return Aead(); -} - -const Aead Aead::FromCtx(std::string_view name, const AeadCtxPointer& ctx) { - for (const auto& [_, info] : aeadIndex) { - if (info.name == name) { - return Aead(&info, EVP_AEAD_CTX_aead(ctx.get())); - } - } - - return Aead(); -} - -int Aead::getMode() const { - if (!aead_) - return -1; - - return info_->mode; -} - -std::string_view Aead::getModeLabel() const { - if (!aead_) - return {}; - switch (getMode()) { - case EVP_CIPH_CCM_MODE: - return "ccm"; - case EVP_CIPH_CTR_MODE: - return "ctr"; - case EVP_CIPH_GCM_MODE: - return "gcm"; - case EVP_CIPH_STREAM_CIPHER: - return "stream"; - } - return "{unknown}"; -} - -int Aead::getNonceLength() const { - if (!aead_) - return 0; - return EVP_AEAD_nonce_length(aead_); -} - -int Aead::getKeyLength() const { - if (!aead_) - return 0; - return EVP_AEAD_key_length(aead_); -} - -int Aead::getMaxOverhead() const { - if (!aead_) - return 0; - return EVP_AEAD_max_overhead(aead_); -} - -int Aead::getMaxTagLength() const { - if (!aead_) - return 0; - return EVP_AEAD_max_tag_len(aead_); -} - -int Aead::getBlockSize() const { - if (!aead_) - return 0; - - // EVP_CIPHER_CTX_block_size returns the block size, in bytes, of the cipher - // underlying |ctx|, or one if the cipher is a stream cipher. - return 1; -} - -std::string_view Aead::getName() const { - if (!aead_) - return ""; - - return info_->name; -} - -int Aead::getNid() const { - if (!aead_) - return 0; - - return info_->nid; -} - -const Aead Aead::FromConstructor(Aead::AeadConstructor construct) { - return Aead(&aeadIndex.at(construct), construct()); -} - -const std::unordered_map<Aead::AeadConstructor, Aead::AeadInfo> Aead::aeadIndex = { - {EVP_aead_aes_128_gcm, {.name = LN_aes_128_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_128_gcm}}, - {EVP_aead_aes_192_gcm, {.name = LN_aes_192_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_192_gcm}}, - {EVP_aead_aes_256_gcm, {.name = LN_aes_256_gcm, .mode = EVP_CIPH_GCM_MODE, .nid = NID_aes_256_gcm}}, - {EVP_aead_chacha20_poly1305, {.name = LN_chacha20_poly1305, .mode = EVP_CIPH_STREAM_CIPHER, .nid = NID_chacha20_poly1305}}, - {EVP_aead_xchacha20_poly1305, - { - .name = "xchacha20-poly1305", - .mode = EVP_CIPH_STREAM_CIPHER, - }}, - {EVP_aead_aes_128_ctr_hmac_sha256, - { - .name = "aes-128-ctr-hmac-sha256", - .mode = EVP_CIPH_CTR_MODE, - }}, - {EVP_aead_aes_256_ctr_hmac_sha256, - { - .name = "aes-256-ctr-hmac-sha256", - .mode = EVP_CIPH_CTR_MODE, - }}, - {EVP_aead_aes_128_gcm_siv, - { - .name = "aes-128-gcm-siv", - .mode = EVP_CIPH_GCM_MODE, - }}, - {EVP_aead_aes_256_gcm_siv, - { - .name = "aes-256-gcm-siv", - .mode = EVP_CIPH_GCM_MODE, - }}, - {EVP_aead_aes_128_gcm_randnonce, - { - .name = "aes-128-gcm-randnonce", - .mode = EVP_CIPH_GCM_MODE, - }}, - {EVP_aead_aes_256_gcm_randnonce, - { - .name = "aes-256-gcm-randnonce", - .mode = EVP_CIPH_GCM_MODE, - }}, - {EVP_aead_aes_128_ccm_bluetooth, - { - .name = "aes-128-ccm-bluetooth", - .mode = EVP_CIPH_CCM_MODE, - }}, - {EVP_aead_aes_128_ccm_bluetooth_8, - { - .name = "aes-128-ccm-bluetooth-8", - .mode = EVP_CIPH_CCM_MODE, - }}, - {EVP_aead_aes_128_ccm_matter, - { - .name = "aes-128-ccm-matter", - .mode = EVP_CIPH_CCM_MODE, - }}, - {EVP_aead_aes_128_eax, - {.name = "aes-128-eax", - // BoringSSL does not define a mode constant for EAX. Using STREAM - // arbitrarily - .mode = EVP_CIPH_STREAM_CIPHER}}, - {EVP_aead_aes_256_eax, - {.name = "aes-256-eax", - // BoringSSL does not define a mode constant for EAX. Using STREAM - // arbitrarily - .mode = EVP_CIPH_STREAM_CIPHER}}, -}; - -void Aead::ForEach(AeadNameCallback callback) { - for (const auto& [_, info] : aeadIndex) { - callback(info.name); - } -} - -const Aead Aead::EMPTY = Aead(); -const Aead Aead::AES_128_GCM = Aead::FromConstructor(EVP_aead_aes_128_gcm); -const Aead Aead::AES_192_GCM = Aead::FromConstructor(EVP_aead_aes_192_gcm); -const Aead Aead::AES_256_GCM = Aead::FromConstructor(EVP_aead_aes_256_gcm); -const Aead Aead::CHACHA20_POLY1305 = Aead::FromConstructor(EVP_aead_chacha20_poly1305); -const Aead Aead::XCHACHA20_POLY1305 = Aead::FromConstructor(EVP_aead_xchacha20_poly1305); -const Aead Aead::AES_128_CTR_HMAC_SHA256 = Aead::FromConstructor(EVP_aead_aes_128_ctr_hmac_sha256); -const Aead Aead::AES_256_CTR_HMAC_SHA256 = Aead::FromConstructor(EVP_aead_aes_256_ctr_hmac_sha256); -const Aead Aead::AES_128_GCM_SIV = Aead::FromConstructor(EVP_aead_aes_128_gcm_siv); -const Aead Aead::AES_256_GCM_SIV = Aead::FromConstructor(EVP_aead_aes_256_gcm_siv); -const Aead Aead::AES_128_GCM_RANDNONCE = Aead::FromConstructor(EVP_aead_aes_128_gcm_randnonce); -const Aead Aead::AES_256_GCM_RANDNONCE = Aead::FromConstructor(EVP_aead_aes_256_gcm_randnonce); -const Aead Aead::AES_128_CCM_BLUETOOTH = Aead::FromConstructor(EVP_aead_aes_128_ccm_bluetooth); -const Aead Aead::AES_128_CCM_BLUETOOTH_8 = Aead::FromConstructor(EVP_aead_aes_128_ccm_bluetooth_8); -const Aead Aead::AES_128_CCM_MATTER = Aead::FromConstructor(EVP_aead_aes_128_ccm_matter); -const Aead Aead::AES_128_EAX = Aead::FromConstructor(EVP_aead_aes_128_eax); -const Aead Aead::AES_256_EAX = Aead::FromConstructor(EVP_aead_aes_256_eax); - -AeadCtxPointer AeadCtxPointer::New(const Aead& aead, bool encrypt, const unsigned char* key, size_t keyLen, size_t tagLen) { - // Note: In the EVP_AEAD API new always calls init - auto ret = AeadCtxPointer(EVP_AEAD_CTX_new(aead.get(), key, keyLen, tagLen)); - - if (!ret) { - return {}; - } - - return ret; -} - -AeadCtxPointer::AeadCtxPointer(EVP_AEAD_CTX* ctx) : ctx_(ctx) {} - -AeadCtxPointer::AeadCtxPointer(AeadCtxPointer&& other) noexcept : ctx_(other.release()) {} - -AeadCtxPointer& AeadCtxPointer::operator=(AeadCtxPointer&& other) noexcept { - if (this == &other) - return *this; - this->~AeadCtxPointer(); - return *new (this) AeadCtxPointer(std::move(other)); -} - -AeadCtxPointer::~AeadCtxPointer() { - reset(); -} - -void AeadCtxPointer::reset(EVP_AEAD_CTX* ctx) { - ctx_.reset(ctx); -} - -EVP_AEAD_CTX* AeadCtxPointer::release() { - return ctx_.release(); -} - -bool AeadCtxPointer::init(const Aead& aead, bool encrypt, const unsigned char* key, size_t keyLen, size_t tagLen) { - return EVP_AEAD_CTX_init_with_direction(ctx_.get(), aead, key, keyLen, tagLen, encrypt ? evp_aead_seal : evp_aead_open); -} - -bool AeadCtxPointer::encrypt(const Buffer<const unsigned char>& in, Buffer<unsigned char>& out, Buffer<unsigned char>& tag, - const Buffer<const unsigned char>& nonce, const Buffer<const unsigned char>& aad) { - if (!ctx_) - return false; - return EVP_AEAD_CTX_seal_scatter(ctx_.get(), out.data, tag.data, &tag.len, tag.len, nonce.data, nonce.len, in.data, in.len, - nullptr /* extra_in */, 0 /* extra_in_len */, aad.data, aad.len) == 1; -} - -bool AeadCtxPointer::decrypt(const Buffer<const unsigned char>& in, Buffer<unsigned char>& out, const Buffer<const unsigned char>& tag, - const Buffer<const unsigned char>& nonce, const Buffer<const unsigned char>& aad) { - if (!ctx_) - return false; - - return EVP_AEAD_CTX_open_gather(ctx_.get(), out.data, nonce.data, nonce.len, in.data, in.len, tag.data, tag.len, aad.data, aad.len) == 1; -} -} // namespace ncrypto -#endif diff --git a/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp b/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp deleted file mode 100644 index 07d587bb9..000000000 --- a/packages/react-native-quick-crypto/deps/ncrypto/src/ncrypto.cpp +++ /dev/null @@ -1,3810 +0,0 @@ -#include "ncrypto.h" -#include <openssl/asn1.h> -#include <openssl/bn.h> -#include <openssl/core_names.h> -#include <openssl/encoder.h> -#include <openssl/evp.h> -#include <openssl/hmac.h> -#include <openssl/pem.h> -#include <openssl/pkcs12.h> -#include <openssl/rand.h> -#include <openssl/x509v3.h> - -#ifndef NCRYPTO_NO_KDF_H -#include <openssl/kdf.h> -#endif -#ifdef OPENSSL_IS_BORINGSSL -#include <openssl/hkdf.h> -#endif - -#include <algorithm> -#include <array> -#include <climits> -#include <cstring> -#include <string_view> -#include <vector> -#if OPENSSL_VERSION_MAJOR >= 3 -#include <openssl/core_names.h> -#include <openssl/params.h> -#include <openssl/provider.h> -#if OPENSSL_VERSION_NUMBER >= 0x30200000L -#include <openssl/thread.h> -#endif -#endif -#if OPENSSL_WITH_PQC -struct PQCMapping { - const char* name; - int nid; -}; - -constexpr static PQCMapping pqc_mappings[] = { - {"ML-DSA-44", EVP_PKEY_ML_DSA_44}, - {"ML-DSA-65", EVP_PKEY_ML_DSA_65}, - {"ML-DSA-87", EVP_PKEY_ML_DSA_87}, - {"ML-KEM-512", EVP_PKEY_ML_KEM_512}, - {"ML-KEM-768", EVP_PKEY_ML_KEM_768}, - {"ML-KEM-1024", EVP_PKEY_ML_KEM_1024}, - {"SLH-DSA-SHA2-128f", EVP_PKEY_SLH_DSA_SHA2_128F}, - {"SLH-DSA-SHA2-128s", EVP_PKEY_SLH_DSA_SHA2_128S}, - {"SLH-DSA-SHA2-192f", EVP_PKEY_SLH_DSA_SHA2_192F}, - {"SLH-DSA-SHA2-192s", EVP_PKEY_SLH_DSA_SHA2_192S}, - {"SLH-DSA-SHA2-256f", EVP_PKEY_SLH_DSA_SHA2_256F}, - {"SLH-DSA-SHA2-256s", EVP_PKEY_SLH_DSA_SHA2_256S}, - {"SLH-DSA-SHAKE-128f", EVP_PKEY_SLH_DSA_SHAKE_128F}, - {"SLH-DSA-SHAKE-128s", EVP_PKEY_SLH_DSA_SHAKE_128S}, - {"SLH-DSA-SHAKE-192f", EVP_PKEY_SLH_DSA_SHAKE_192F}, - {"SLH-DSA-SHAKE-192s", EVP_PKEY_SLH_DSA_SHAKE_192S}, - {"SLH-DSA-SHAKE-256f", EVP_PKEY_SLH_DSA_SHAKE_256F}, - {"SLH-DSA-SHAKE-256s", EVP_PKEY_SLH_DSA_SHAKE_256S}, -}; - -#endif - -// EVP_PKEY_CTX_set_dsa_paramgen_q_bits was added in OpenSSL 1.1.1e. -#if OPENSSL_VERSION_NUMBER < 0x1010105fL -#define EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits) \ - EVP_PKEY_CTX_ctrl((ctx), EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, (qbits), nullptr) -#endif - -namespace ncrypto { -namespace { - using BignumCtxPointer = DeleteFnPtr<BN_CTX, BN_CTX_free>; - using BignumGenCallbackPointer = DeleteFnPtr<BN_GENCB, BN_GENCB_free>; - using NetscapeSPKIPointer = DeleteFnPtr<NETSCAPE_SPKI, NETSCAPE_SPKI_free>; - - static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON = XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB & ~ASN1_STRFLGS_ESC_CTRL; -} // namespace - -// ============================================================================ - -ClearErrorOnReturn::ClearErrorOnReturn(CryptoErrorList* errors) : errors_(errors) { - ERR_clear_error(); -} - -ClearErrorOnReturn::~ClearErrorOnReturn() { - if (errors_ != nullptr) - errors_->capture(); - ERR_clear_error(); -} - -int ClearErrorOnReturn::peekError() { - return ERR_peek_error(); -} - -MarkPopErrorOnReturn::MarkPopErrorOnReturn(CryptoErrorList* errors) : errors_(errors) { - ERR_set_mark(); -} - -MarkPopErrorOnReturn::~MarkPopErrorOnReturn() { - if (errors_ != nullptr) - errors_->capture(); - ERR_pop_to_mark(); -} - -int MarkPopErrorOnReturn::peekError() { - return ERR_peek_error(); -} - -CryptoErrorList::CryptoErrorList(CryptoErrorList::Option option) { - if (option == Option::CAPTURE_ON_CONSTRUCT) - capture(); -} - -void CryptoErrorList::capture() { - errors_.clear(); - while (const auto err = ERR_get_error()) { - char buf[256]; - ERR_error_string_n(err, buf, sizeof(buf)); - errors_.emplace_front(buf); - } -} - -void CryptoErrorList::add(std::string error) { - errors_.push_back(error); -} - -std::optional<std::string> CryptoErrorList::pop_back() { - if (errors_.empty()) - return std::nullopt; - std::string error = errors_.back(); - errors_.pop_back(); - return error; -} - -std::optional<std::string> CryptoErrorList::pop_front() { - if (errors_.empty()) - return std::nullopt; - std::string error = errors_.front(); - errors_.pop_front(); - return error; -} - -// ============================================================================ -DataPointer DataPointer::Alloc(size_t len) { -#ifdef OPENSSL_IS_BORINGSSL - // Boringssl does not implement OPENSSL_zalloc - auto ptr = OPENSSL_malloc(len); - if (ptr == nullptr) - return {}; - memset(ptr, 0, len); - return DataPointer(ptr, len); -#else - return DataPointer(OPENSSL_zalloc(len), len); -#endif -} - -DataPointer DataPointer::SecureAlloc(size_t len) { -#ifndef OPENSSL_IS_BORINGSSL - auto ptr = OPENSSL_secure_zalloc(len); - if (ptr == nullptr) - return {}; - return DataPointer(ptr, len, true); -#else - // BoringSSL does not implement the OPENSSL_secure_zalloc API. - auto ptr = OPENSSL_malloc(len); - if (ptr == nullptr) - return {}; - memset(ptr, 0, len); - return DataPointer(ptr, len); -#endif -} - -size_t DataPointer::GetSecureHeapUsed() { -#ifndef OPENSSL_IS_BORINGSSL - return CRYPTO_secure_malloc_initialized() ? CRYPTO_secure_used() : 0; -#else - // BoringSSL does not have the secure heap and therefore - // will always return 0. - return 0; -#endif -} - -DataPointer::InitSecureHeapResult DataPointer::TryInitSecureHeap(size_t amount, size_t min) { -#ifndef OPENSSL_IS_BORINGSSL - switch (CRYPTO_secure_malloc_init(amount, min)) { - case 0: - return InitSecureHeapResult::FAILED; - case 2: - return InitSecureHeapResult::UNABLE_TO_MEMORY_MAP; - case 1: - return InitSecureHeapResult::OK; - default: - return InitSecureHeapResult::FAILED; - } -#else - // BoringSSL does not actually support the secure heap - return InitSecureHeapResult::FAILED; -#endif -} - -DataPointer DataPointer::Copy(const Buffer<const void>& buffer) { - return DataPointer(OPENSSL_memdup(buffer.data, buffer.len), buffer.len); -} - -DataPointer::DataPointer(void* data, size_t length, bool secure) : data_(data), len_(length), secure_(secure) {} - -DataPointer::DataPointer(const Buffer<void>& buffer, bool secure) : data_(buffer.data), len_(buffer.len), secure_(secure) {} - -DataPointer::DataPointer(DataPointer&& other) noexcept : data_(other.data_), len_(other.len_), secure_(other.secure_) { - other.data_ = nullptr; - other.len_ = 0; - other.secure_ = false; -} - -DataPointer& DataPointer::operator=(DataPointer&& other) noexcept { - if (this == &other) - return *this; - this->~DataPointer(); - return *new (this) DataPointer(std::move(other)); -} - -DataPointer::~DataPointer() { - reset(); -} - -void DataPointer::zero() { - if (!data_) - return; - OPENSSL_cleanse(data_, len_); -} - -void DataPointer::free() { - if (data_ != nullptr) { - if (secure_) { - OPENSSL_secure_clear_free(data_, len_); - } else { - OPENSSL_clear_free(data_, len_); - } - } -} - -void DataPointer::reset(void* data, size_t length) { - free(); - data_ = data; - len_ = length; -} - -void DataPointer::reset(const Buffer<void>& buffer) { - reset(buffer.data, buffer.len); -} - -Buffer<void> DataPointer::release() { - Buffer<void> buf{ - .data = data_, - .len = len_, - }; - data_ = nullptr; - len_ = 0; - return buf; -} - -DataPointer DataPointer::resize(size_t len) { - size_t actual_len = std::min(len_, len); - auto buf = release(); - if (actual_len == len_) - return DataPointer(buf.data, actual_len); - auto new_data = OPENSSL_realloc(buf.data, actual_len); - if (new_data == nullptr) { - free(); - return {}; - } - buf.data = new_data; - buf.len = actual_len; - return DataPointer(buf); -} - -// ============================================================================ -bool isFipsEnabled() { - ClearErrorOnReturn clear_error_on_return; -#if OPENSSL_VERSION_MAJOR >= 3 - return EVP_default_properties_is_fips_enabled(nullptr) == 1; -#else - return FIPS_mode() == 1; -#endif -} - -bool setFipsEnabled(bool enable, CryptoErrorList* errors) { - if (isFipsEnabled() == enable) - return true; - ClearErrorOnReturn clearErrorOnReturn(errors); -#if OPENSSL_VERSION_MAJOR >= 3 - return EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1 && EVP_default_properties_is_fips_enabled(nullptr); -#else - return FIPS_mode_set(enable ? 1 : 0) == 1; -#endif -} - -bool testFipsEnabled() { - ClearErrorOnReturn clear_error_on_return; -#if OPENSSL_VERSION_MAJOR >= 3 - OSSL_PROVIDER* fips_provider = nullptr; - if (OSSL_PROVIDER_available(nullptr, "fips")) { - fips_provider = OSSL_PROVIDER_load(nullptr, "fips"); - } - if (fips_provider == nullptr) - return false; - int result = OSSL_PROVIDER_self_test(fips_provider); - OSSL_PROVIDER_unload(fips_provider); - return result; -#else -#ifdef OPENSSL_FIPS - return FIPS_selftest(); -#else // OPENSSL_FIPS - return false; -#endif // OPENSSL_FIPS -#endif -} - -// ============================================================================ -// Bignum -BignumPointer::BignumPointer(BIGNUM* bignum) : bn_(bignum) {} - -BignumPointer::BignumPointer(const unsigned char* data, size_t len) : BignumPointer(BN_bin2bn(data, len, nullptr)) {} - -BignumPointer::BignumPointer(BignumPointer&& other) noexcept : bn_(other.release()) {} - -BignumPointer BignumPointer::New() { - return BignumPointer(BN_new()); -} - -BignumPointer BignumPointer::NewSecure() { -#ifdef OPENSSL_IS_BORINGSSL - // Boringssl does not implement BN_secure_new. - return New(); -#else - return BignumPointer(BN_secure_new()); -#endif -} - -BignumPointer& BignumPointer::operator=(BignumPointer&& other) noexcept { - if (this == &other) - return *this; - this->~BignumPointer(); - return *new (this) BignumPointer(std::move(other)); -} - -BignumPointer::~BignumPointer() { - reset(); -} - -void BignumPointer::reset(BIGNUM* bn) { - bn_.reset(bn); -} - -void BignumPointer::reset(const unsigned char* data, size_t len) { - reset(BN_bin2bn(data, len, nullptr)); -} - -BIGNUM* BignumPointer::release() { - return bn_.release(); -} - -size_t BignumPointer::byteLength() const { - if (bn_ == nullptr) - return 0; - return BN_num_bytes(bn_.get()); -} - -size_t BignumPointer::bitLength() const { - if (bn_ == nullptr) - return 0; - return BN_num_bits(bn_.get()); -} - -DataPointer BignumPointer::encode() const { - return EncodePadded(bn_.get(), byteLength()); -} - -DataPointer BignumPointer::encodePadded(size_t size) const { - return EncodePadded(bn_.get(), size); -} - -size_t BignumPointer::encodeInto(unsigned char* out) const { - if (!bn_) - return 0; - return BN_bn2bin(bn_.get(), out); -} - -size_t BignumPointer::encodePaddedInto(unsigned char* out, size_t size) const { - if (!bn_) - return 0; - return BN_bn2binpad(bn_.get(), out, size); -} - -DataPointer BignumPointer::Encode(const BIGNUM* bn) { - return EncodePadded(bn, bn != nullptr ? BN_num_bytes(bn) : 0); -} - -bool BignumPointer::setWord(unsigned long w) { // NOLINT(runtime/int) - if (!bn_) - return false; - return BN_set_word(bn_.get(), w) == 1; -} - -unsigned long BignumPointer::GetWord(const BIGNUM* bn) { // NOLINT(runtime/int) - return BN_get_word(bn); -} - -unsigned long BignumPointer::getWord() const { // NOLINT(runtime/int) - if (!bn_) - return 0; - return GetWord(bn_.get()); -} - -DataPointer BignumPointer::EncodePadded(const BIGNUM* bn, size_t s) { - if (bn == nullptr) - return DataPointer(); - size_t size = std::max(s, static_cast<size_t>(GetByteCount(bn))); - auto buf = DataPointer::Alloc(size); - BN_bn2binpad(bn, reinterpret_cast<unsigned char*>(buf.get()), size); - return buf; -} -size_t BignumPointer::EncodePaddedInto(const BIGNUM* bn, unsigned char* out, size_t size) { - if (bn == nullptr) - return 0; - return BN_bn2binpad(bn, out, size); -} - -int BignumPointer::operator<=>(const BignumPointer& other) const noexcept { - if (bn_ == nullptr && other.bn_ != nullptr) - return -1; - if (bn_ != nullptr && other.bn_ == nullptr) - return 1; - if (bn_ == nullptr && other.bn_ == nullptr) - return 0; - return BN_cmp(bn_.get(), other.bn_.get()); -} - -int BignumPointer::operator<=>(const BIGNUM* other) const noexcept { - if (bn_ == nullptr && other != nullptr) - return -1; - if (bn_ != nullptr && other == nullptr) - return 1; - if (bn_ == nullptr && other == nullptr) - return 0; - return BN_cmp(bn_.get(), other); -} - -DataPointer BignumPointer::toHex() const { - if (!bn_) - return {}; - char* hex = BN_bn2hex(bn_.get()); - if (!hex) - return {}; - return DataPointer(hex, strlen(hex)); -} - -int BignumPointer::GetBitCount(const BIGNUM* bn) { - return BN_num_bits(bn); -} - -int BignumPointer::GetByteCount(const BIGNUM* bn) { - return BN_num_bytes(bn); -} - -bool BignumPointer::isZero() const { - return bn_ && BN_is_zero(bn_.get()); -} - -bool BignumPointer::isOne() const { - return bn_ && BN_is_one(bn_.get()); -} - -const BIGNUM* BignumPointer::One() { - return BN_value_one(); -} - -BignumPointer BignumPointer::clone() { - if (!bn_) - return {}; - return BignumPointer(BN_dup(bn_.get())); -} - -int BignumPointer::isPrime(int nchecks, BignumPointer::PrimeCheckCallback innerCb) const { - BignumCtxPointer ctx(BN_CTX_new()); - BignumGenCallbackPointer cb(nullptr); - if (innerCb != nullptr) { - cb = BignumGenCallbackPointer(BN_GENCB_new()); - if (!cb) [[unlikely]] - return -1; - BN_GENCB_set( - cb.get(), - // TODO(@jasnell): This could be refactored to allow inlining. - // Not too important right now tho. - [](int a, int b, BN_GENCB* ctx) mutable -> int { - // BN_GENCB is opaque in OpenSSL 3.x, must use accessor - PrimeCheckCallback& ptr = *static_cast<PrimeCheckCallback*>(BN_GENCB_get_arg(ctx)); - return ptr(a, b) ? 1 : 0; - }, - &innerCb); - } - const int minimum_checks = bitLength() > 2048 ? 128 : 64; - const int repetitions = nchecks > minimum_checks ? 1 + (nchecks - 1) / minimum_checks : 1; - for (int i = 0; i < repetitions; i++) { - const int result = BN_check_prime(get(), ctx.get(), cb.get()); - if (result != 1) - return result; - } - return 1; -} - -BignumPointer BignumPointer::NewPrime(const PrimeConfig& params, PrimeCheckCallback cb) { - BignumPointer prime(BN_new()); - if (!prime || !prime.generate(params, std::move(cb))) { - return {}; - } - return prime; -} - -bool BignumPointer::generate(const PrimeConfig& params, PrimeCheckCallback innerCb) const { - // BN_generate_prime_ex() calls RAND_bytes_ex() internally. - // Make sure the CSPRNG is properly seeded. - std::ignore = CSPRNG(nullptr, 0); - BignumGenCallbackPointer cb(nullptr); - if (innerCb != nullptr) { - cb = BignumGenCallbackPointer(BN_GENCB_new()); - if (!cb) [[unlikely]] - return -1; - BN_GENCB_set( - cb.get(), - [](int a, int b, BN_GENCB* ctx) mutable -> int { - // BN_GENCB is opaque in OpenSSL 3.x, must use accessor - PrimeCheckCallback& ptr = *static_cast<PrimeCheckCallback*>(BN_GENCB_get_arg(ctx)); - return ptr(a, b) ? 1 : 0; - }, - &innerCb); - } - if (BN_generate_prime_ex(get(), params.bits, params.safe ? 1 : 0, params.add.get(), params.rem.get(), cb.get()) == 0) { - return false; - } - - return true; -} - -BignumPointer BignumPointer::NewSub(const BignumPointer& a, const BignumPointer& b) { - BignumPointer res = New(); - if (!res) - return {}; - if (!BN_sub(res.get(), a.get(), b.get())) { - return {}; - } - return res; -} - -BignumPointer BignumPointer::NewLShift(size_t length) { - BignumPointer res = New(); - if (!res) - return {}; - if (!BN_lshift(res.get(), One(), length)) { - return {}; - } - return res; -} - -// ============================================================================ -// Utility methods - -bool CSPRNG(void* buffer, size_t length) { - auto buf = reinterpret_cast<unsigned char*>(buffer); - do { - if (1 == RAND_status()) { -#if OPENSSL_VERSION_MAJOR >= 3 - if (1 == RAND_bytes_ex(nullptr, buf, length, 0)) { - return true; - } -#else - while (length > INT_MAX && 1 == RAND_bytes(buf, INT_MAX)) { - buf += INT_MAX; - length -= INT_MAX; - } - if (length <= INT_MAX && 1 == RAND_bytes(buf, static_cast<int>(length))) - return true; -#endif - } -#if OPENSSL_VERSION_MAJOR >= 3 - const auto code = ERR_peek_last_error(); - // A misconfigured OpenSSL 3 installation may report 1 from RAND_poll() - // and RAND_status() but fail in RAND_bytes() if it cannot look up - // a matching algorithm for the CSPRNG. - if (ERR_GET_LIB(code) == ERR_LIB_RAND) { - const auto reason = ERR_GET_REASON(code); - if (reason == RAND_R_ERROR_INSTANTIATING_DRBG || reason == RAND_R_UNABLE_TO_FETCH_DRBG || reason == RAND_R_UNABLE_TO_CREATE_DRBG) { - return false; - } - } -#endif - } while (1 == RAND_poll()); - - return false; -} - -int NoPasswordCallback(char*, int, int, void*) { - return 0; -} - -int PasswordCallback(char* buf, int size, int, void* u) { - auto passphrase = static_cast<const Buffer<char>*>(u); - if (passphrase != nullptr) { - size_t buflen = static_cast<size_t>(size); - size_t len = passphrase->len; - if (buflen < len) - return -1; - memcpy(buf, reinterpret_cast<const char*>(passphrase->data), len); - return len; - } - - return -1; -} - -// Algorithm: http://howardhinnant.github.io/date_algorithms.html -constexpr int days_from_epoch(int y, unsigned m, unsigned d) { - y -= m <= 2; - const int era = (y >= 0 ? y : y - 399) / 400; - const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399] - const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; // [0, 365] - const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] - return era * 146097 + static_cast<int>(doe) - 719468; -} - -#ifndef OPENSSL_IS_BORINGSSL -// tm must be in UTC -// using time_t causes problems on 32-bit systems and windows x64. -int64_t PortableTimeGM(struct tm* t) { - int year = t->tm_year + 1900; - int month = t->tm_mon; - if (month > 11) { - year += month / 12; - month %= 12; - } else if (month < 0) { - int years_diff = (11 - month) / 12; - year -= years_diff; - month += 12 * years_diff; - } - int days_since_epoch = days_from_epoch(year, month + 1, t->tm_mday); - - return 60 * (60 * (24LL * static_cast<int64_t>(days_since_epoch) + t->tm_hour) + t->tm_min) + t->tm_sec; -} -#endif - -// ============================================================================ -// SPKAC - -bool VerifySpkac(const char* input, size_t length) { -#ifdef OPENSSL_IS_BORINGSSL - // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, - // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. - // As such, we trim those characters here for compatibility. - // - // find_last_not_of can return npos, which is the maximum value of size_t. - // The + 1 will force a roll-ver to 0, which is the correct value. in that - // case. - length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; -#endif - NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length)); - if (!spki) - return false; - - EVPKeyPointer pkey(X509_PUBKEY_get(spki->spkac->pubkey)); - return pkey ? NETSCAPE_SPKI_verify(spki.get(), pkey.get()) > 0 : false; -} - -BIOPointer ExportPublicKey(const char* input, size_t length) { - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - -#ifdef OPENSSL_IS_BORINGSSL - // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, - // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. - // As such, we trim those characters here for compatibility. - length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; -#endif - NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length)); - if (!spki) - return {}; - - EVPKeyPointer pkey(NETSCAPE_SPKI_get_pubkey(spki.get())); - if (!pkey) - return {}; - - if (PEM_write_bio_PUBKEY(bio.get(), pkey.get()) <= 0) - return {}; - - return bio; -} - -Buffer<char> ExportChallenge(const char* input, size_t length) { -#ifdef OPENSSL_IS_BORINGSSL - // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, - // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. - // As such, we trim those characters here for compatibility. - length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1; -#endif - NetscapeSPKIPointer sp(NETSCAPE_SPKI_b64_decode(input, length)); - if (!sp) - return {}; - - unsigned char* buf = nullptr; - int buf_size = ASN1_STRING_to_UTF8(&buf, sp->spkac->challenge); - if (buf_size >= 0) { - return { - .data = reinterpret_cast<char*>(buf), - .len = static_cast<size_t>(buf_size), - }; - } - - return {}; -} - -bool VerifySpkac(const Buffer<const char>& input) { - return VerifySpkac(input.data, input.len); -} - -BIOPointer ExportPublicKey(const Buffer<const char>& input) { - return ExportPublicKey(input.data, input.len); -} - -DataPointer ExportChallenge(const Buffer<const char>& input) { - auto buf = ExportChallenge(input.data, input.len); - if (buf.data != nullptr) { - return DataPointer(buf.data, buf.len); - } - return {}; -} - -// ============================================================================ -namespace { - enum class AltNameOption { - NONE, - UTF8, - }; - - bool IsSafeAltName(const char* name, size_t length, AltNameOption option) { - for (size_t i = 0; i < length; i++) { - char c = name[i]; - switch (c) { - case '"': - case '\\': - // These mess with encoding rules. - // Fall through. - case ',': - // Commas make it impossible to split the list of subject alternative - // names unambiguously, which is why we have to escape. - // Fall through. - case '\'': - // Single quotes are unlikely to appear in any legitimate values, but - // they could be used to make a value look like it was escaped (i.e., - // enclosed in single/double quotes). - return false; - default: - if (option == AltNameOption::UTF8) { - // In UTF8 strings, we require escaping for any ASCII control - // character, but NOT for non-ASCII characters. Note that all bytes of - // any code point that consists of more than a single byte have their - // MSB set. - if (static_cast<unsigned char>(c) < ' ' || c == '\x7f') { - return false; - } - } else { - // Check if the char is a control character or non-ASCII character. - // Note that char may or may not be a signed type. Regardless, - // non-ASCII values will always be outside of this range. - if (c < ' ' || c > '~') { - return false; - } - } - } - } - return true; - } - - void PrintAltName(const BIOPointer& out, const char* name, size_t length, AltNameOption option = AltNameOption::NONE, - const char* safe_prefix = nullptr) { - if (IsSafeAltName(name, length, option)) { - // For backward-compatibility, append "safe" names without any - // modifications. - if (safe_prefix != nullptr) { - BIO_printf(out.get(), "%s:", safe_prefix); - } - BIO_write(out.get(), name, length); - } else { - // If a name is not "safe", we cannot embed it without special - // encoding. This does not usually happen, but we don't want to hide - // it from the user either. We use JSON compatible escaping here. - BIO_write(out.get(), "\"", 1); - if (safe_prefix != nullptr) { - BIO_printf(out.get(), "%s:", safe_prefix); - } - for (size_t j = 0; j < length; j++) { - char c = static_cast<char>(name[j]); - if (c == '\\') { - BIO_write(out.get(), "\\\\", 2); - } else if (c == '"') { - BIO_write(out.get(), "\\\"", 2); - } else if ((c >= ' ' && c != ',' && c <= '~') || (option == AltNameOption::UTF8 && (c & 0x80))) { - // Note that the above condition explicitly excludes commas, which means - // that those are encoded as Unicode escape sequences in the "else" - // block. That is not strictly necessary, and Node.js itself would parse - // it correctly either way. We only do this to account for third-party - // code that might be splitting the string at commas (as Node.js itself - // used to do). - BIO_write(out.get(), &c, 1); - } else { - // Control character or non-ASCII character. We treat everything as - // Latin-1, which corresponds to the first 255 Unicode code points. - const char hex[] = "0123456789abcdef"; - char u[] = {'\\', 'u', '0', '0', hex[(c & 0xf0) >> 4], hex[c & 0x0f]}; - BIO_write(out.get(), u, sizeof(u)); - } - } - BIO_write(out.get(), "\"", 1); - } - } - - // This function emulates the behavior of i2v_GENERAL_NAME in a safer and less - // ambiguous way. "othername:" entries use the GENERAL_NAME_print format. - bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) { - if (gen->type == GEN_DNS) { - ASN1_IA5STRING* name = gen->d.dNSName; - BIO_write(out.get(), "DNS:", 4); - // Note that the preferred name syntax (see RFCs 5280 and 1034) with - // wildcards is a subset of what we consider "safe", so spec-compliant DNS - // names will never need to be escaped. - PrintAltName(out, reinterpret_cast<const char*>(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); - } else if (gen->type == GEN_EMAIL) { - ASN1_IA5STRING* name = gen->d.rfc822Name; - BIO_write(out.get(), "email:", 6); - PrintAltName(out, reinterpret_cast<const char*>(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); - } else if (gen->type == GEN_URI) { - ASN1_IA5STRING* name = gen->d.uniformResourceIdentifier; - BIO_write(out.get(), "URI:", 4); - // The set of "safe" names was designed to include just about any URI, - // with a few exceptions, most notably URIs that contains commas (see - // RFC 2396). In other words, most legitimate URIs will not require - // escaping. - PrintAltName(out, reinterpret_cast<const char*>(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name)); - } else if (gen->type == GEN_DIRNAME) { - // Earlier versions of Node.js used X509_NAME_oneline to print the X509_NAME - // object. The format was non standard and should be avoided. The use of - // X509_NAME_oneline is discouraged by OpenSSL but was required for backward - // compatibility. Conveniently, X509_NAME_oneline produced ASCII and the - // output was unlikely to contains commas or other characters that would - // require escaping. However, it SHOULD NOT produce ASCII output since an - // RFC5280 AttributeValue may be a UTF8String. - // Newer versions of Node.js have since switched to X509_NAME_print_ex to - // produce a better format at the cost of backward compatibility. The new - // format may contain Unicode characters and it is likely to contain commas, - // which require escaping. Fortunately, the recently safeguarded function - // PrintAltName handles all of that safely. - BIO_printf(out.get(), "DirName:"); - BIOPointer tmp(BIO_new(BIO_s_mem())); - NCRYPTO_ASSERT_TRUE(tmp); - if (X509_NAME_print_ex(tmp.get(), gen->d.dirn, 0, kX509NameFlagsRFC2253WithinUtf8JSON) < 0) { - return false; - } - char* oline = nullptr; - long n_bytes = BIO_get_mem_data(tmp.get(), &oline); // NOLINT(runtime/int) - NCRYPTO_ASSERT_TRUE(n_bytes >= 0); - PrintAltName(out, oline, static_cast<size_t>(n_bytes), ncrypto::AltNameOption::UTF8, nullptr); - } else if (gen->type == GEN_IPADD) { - BIO_printf(out.get(), "IP Address:"); - const ASN1_OCTET_STRING* ip = gen->d.ip; - const unsigned char* b = ASN1_STRING_get0_data(ip); - int ip_len = ASN1_STRING_length(ip); - if (ip_len == 4) { - BIO_printf(out.get(), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]); - } else if (ip_len == 16) { - for (unsigned int j = 0; j < 8; j++) { - uint16_t pair = (b[2 * j] << 8) | b[2 * j + 1]; - BIO_printf(out.get(), (j == 0) ? "%X" : ":%X", pair); - } - } else { -#if OPENSSL_VERSION_MAJOR >= 3 - BIO_printf(out.get(), "<invalid length=%d>", ip_len); -#else - BIO_printf(out.get(), "<invalid>"); -#endif - } - } else if (gen->type == GEN_RID) { - // Unlike OpenSSL's default implementation, never print the OID as text and - // instead always print its numeric representation. - char oline[256]; - OBJ_obj2txt(oline, sizeof(oline), gen->d.rid, true); - BIO_printf(out.get(), "Registered ID:%s", oline); - } else if (gen->type == GEN_OTHERNAME) { - // The format that is used here is based on OpenSSL's implementation of - // GENERAL_NAME_print (as of OpenSSL 3.0.1). Earlier versions of Node.js - // instead produced the same format as i2v_GENERAL_NAME, which was somewhat - // awkward, especially when passed to translatePeerCertificate. - bool unicode = true; - const char* prefix = nullptr; - // OpenSSL 1.1.1 does not support othername in GENERAL_NAME_print and may - // not define these NIDs. -#if OPENSSL_VERSION_MAJOR >= 3 - int nid = OBJ_obj2nid(gen->d.otherName->type_id); - switch (nid) { - case NID_id_on_SmtpUTF8Mailbox: - prefix = "SmtpUTF8Mailbox"; - break; - case NID_XmppAddr: - prefix = "XmppAddr"; - break; - case NID_SRVName: - prefix = "SRVName"; - unicode = false; - break; - case NID_ms_upn: - prefix = "UPN"; - break; - case NID_NAIRealm: - prefix = "NAIRealm"; - break; - } -#endif // OPENSSL_VERSION_MAJOR >= 3 - int val_type = gen->d.otherName->value->type; - if (prefix == nullptr || (unicode && val_type != V_ASN1_UTF8STRING) || (!unicode && val_type != V_ASN1_IA5STRING)) { - BIO_printf(out.get(), "othername:<unsupported>"); - } else { - BIO_printf(out.get(), "othername:"); - if (unicode) { - auto name = gen->d.otherName->value->value.utf8string; - PrintAltName(out, reinterpret_cast<const char*>(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name), AltNameOption::UTF8, - prefix); - } else { - auto name = gen->d.otherName->value->value.ia5string; - PrintAltName(out, reinterpret_cast<const char*>(ASN1_STRING_get0_data(name)), ASN1_STRING_length(name), AltNameOption::NONE, - prefix); - } - } - } else if (gen->type == GEN_X400) { - // TODO(tniessen): this is what OpenSSL does, implement properly instead - BIO_printf(out.get(), "X400Name:<unsupported>"); - } else if (gen->type == GEN_EDIPARTY) { - // TODO(tniessen): this is what OpenSSL does, implement properly instead - BIO_printf(out.get(), "EdiPartyName:<unsupported>"); - } else { - // This is safe because X509V3_EXT_d2i would have returned nullptr in this - // case already. - unreachable(); - } - - return true; - } -} // namespace - -bool SafeX509SubjectAltNamePrint(const BIOPointer& out, const X509_EXTENSION* ext) { - // const_cast needed for OpenSSL < 4.0 which lacks const-correctness - auto* mext = const_cast<X509_EXTENSION*>(ext); - auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(mext)); - if (ret != NID_subject_alt_name) - return false; - - GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(mext)); - if (names == nullptr) - return false; - - bool ok = true; - - for (OPENSSL_SIZE_T i = 0; i < sk_GENERAL_NAME_num(names); i++) { - GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i); - - if (i != 0) - BIO_write(out.get(), ", ", 2); - - if (!(ok = ncrypto::PrintGeneralName(out, gen))) { - break; - } - } - sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); - - return ok; -} - -bool SafeX509InfoAccessPrint(const BIOPointer& out, const X509_EXTENSION* ext) { - // const_cast needed for OpenSSL < 4.0 which lacks const-correctness - auto* mext = const_cast<X509_EXTENSION*>(ext); - auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(mext)); - if (ret != NID_info_access) - return false; - - AUTHORITY_INFO_ACCESS* descs = static_cast<AUTHORITY_INFO_ACCESS*>(X509V3_EXT_d2i(mext)); - if (descs == nullptr) - return false; - - bool ok = true; - - for (OPENSSL_SIZE_T i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) { - ACCESS_DESCRIPTION* desc = sk_ACCESS_DESCRIPTION_value(descs, i); - - if (i != 0) - BIO_write(out.get(), "\n", 1); - - char objtmp[80]; - i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method); - BIO_printf(out.get(), "%s - ", objtmp); - if (!(ok = ncrypto::PrintGeneralName(out, desc->location))) { - break; - } - } - sk_ACCESS_DESCRIPTION_pop_free(descs, ACCESS_DESCRIPTION_free); - -#if OPENSSL_VERSION_MAJOR < 3 - BIO_write(out.get(), "\n", 1); -#endif - - return ok; -} - -// ============================================================================ -// X509Pointer - -X509Pointer::X509Pointer(X509* x509) : cert_(x509) {} - -X509Pointer::X509Pointer(X509Pointer&& other) noexcept : cert_(other.release()) {} - -X509Pointer& X509Pointer::operator=(X509Pointer&& other) noexcept { - if (this == &other) - return *this; - this->~X509Pointer(); - return *new (this) X509Pointer(std::move(other)); -} - -X509Pointer::~X509Pointer() { - reset(); -} - -void X509Pointer::reset(X509* x509) { - cert_.reset(x509); -} - -X509* X509Pointer::release() { - return cert_.release(); -} - -X509View X509Pointer::view() const { - return X509View(cert_.get()); -} - -BIOPointer X509View::toPEM() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - if (PEM_write_bio_X509(bio.get(), const_cast<X509*>(cert_)) <= 0) - return {}; - return bio; -} - -BIOPointer X509View::toDER() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - if (i2d_X509_bio(bio.get(), const_cast<X509*>(cert_)) <= 0) - return {}; - return bio; -} - -BIOPointer X509View::getSubject() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - if (X509_NAME_print_ex(bio.get(), X509_get_subject_name(cert_), 0, kX509NameFlagsMultiline) <= 0) { - return {}; - } - return bio; -} - -BIOPointer X509View::getSubjectAltName() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - int index = X509_get_ext_by_NID(cert_, NID_subject_alt_name, -1); - if (index < 0 || !SafeX509SubjectAltNamePrint(bio, X509_get_ext(cert_, index))) { - return {}; - } - return bio; -} - -BIOPointer X509View::getIssuer() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - if (X509_NAME_print_ex(bio.get(), X509_get_issuer_name(cert_), 0, kX509NameFlagsMultiline) <= 0) { - return {}; - } - return bio; -} - -BIOPointer X509View::getInfoAccess() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - int index = X509_get_ext_by_NID(cert_, NID_info_access, -1); - if (index < 0) - return {}; - if (!SafeX509InfoAccessPrint(bio, X509_get_ext(cert_, index))) { - return {}; - } - return bio; -} - -BIOPointer X509View::getValidFrom() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert_)); - return bio; -} - -BIOPointer X509View::getValidTo() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return {}; - ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert_)); - return bio; -} - -std::optional<std::string_view> X509View::getSignatureAlgorithm() const { - if (cert_ == nullptr) - return std::nullopt; - int nid = X509_get_signature_nid(cert_); - if (nid == NID_undef) - return std::nullopt; - const char* ln = OBJ_nid2ln(nid); - if (ln == nullptr) - return std::nullopt; - return std::string_view(ln); -} - -std::optional<std::string> X509View::getSignatureAlgorithmOID() const { - if (cert_ == nullptr) - return std::nullopt; - const X509_ALGOR* alg = nullptr; - X509_get0_signature(nullptr, &alg, cert_); - if (alg == nullptr) - return std::nullopt; - const ASN1_OBJECT* obj = nullptr; - X509_ALGOR_get0(&obj, nullptr, nullptr, alg); - if (obj == nullptr) - return std::nullopt; - std::array<char, 128> buf{}; - int len = OBJ_obj2txt(buf.data(), buf.size(), obj, 1); - if (len < 0 || static_cast<size_t>(len) >= buf.size()) - return std::nullopt; - return std::string(buf.data(), static_cast<size_t>(len)); -} - -int64_t X509View::getValidToTime() const { -#ifdef OPENSSL_IS_BORINGSSL -#ifndef NCRYPTO_NO_ASN1_TIME - // Boringssl does not implement ASN1_TIME_to_tm in a public way, - // and only recently added ASN1_TIME_to_posix. Some boringssl - // users on older version may still need to patch around this - // or use a different implementation. - int64_t tp; - ASN1_TIME_to_posix(X509_get0_notAfter(cert_), &tp); - return tp; -#else - // Older versions of Boringssl do not implement the ASN1_TIME_to_* - // version functions. For now, neither shall we. - return 0LL; -#endif // NCRYPTO_NO_ASN1_TIME -#else // OPENSSL_IS_BORINGSSL - struct tm tp; - ASN1_TIME_to_tm(X509_get0_notAfter(cert_), &tp); - return PortableTimeGM(&tp); -#endif -} - -int64_t X509View::getValidFromTime() const { -#ifdef OPENSSL_IS_BORINGSSL -#ifndef NCRYPTO_NO_ASN1_TIME - int64_t tp; - ASN1_TIME_to_posix(X509_get0_notBefore(cert_), &tp); - return tp; -#else - // Older versions of Boringssl do not implement the ASN1_TIME_to_* - // version functions. For now, neither shall we. - return 0LL; -#endif // NCRYPTO_NO_ASN1_TIME -#else - struct tm tp; - ASN1_TIME_to_tm(X509_get0_notBefore(cert_), &tp); - return PortableTimeGM(&tp); -#endif -} - -DataPointer X509View::getSerialNumber() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - if (ASN1_INTEGER* serial_number = X509_get_serialNumber(const_cast<X509*>(cert_))) { - if (auto bn = BignumPointer(ASN1_INTEGER_to_BN(serial_number, nullptr))) { - return bn.toHex(); - } - } - return {}; -} - -Result<EVPKeyPointer, int> X509View::getPublicKey() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return Result<EVPKeyPointer, int>(EVPKeyPointer{}); - auto pkey = EVPKeyPointer(X509_get_pubkey(const_cast<X509*>(cert_))); - if (!pkey) - return Result<EVPKeyPointer, int>(ERR_get_error()); - return pkey; -} - -StackOfASN1 X509View::getKeyUsage() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return {}; - return StackOfASN1(static_cast<STACK_OF(ASN1_OBJECT)*>(X509_get_ext_d2i(cert_, NID_ext_key_usage, nullptr, nullptr))); -} - -bool X509View::isCA() const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return false; - return X509_check_ca(const_cast<X509*>(cert_)) == 1; -} - -bool X509View::isIssuedBy(const X509View& issuer) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr || issuer.cert_ == nullptr) - return false; - return X509_check_issued(const_cast<X509*>(issuer.cert_), const_cast<X509*>(cert_)) == X509_V_OK; -} - -bool X509View::checkPrivateKey(const EVPKeyPointer& pkey) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr || pkey == nullptr) - return false; - return X509_check_private_key(const_cast<X509*>(cert_), pkey.get()) == 1; -} - -bool X509View::checkPublicKey(const EVPKeyPointer& pkey) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr || pkey == nullptr) - return false; - return X509_verify(const_cast<X509*>(cert_), pkey.get()) == 1; -} - -X509View::CheckMatch X509View::checkHost(const std::string_view host, int flags, DataPointer* peerName) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return CheckMatch::NO_MATCH; - char* peername; - switch (X509_check_host(const_cast<X509*>(cert_), host.data(), host.size(), flags, &peername)) { - case 0: - return CheckMatch::NO_MATCH; - case 1: { - if (peername != nullptr) { - DataPointer name(peername, strlen(peername)); - if (peerName != nullptr) - *peerName = std::move(name); - } - return CheckMatch::MATCH; - } - case -2: - return CheckMatch::INVALID_NAME; - default: - return CheckMatch::OPERATION_FAILED; - } -} - -X509View::CheckMatch X509View::checkEmail(const std::string_view email, int flags) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return CheckMatch::NO_MATCH; - switch (X509_check_email(const_cast<X509*>(cert_), email.data(), email.size(), flags)) { - case 0: - return CheckMatch::NO_MATCH; - case 1: - return CheckMatch::MATCH; - case -2: - return CheckMatch::INVALID_NAME; - default: - return CheckMatch::OPERATION_FAILED; - } -} - -X509View::CheckMatch X509View::checkIp(const std::string_view ip, int flags) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) - return CheckMatch::NO_MATCH; - switch (X509_check_ip_asc(const_cast<X509*>(cert_), ip.data(), flags)) { - case 0: - return CheckMatch::NO_MATCH; - case 1: - return CheckMatch::MATCH; - case -2: - return CheckMatch::INVALID_NAME; - default: - return CheckMatch::OPERATION_FAILED; - } -} - -std::optional<std::string> X509View::getFingerprint(const Digest& method) const { - unsigned int md_size; - unsigned char md[EVP_MAX_MD_SIZE]; - static constexpr char hex[] = "0123456789ABCDEF"; - - if (X509_digest(get(), method, md, &md_size)) { - if (md_size == 0) - return std::nullopt; - std::string fingerprint((md_size * 3) - 1, 0); - for (unsigned int i = 0; i < md_size; i++) { - auto idx = 3 * i; - fingerprint[idx] = hex[(md[i] & 0xf0) >> 4]; - fingerprint[idx + 1] = hex[(md[i] & 0x0f)]; - if (i == md_size - 1) - break; - fingerprint[idx + 2] = ':'; - } - - return fingerprint; - } - - return std::nullopt; -} - -Result<X509Pointer, int> X509Pointer::Parse(Buffer<const unsigned char> buffer) { - ClearErrorOnReturn clearErrorOnReturn; - BIOPointer bio(BIO_new_mem_buf(buffer.data, buffer.len)); - if (!bio) - return Result<X509Pointer, int>(ERR_get_error()); - - X509Pointer pem(PEM_read_bio_X509_AUX(bio.get(), nullptr, NoPasswordCallback, nullptr)); - if (pem) - return Result<X509Pointer, int>(std::move(pem)); - if (!bio.resetBio()) - return Result<X509Pointer, int>(ERR_get_error()); - - X509Pointer der(d2i_X509_bio(bio.get(), nullptr)); - if (der) - return Result<X509Pointer, int>(std::move(der)); - - return Result<X509Pointer, int>(ERR_get_error()); -} - -bool X509View::enumUsages(UsageCallback callback) const { - if (cert_ == nullptr) - return false; - StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(X509_get_ext_d2i(cert_, NID_ext_key_usage, nullptr, nullptr))); - if (!eku) - return false; - const int count = sk_ASN1_OBJECT_num(eku.get()); - char buf[256]{}; - - for (int i = 0; i < count; i++) { - if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) { - callback(buf); - } - } - return true; -} - -// When adding or removing errors below, please also update the list in the API -// documentation. See the "OpenSSL Error Codes" section of doc/api/errors.md -// Also *please* update the respective section in doc/api/tls.md as well -const char* X509Pointer::ErrorCode(int32_t err) { // NOLINT(runtime/int) -#define CASE(CODE) \ - case X509_V_ERR_##CODE: \ - return #CODE; - switch (err) { - CASE(UNABLE_TO_GET_ISSUER_CERT) - CASE(UNABLE_TO_GET_CRL) - CASE(UNABLE_TO_DECRYPT_CERT_SIGNATURE) - CASE(UNABLE_TO_DECRYPT_CRL_SIGNATURE) - CASE(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY) - CASE(CERT_SIGNATURE_FAILURE) - CASE(CRL_SIGNATURE_FAILURE) - CASE(CERT_NOT_YET_VALID) - CASE(CERT_HAS_EXPIRED) - CASE(CRL_NOT_YET_VALID) - CASE(CRL_HAS_EXPIRED) - CASE(ERROR_IN_CERT_NOT_BEFORE_FIELD) - CASE(ERROR_IN_CERT_NOT_AFTER_FIELD) - CASE(ERROR_IN_CRL_LAST_UPDATE_FIELD) - CASE(ERROR_IN_CRL_NEXT_UPDATE_FIELD) - CASE(OUT_OF_MEM) - CASE(DEPTH_ZERO_SELF_SIGNED_CERT) - CASE(SELF_SIGNED_CERT_IN_CHAIN) - CASE(UNABLE_TO_GET_ISSUER_CERT_LOCALLY) - CASE(UNABLE_TO_VERIFY_LEAF_SIGNATURE) - CASE(CERT_CHAIN_TOO_LONG) - CASE(CERT_REVOKED) - CASE(INVALID_CA) - CASE(PATH_LENGTH_EXCEEDED) - CASE(INVALID_PURPOSE) - CASE(CERT_UNTRUSTED) - CASE(CERT_REJECTED) - CASE(HOSTNAME_MISMATCH) - } -#undef CASE - return "UNSPECIFIED"; -} - -std::optional<const char*> X509Pointer::ErrorReason(int32_t err) { - if (err == X509_V_OK) - return std::nullopt; - return X509_verify_cert_error_string(err); -} - -// ============================================================================ -// BIOPointer - -BIOPointer::BIOPointer(BIO* bio) : bio_(bio) {} - -BIOPointer::BIOPointer(BIOPointer&& other) noexcept : bio_(other.release()) {} - -BIOPointer& BIOPointer::operator=(BIOPointer&& other) noexcept { - if (this == &other) - return *this; - this->~BIOPointer(); - return *new (this) BIOPointer(std::move(other)); -} - -BIOPointer::~BIOPointer() { - reset(); -} - -void BIOPointer::reset(BIO* bio) { - bio_.reset(bio); -} - -BIO* BIOPointer::release() { - return bio_.release(); -} - -bool BIOPointer::resetBio() const { - if (!bio_) - return 0; - return BIO_reset(bio_.get()) == 1; -} - -BIOPointer BIOPointer::NewMem() { - return BIOPointer(BIO_new(BIO_s_mem())); -} - -BIOPointer BIOPointer::NewSecMem() { -#ifdef OPENSSL_IS_BORINGSSL - // Boringssl does not implement the BIO_s_secmem API. - return BIOPointer(BIO_new(BIO_s_mem())); -#else - return BIOPointer(BIO_new(BIO_s_secmem())); -#endif -} - -BIOPointer BIOPointer::New(const BIO_METHOD* method) { - if (method == nullptr) - return {}; - return BIOPointer(BIO_new(method)); -} - -BIOPointer BIOPointer::New(const void* data, size_t len) { - return BIOPointer(BIO_new_mem_buf(data, len)); -} - -BIOPointer BIOPointer::NewFile(const char* filename, const char* mode) { - return BIOPointer(BIO_new_file(filename, mode)); -} - -BIOPointer BIOPointer::NewFp(FILE* fd, int close_flag) { - return BIOPointer(BIO_new_fp(fd, close_flag)); -} - -BIOPointer BIOPointer::New(const BIGNUM* bn) { - auto res = NewMem(); - if (!res || !BN_print(res.get(), bn)) - return {}; - return res; -} - -int BIOPointer::Write(BIOPointer* bio, std::string_view message) { - if (bio == nullptr || !*bio) - return 0; - return BIO_write(bio->get(), message.data(), message.size()); -} - -// ============================================================================ -// KDF - -const EVP_MD* getDigestByName(const char* name) { - // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1 - // exposed through the public API. - if (strcmp(name, "dss1") == 0 || strcmp(name, "DSS1") == 0) [[unlikely]] { - return EVP_sha1(); - } - return EVP_get_digestbyname(name); -} - -const EVP_CIPHER* getCipherByName(const char* name) { - return EVP_get_cipherbyname(name); -} - -bool checkHkdfLength(const Digest& md, size_t length) { - // HKDF-Expand computes up to 255 HMAC blocks, each having as many bits as - // the output of the hash function. 255 is a hard limit because HKDF appends - // an 8-bit counter to each HMAC'd message, starting at 1. - static constexpr size_t kMaxDigestMultiplier = 255; - size_t max_length = md.size() * kMaxDigestMultiplier; - if (length > max_length) - return false; - return true; -} - -bool hkdfInfo(const Digest& md, const Buffer<const unsigned char>& key, const Buffer<const unsigned char>& info, - const Buffer<const unsigned char>& salt, size_t length, Buffer<unsigned char>* out) { - ClearErrorOnReturn clearErrorOnReturn; - - if (!checkHkdfLength(md, length) || info.len > INT_MAX || salt.len > INT_MAX) { - return false; - } - - std::string_view actual_salt; - static const char default_salt[EVP_MAX_MD_SIZE] = {0}; - if (salt.len > 0) { - actual_salt = {reinterpret_cast<const char*>(salt.data), salt.len}; - } else { - actual_salt = {default_salt, static_cast<unsigned>(md.size())}; - } - -#ifdef OPENSSL_IS_BORINGSSL - if (out == nullptr || out->len != length) - return false; - return HKDF(out->data, length, md, key.data, key.len, reinterpret_cast<const unsigned char*>(actual_salt.data()), actual_salt.size(), - info.data, info.len) == 1; -#else - auto ctx = EVPKeyCtxPointer::NewFromID(EVP_PKEY_HKDF); - // OpenSSL < 3.0.0 accepted only a void* as the argument of - // EVP_PKEY_CTX_set_hkdf_md. - const EVP_MD* md_ptr = md; - if (!ctx || !EVP_PKEY_derive_init(ctx.get()) || !EVP_PKEY_CTX_set_hkdf_md(ctx.get(), md_ptr) || - !EVP_PKEY_CTX_add1_hkdf_info(ctx.get(), info.data, info.len)) { - return false; - } - - // We do not use EVP_PKEY_HKDF_MODE_EXTRACT_AND_EXPAND because and instead - // implement the extraction step ourselves because EVP_PKEY_derive does not - // handle zero-length keys, which are required for Web Crypto. - // TODO(jasnell): Once OpenSSL 1.1.1 support is dropped completely, and once - // BoringSSL is confirmed to support it, we can hopefully drop this and use - // EVP_KDF directly which does support zero length keys. - unsigned char pseudorandom_key[EVP_MAX_MD_SIZE]; - unsigned pseudorandom_key_len = sizeof(pseudorandom_key); - - if (HMAC(md, actual_salt.data(), actual_salt.size(), key.data, key.len, pseudorandom_key, &pseudorandom_key_len) == nullptr) { - return false; - } - if (!EVP_PKEY_CTX_hkdf_mode(ctx.get(), EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) || - !EVP_PKEY_CTX_set1_hkdf_key(ctx.get(), pseudorandom_key, pseudorandom_key_len)) { - return false; - } - - if (out == nullptr || out->len != length) - return false; - - return EVP_PKEY_derive(ctx.get(), out->data, &length) > 0; -#endif -} - -DataPointer hkdf(const Digest& md, const Buffer<const unsigned char>& key, const Buffer<const unsigned char>& info, - const Buffer<const unsigned char>& salt, size_t length) { - auto buf = DataPointer::Alloc(length); - if (!buf) - return {}; - Buffer<unsigned char> out{ - .data = static_cast<unsigned char*>(buf.get()), - .len = length, - }; - if (hkdfInfo(md, key, info, salt, length, &out)) { - return buf; - } - return {}; -} - -bool checkScryptParams(uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem) { - return EVP_PBE_scrypt(nullptr, 0, nullptr, 0, N, r, p, maxmem, nullptr, 0) == 1; -} - -bool scryptInto(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint64_t N, uint64_t r, uint64_t p, - uint64_t maxmem, size_t length, Buffer<unsigned char>* out) { - ClearErrorOnReturn clearErrorOnReturn; - - if (pass.len > INT_MAX || salt.len > INT_MAX || out == nullptr) { - return false; - } - - return EVP_PBE_scrypt(pass.data, pass.len, salt.data, salt.len, N, r, p, maxmem, out->data, length) == 1; -} - -DataPointer scrypt(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint64_t N, uint64_t r, uint64_t p, - uint64_t maxmem, size_t length) { - ClearErrorOnReturn clearErrorOnReturn; - - if (pass.len > INT_MAX || salt.len > INT_MAX) { - return {}; - } - - auto dp = DataPointer::Alloc(length); - if (dp && EVP_PBE_scrypt(pass.data, pass.len, salt.data, salt.len, N, r, p, maxmem, reinterpret_cast<unsigned char*>(dp.get()), length)) { - return dp; - } - - return {}; -} - -bool pbkdf2Into(const Digest& md, const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t iterations, - size_t length, Buffer<unsigned char>* out) { - ClearErrorOnReturn clearErrorOnReturn; - - if (pass.len > INT_MAX || salt.len > INT_MAX || length > INT_MAX || out == nullptr) { - return false; - } - - const EVP_MD* md_ptr = md; - return PKCS5_PBKDF2_HMAC(pass.data, pass.len, salt.data, salt.len, iterations, md_ptr, length, out->data) == 1; -} - -DataPointer pbkdf2(const Digest& md, const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t iterations, - size_t length) { - ClearErrorOnReturn clearErrorOnReturn; - - if (pass.len > INT_MAX || salt.len > INT_MAX || length > INT_MAX) { - return {}; - } - - auto dp = DataPointer::Alloc(length); - const EVP_MD* md_ptr = md; - if (dp && - PKCS5_PBKDF2_HMAC(pass.data, pass.len, salt.data, salt.len, iterations, md_ptr, length, reinterpret_cast<unsigned char*>(dp.get()))) { - return dp; - } - - return {}; -} - -#if OPENSSL_VERSION_NUMBER >= 0x30200000L -#ifndef OPENSSL_NO_ARGON2 -DataPointer argon2(const Buffer<const char>& pass, const Buffer<const unsigned char>& salt, uint32_t lanes, size_t length, uint32_t memcost, - uint32_t iter, uint32_t version, const Buffer<const unsigned char>& secret, const Buffer<const unsigned char>& ad, - Argon2Type type) { - ClearErrorOnReturn clearErrorOnReturn; - (void)version; - - std::string_view algorithm; - switch (type) { - case Argon2Type::ARGON2I: - algorithm = "ARGON2I"; - break; - case Argon2Type::ARGON2D: - algorithm = "ARGON2D"; - break; - case Argon2Type::ARGON2ID: - algorithm = "ARGON2ID"; - break; - default: - // Invalid Argon2 type - return {}; - } - - // creates a new library context to avoid locking when running concurrently - auto ctx = DeleteFnPtr<OSSL_LIB_CTX, OSSL_LIB_CTX_free>{OSSL_LIB_CTX_new()}; - if (!ctx) { - return {}; - } - - // required if threads > 1 - if (lanes > 1 && OSSL_set_max_threads(ctx.get(), lanes) != 1) { - return {}; - } - - auto kdf = DeleteFnPtr<EVP_KDF, EVP_KDF_free>{EVP_KDF_fetch(ctx.get(), algorithm.data(), nullptr)}; - if (!kdf) { - return {}; - } - - auto kctx = DeleteFnPtr<EVP_KDF_CTX, EVP_KDF_CTX_free>{EVP_KDF_CTX_new(kdf.get())}; - if (!kctx) { - return {}; - } - - std::vector<OSSL_PARAM> params; - params.reserve(9); - - params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, const_cast<char*>(pass.len > 0 ? pass.data : ""), pass.len)); - params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, const_cast<unsigned char*>(salt.data), salt.len)); - params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_THREADS, &lanes)); - params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES, &lanes)); - params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memcost)); - params.push_back(OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ITER, &iter)); - - if (ad.len != 0) { - params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_ARGON2_AD, const_cast<unsigned char*>(ad.data), ad.len)); - } - - if (secret.len != 0) { - params.push_back(OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, const_cast<unsigned char*>(secret.data), secret.len)); - } - - params.push_back(OSSL_PARAM_construct_end()); - - auto dp = DataPointer::Alloc(length); - if (dp && EVP_KDF_derive(kctx.get(), reinterpret_cast<unsigned char*>(dp.get()), length, params.data()) == 1) { - return dp; - } - - return {}; -} -#endif -#endif - -// ============================================================================ - -EVPKeyPointer::PrivateKeyEncodingConfig::PrivateKeyEncodingConfig(const PrivateKeyEncodingConfig& other) - : PrivateKeyEncodingConfig(other.output_key_object, other.format, other.type) { - cipher = other.cipher; - if (other.passphrase.has_value()) { - auto& otherPassphrase = other.passphrase.value(); - auto newPassphrase = DataPointer::Alloc(otherPassphrase.size()); - memcpy(newPassphrase.get(), otherPassphrase.get(), otherPassphrase.size()); - passphrase = std::move(newPassphrase); - } -} - -EVPKeyPointer::AsymmetricKeyEncodingConfig::AsymmetricKeyEncodingConfig(bool output_key_object, PKFormatType format, PKEncodingType type) - : output_key_object(output_key_object), format(format), type(type) {} - -EVPKeyPointer::PrivateKeyEncodingConfig& EVPKeyPointer::PrivateKeyEncodingConfig::operator=(const PrivateKeyEncodingConfig& other) { - if (this == &other) - return *this; - this->~PrivateKeyEncodingConfig(); - return *new (this) PrivateKeyEncodingConfig(other); -} - -EVPKeyPointer EVPKeyPointer::New() { - return EVPKeyPointer(EVP_PKEY_new()); -} - -EVPKeyPointer EVPKeyPointer::NewRawPublic(int id, const Buffer<const unsigned char>& data) { - if (id == 0) - return {}; - return EVPKeyPointer(EVP_PKEY_new_raw_public_key(id, nullptr, data.data, data.len)); -} - -EVPKeyPointer EVPKeyPointer::NewRawPrivate(int id, const Buffer<const unsigned char>& data) { - if (id == 0) - return {}; - return EVPKeyPointer(EVP_PKEY_new_raw_private_key(id, nullptr, data.data, data.len)); -} - -#if OPENSSL_WITH_PQC -EVPKeyPointer EVPKeyPointer::NewRawSeed(int id, const Buffer<const unsigned char>& data) { - if (id == 0) - return {}; - - OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_ML_DSA_SEED, const_cast<unsigned char*>(data.data), data.len), - OSSL_PARAM_END}; - - EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(id, nullptr); - if (ctx == nullptr) - return {}; - - EVP_PKEY* pkey = nullptr; - if (ctx == nullptr || EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) { - EVP_PKEY_CTX_free(ctx); - return {}; - } - - return EVPKeyPointer(pkey); -} -#endif - -EVPKeyPointer::EVPKeyPointer(EVP_PKEY* pkey) : pkey_(pkey) {} - -EVPKeyPointer::EVPKeyPointer(EVPKeyPointer&& other) noexcept : pkey_(other.release()) {} - -EVPKeyPointer& EVPKeyPointer::operator=(EVPKeyPointer&& other) noexcept { - if (this == &other) - return *this; - this->~EVPKeyPointer(); - return *new (this) EVPKeyPointer(std::move(other)); -} - -EVPKeyPointer::~EVPKeyPointer() { - reset(); -} - -void EVPKeyPointer::reset(EVP_PKEY* pkey) { - pkey_.reset(pkey); -} - -EVP_PKEY* EVPKeyPointer::release() { - return pkey_.release(); -} - -int EVPKeyPointer::id(const EVP_PKEY* key) { - if (key == nullptr) - return 0; - int type = EVP_PKEY_id(key); -#if OPENSSL_WITH_PQC - // EVP_PKEY_id returns -1 when EVP_PKEY_* is only implemented in a provider - // which is the case for all post-quantum NIST algorithms - // one suggested way would be to use a chain of `EVP_PKEY_is_a` - // https://github.com/openssl/openssl/issues/27738#issuecomment-3013215870 - // or, this way there are less calls to the OpenSSL provider, just - // getting the name once - if (type == -1) { - const char* type_name = EVP_PKEY_get0_type_name(key); - if (type_name == nullptr) - return -1; - - for (const auto& mapping : pqc_mappings) { - if (strcmp(type_name, mapping.name) == 0) { - return mapping.nid; - } - } - } -#endif - return type; -} - -int EVPKeyPointer::base_id(const EVP_PKEY* key) { - if (key == nullptr) - return 0; - return EVP_PKEY_base_id(key); -} - -int EVPKeyPointer::id() const { - return id(get()); -} - -int EVPKeyPointer::base_id() const { - return base_id(get()); -} - -int EVPKeyPointer::bits() const { - if (get() == nullptr) - return 0; - return EVP_PKEY_bits(get()); -} - -size_t EVPKeyPointer::size() const { - if (get() == nullptr) - return 0; - return EVP_PKEY_size(get()); -} - -EVPKeyCtxPointer EVPKeyPointer::newCtx() const { - if (!pkey_) - return {}; - return EVPKeyCtxPointer::New(*this); -} - -size_t EVPKeyPointer::rawPublicKeySize() const { - if (!pkey_) - return 0; - size_t len = 0; - if (EVP_PKEY_get_raw_public_key(get(), nullptr, &len) == 1) - return len; - return 0; -} - -size_t EVPKeyPointer::rawPrivateKeySize() const { - if (!pkey_) - return 0; - size_t len = 0; - if (EVP_PKEY_get_raw_private_key(get(), nullptr, &len) == 1) - return len; - return 0; -} - -DataPointer EVPKeyPointer::rawPublicKey() const { - if (!pkey_) - return {}; - if (auto data = DataPointer::Alloc(rawPublicKeySize())) { - const Buffer<unsigned char> buf = data; - size_t len = data.size(); - if (EVP_PKEY_get_raw_public_key(get(), buf.data, &len) != 1) - return {}; - return data; - } - return {}; -} - -#if OPENSSL_WITH_PQC -DataPointer EVPKeyPointer::rawSeed() const { - if (!pkey_) - return {}; - - // Determine seed length and parameter name based on key type - size_t seed_len; - const char* param_name; - - switch (id()) { - case EVP_PKEY_ML_DSA_44: - case EVP_PKEY_ML_DSA_65: - case EVP_PKEY_ML_DSA_87: - seed_len = 32; // ML-DSA uses 32-byte seeds - param_name = OSSL_PKEY_PARAM_ML_DSA_SEED; - break; - case EVP_PKEY_ML_KEM_512: - case EVP_PKEY_ML_KEM_768: - case EVP_PKEY_ML_KEM_1024: - seed_len = 64; // ML-KEM uses 64-byte seeds - param_name = OSSL_PKEY_PARAM_ML_KEM_SEED; - break; - default: - unreachable(); - } - - if (auto data = DataPointer::Alloc(seed_len)) { - const Buffer<unsigned char> buf = data; - size_t len = data.size(); - - if (EVP_PKEY_get_octet_string_param(get(), param_name, buf.data, len, &seed_len) != 1) - return {}; - return data; - } - return {}; -} -#endif - -DataPointer EVPKeyPointer::rawPrivateKey() const { - if (!pkey_) - return {}; - if (auto data = DataPointer::Alloc(rawPrivateKeySize())) { - const Buffer<unsigned char> buf = data; - size_t len = data.size(); - if (EVP_PKEY_get_raw_private_key(get(), buf.data, &len) != 1) - return {}; - return data; - } - return {}; -} - -BIOPointer EVPKeyPointer::derPublicKey() const { - if (!pkey_) - return {}; - auto bio = BIOPointer::NewMem(); - if (!bio) - return {}; - if (!i2d_PUBKEY_bio(bio.get(), get())) - return {}; - return bio; -} - -namespace { - EVPKeyPointer::ParseKeyResult TryParsePublicKeyInner(const BIOPointer& bp, const char* name, auto&& parse) { - if (!bp.resetBio()) { - return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::FAILED); - } - unsigned char* der_data; - long der_len; // NOLINT(runtime/int) - - // This skips surrounding data and decodes PEM to DER. - { - MarkPopErrorOnReturn mark_pop_error_on_return; - if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name, bp.get(), nullptr, nullptr) != 1) - return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::NOT_RECOGNIZED); - } - DataPointer data(der_data, der_len); - - // OpenSSL might modify the pointer, so we need to make a copy before parsing. - const unsigned char* p = der_data; - EVPKeyPointer pkey(parse(&p, der_len)); - if (!pkey) - return EVPKeyPointer::ParseKeyResult(EVPKeyPointer::PKParseError::FAILED); - return EVPKeyPointer::ParseKeyResult(std::move(pkey)); - } - - constexpr bool IsASN1Sequence(const unsigned char* data, size_t size, size_t* data_offset, size_t* data_size) { - if (size < 2 || data[0] != 0x30) - return false; - - if (data[1] & 0x80) { - // Long form. - size_t n_bytes = data[1] & ~0x80; - if (n_bytes + 2 > size || n_bytes > sizeof(size_t)) - return false; - size_t length = 0; - for (size_t i = 0; i < n_bytes; i++) - length = (length << 8) | data[i + 2]; - *data_offset = 2 + n_bytes; - *data_size = std::min(size - 2 - n_bytes, length); - } else { - // Short form. - *data_offset = 2; - *data_size = std::min<size_t>(size - 2, data[1]); - } - - return true; - } - - constexpr bool IsEncryptedPrivateKeyInfo(const Buffer<const unsigned char>& buffer) { - // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE. - if (buffer.len == 0 || buffer.data == nullptr) - return false; - size_t offset, len; - if (!IsASN1Sequence(buffer.data, buffer.len, &offset, &len)) - return false; - - // A PrivateKeyInfo sequence always starts with an integer whereas an - // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier. - return len >= 1 && buffer.data[offset] != 2; - } - -} // namespace - -bool EVPKeyPointer::IsRSAPrivateKey(const Buffer<const unsigned char>& buffer) { - // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE. - size_t offset, len; - if (!IsASN1Sequence(buffer.data, buffer.len, &offset, &len)) - return false; - - // An RSAPrivateKey sequence always starts with a single-byte integer whose - // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus - // (which is the product of two primes and therefore at least 4), so we can - // decide the type of the structure based on the first three bytes of the - // sequence. - return len >= 3 && buffer.data[offset] == 2 && buffer.data[offset + 1] == 1 && !(buffer.data[offset + 2] & 0xfe); -} - -EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKeyPEM(const Buffer<const unsigned char>& buffer) { - auto bp = BIOPointer::New(buffer.data, buffer.len); - if (!bp) - return ParseKeyResult(PKParseError::FAILED); - - // Try parsing as SubjectPublicKeyInfo (SPKI) first. - if (auto ret = TryParsePublicKeyInner(bp, "PUBLIC KEY", [](const unsigned char** p, long l) { // NOLINT(runtime/int) - return d2i_PUBKEY(nullptr, p, l); - })) { - return ret; - } - - // Maybe it is PKCS#1. - if (auto ret = TryParsePublicKeyInner(bp, "RSA PUBLIC KEY", [](const unsigned char** p, long l) { // NOLINT(runtime/int) - return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l); - })) { - return ret; - } - - // X.509 fallback. - if (auto ret = TryParsePublicKeyInner(bp, "CERTIFICATE", [](const unsigned char** p, long l) { // NOLINT(runtime/int) - X509Pointer x509(d2i_X509(nullptr, p, l)); - return x509 ? X509_get_pubkey(x509.get()) : nullptr; - })) { - return ret; - }; - - return ParseKeyResult(PKParseError::NOT_RECOGNIZED); -} - -EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKey(const PublicKeyEncodingConfig& config, - const Buffer<const unsigned char>& buffer) { - if (config.format == PKFormatType::PEM) { - return TryParsePublicKeyPEM(buffer); - } - - if (config.format != PKFormatType::DER) { - return ParseKeyResult(PKParseError::FAILED); - } - - const unsigned char* start = buffer.data; - - EVP_PKEY* key = nullptr; - - if (config.type == PKEncodingType::PKCS1 && (key = d2i_PublicKey(EVP_PKEY_RSA, nullptr, &start, buffer.len))) { - return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); - } - - if (config.type == PKEncodingType::SPKI && (key = d2i_PUBKEY(nullptr, &start, buffer.len))) { - return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); - } - - return ParseKeyResult(PKParseError::FAILED); -} - -namespace { - Buffer<char> GetPassphrase(const EVPKeyPointer::PrivateKeyEncodingConfig& config) { - static char empty_passphrase; - Buffer<char> pass{ - .data = &empty_passphrase, - .len = 0, - }; - if (config.passphrase.has_value()) { - auto& passphrase = config.passphrase.value(); - // The pass.data can't be a nullptr, even if the len is zero or else - // openssl will prompt for a password and we really don't want that. - if (passphrase.get() != nullptr) { - pass.data = static_cast<char*>(passphrase.get()); - } - pass.len = passphrase.size(); - } - return pass; - } - - using EncoderCtxPointer = DeleteFnPtr<OSSL_ENCODER_CTX, OSSL_ENCODER_CTX_free>; - - bool EncodeTraditionalPemWithEmptyPassphrase(const EVP_PKEY* key, BIO* bio, int selection, const char* structure, - const EVP_CIPHER* cipher) { - BIOPointer der = BIOPointer::NewMem(); - EncoderCtxPointer encoder(OSSL_ENCODER_CTX_new_for_pkey(key, selection, "DER", structure, nullptr)); - if (!der || !encoder || OSSL_ENCODER_CTX_get_num_encoders(encoder.get()) == 0 || OSSL_ENCODER_to_bio(encoder.get(), der.get()) != 1) { - return false; - } - - BUF_MEM* der_data = der; - const int iv_length = EVP_CIPHER_get_iv_length(cipher); - const int key_length = EVP_CIPHER_get_key_length(cipher); - const int block_size = EVP_CIPHER_get_block_size(cipher); - if (der_data == nullptr || der_data->length > INT_MAX || iv_length <= 0 || iv_length > EVP_MAX_IV_LENGTH || key_length <= 0 || - key_length > EVP_MAX_KEY_LENGTH || block_size <= 0 || der_data->length > static_cast<size_t>(INT_MAX - block_size)) { - return false; - } - - std::array<unsigned char, EVP_MAX_IV_LENGTH> iv{}; - auto derived_key = DataPointer::SecureAlloc(key_length); - auto encrypted = DataPointer::Alloc(der_data->length + block_size); - auto ctx = CipherCtxPointer::New(); - const unsigned char empty_passphrase = 0; - if (!derived_key || !encrypted || !ctx || RAND_bytes(iv.data(), iv_length) != 1 || - EVP_BytesToKey(cipher, EVP_md5(), iv.data(), &empty_passphrase, 0, 1, derived_key.get<unsigned char>(), nullptr) != key_length || - EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, derived_key.get<unsigned char>(), iv.data()) != 1) { - return false; - } - - int encrypted_length = 0; - int final_length = 0; - if (EVP_EncryptUpdate(ctx.get(), encrypted.get<unsigned char>(), &encrypted_length, - reinterpret_cast<const unsigned char*>(der_data->data), static_cast<int>(der_data->length)) != 1 || - EVP_EncryptFinal_ex(ctx.get(), encrypted.get<unsigned char>() + encrypted_length, &final_length) != 1) { - return false; - } - - const char* pem_name; - switch (EVP_PKEY_get_id(key)) { - case EVP_PKEY_RSA: - pem_name = "RSA PRIVATE KEY"; - break; - case EVP_PKEY_EC: - pem_name = "EC PRIVATE KEY"; - break; - default: - return false; - } - - const char* cipher_name = EVP_CIPHER_get0_name(cipher); - if (cipher_name == nullptr) - return false; - std::array<char, PEM_BUFSIZE> header{}; - PEM_proc_type(header.data(), PEM_TYPE_ENCRYPTED); - PEM_dek_info(header.data(), cipher_name, iv_length, reinterpret_cast<const char*>(iv.data())); - return PEM_write_bio(bio, pem_name, header.data(), encrypted.get<unsigned char>(), encrypted_length + final_length) > 0; - } - - bool EncodeKey(const EVP_PKEY* key, BIO* bio, int selection, EVPKeyPointer::PKFormatType format, const char* structure, - const EVP_CIPHER* cipher = nullptr, Buffer<char> passphrase = {}) { - const char* output_type; - switch (format) { - case EVPKeyPointer::PKFormatType::PEM: - output_type = "PEM"; - break; - case EVPKeyPointer::PKFormatType::DER: - output_type = "DER"; - break; - default: - return false; - } - - EncoderCtxPointer ctx(OSSL_ENCODER_CTX_new_for_pkey(key, selection, output_type, structure, nullptr)); - if (!ctx || OSSL_ENCODER_CTX_get_num_encoders(ctx.get()) == 0) - return false; - - if (cipher != nullptr) { - if (passphrase.len == 0) { - // Provider PEM encoding rejects an empty password before encryption. - // Provider DER plus EVP framing preserves the traditional PEM behavior. - return EncodeTraditionalPemWithEmptyPassphrase(key, bio, selection, structure, cipher); - } - const char* cipher_name = EVP_CIPHER_get0_name(cipher); - if (cipher_name == nullptr || OSSL_ENCODER_CTX_set_cipher(ctx.get(), cipher_name, nullptr) != 1 || - OSSL_ENCODER_CTX_set_passphrase(ctx.get(), reinterpret_cast<const unsigned char*>(passphrase.data), passphrase.len) != 1) { - return false; - } - } - - return OSSL_ENCODER_to_bio(ctx.get(), bio) == 1; - } -} // namespace - -EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePrivateKey(const PrivateKeyEncodingConfig& config, - const Buffer<const unsigned char>& buffer) { - static constexpr auto keyOrError = [](EVPKeyPointer pkey, bool had_passphrase = false) { - if (int err = ERR_peek_error()) { - if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ && !had_passphrase) { - return ParseKeyResult(PKParseError::NEED_PASSPHRASE); - } - return ParseKeyResult(PKParseError::FAILED, err); - } - if (!pkey) - return ParseKeyResult(PKParseError::FAILED); - return ParseKeyResult(std::move(pkey)); - }; - - auto bio = BIOPointer::New(buffer); - if (!bio) - return ParseKeyResult(PKParseError::FAILED); - - auto passphrase = GetPassphrase(config); - - if (config.format == PKFormatType::PEM) { - auto key = PEM_read_bio_PrivateKey(bio.get(), nullptr, PasswordCallback, config.passphrase.has_value() ? &passphrase : nullptr); - return keyOrError(EVPKeyPointer(key), config.passphrase.has_value()); - } - - if (config.format != PKFormatType::DER) { - return ParseKeyResult(PKParseError::FAILED); - } - - switch (config.type) { - case PKEncodingType::PKCS1: { - auto key = d2i_PrivateKey_bio(bio.get(), nullptr); - return keyOrError(EVPKeyPointer(key)); - } - case PKEncodingType::PKCS8: { - if (IsEncryptedPrivateKeyInfo(buffer)) { - auto key = d2i_PKCS8PrivateKey_bio(bio.get(), nullptr, PasswordCallback, config.passphrase.has_value() ? &passphrase : nullptr); - return keyOrError(EVPKeyPointer(key), config.passphrase.has_value()); - } - - PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr)); - if (!p8inf) { - return ParseKeyResult(PKParseError::FAILED, ERR_peek_error()); - } - return keyOrError(EVPKeyPointer(EVP_PKCS82PKEY(p8inf.get()))); - } - case PKEncodingType::SEC1: { - auto key = d2i_PrivateKey_bio(bio.get(), nullptr); - return keyOrError(EVPKeyPointer(key)); - } - default: { - return ParseKeyResult(PKParseError::FAILED, ERR_peek_error()); - } - }; -} - -Result<BIOPointer, bool> EVPKeyPointer::writePrivateKey(const PrivateKeyEncodingConfig& config) const { - if (config.format == PKFormatType::JWK) { - return Result<BIOPointer, bool>(false); - } - - auto bio = BIOPointer::NewMem(); - if (!bio) { - return Result<BIOPointer, bool>(false); - } - - auto passphrase = GetPassphrase(config); - MarkPopErrorOnReturn mark_pop_error_on_return; - bool err; - - switch (config.type) { - case PKEncodingType::PKCS1: { - // PKCS1 is only permitted for RSA keys. - if (id() != EVP_PKEY_RSA) - return Result<BIOPointer, bool>(false); - const EVP_CIPHER* cipher = config.format == PKFormatType::PEM ? config.cipher : nullptr; - err = !EncodeKey(get(), bio.get(), EVP_PKEY_KEYPAIR, config.format, "type-specific", cipher, passphrase); - break; - } - case PKEncodingType::PKCS8: { - switch (config.format) { - case PKFormatType::PEM: { - // Encode PKCS#8 as PEM. - err = PEM_write_bio_PKCS8PrivateKey(bio.get(), get(), config.cipher, passphrase.data, passphrase.len, nullptr, nullptr) != 1; - break; - } - case PKFormatType::DER: { - err = i2d_PKCS8PrivateKey_bio(bio.get(), get(), config.cipher, passphrase.data, passphrase.len, nullptr, nullptr) != 1; - break; - } - default: { - // Should never get here. - return Result<BIOPointer, bool>(false); - } - } - break; - } - case PKEncodingType::SEC1: { - // SEC1 is only permitted for EC keys - if (id() != EVP_PKEY_EC) - return Result<BIOPointer, bool>(false); - const EVP_CIPHER* cipher = config.format == PKFormatType::PEM ? config.cipher : nullptr; - err = !EncodeKey(get(), bio.get(), EVP_PKEY_KEYPAIR, config.format, "type-specific", cipher, passphrase); - break; - } - default: { - // Not a valid private key encoding - return Result<BIOPointer, bool>(false); - } - } - - if (err) { - // Failed to encode the private key. - return Result<BIOPointer, bool>(false, mark_pop_error_on_return.peekError()); - } - - return bio; -} - -Result<BIOPointer, bool> EVPKeyPointer::writePublicKey(const ncrypto::EVPKeyPointer::PublicKeyEncodingConfig& config) const { - auto bio = BIOPointer::NewMem(); - if (!bio) - return Result<BIOPointer, bool>(false); - - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (config.type == ncrypto::EVPKeyPointer::PKEncodingType::PKCS1) { - // PKCS#1 is only valid for RSA keys. - if (id() != EVP_PKEY_RSA || !EncodeKey(get(), bio.get(), EVP_PKEY_PUBLIC_KEY, config.format, "type-specific")) { - return Result<BIOPointer, bool>(false, mark_pop_error_on_return.peekError()); - } - return bio; - } - - if (config.format == ncrypto::EVPKeyPointer::PKFormatType::PEM) { - // Encode SPKI as PEM. - if (PEM_write_bio_PUBKEY(bio.get(), get()) != 1) { - return Result<BIOPointer, bool>(false, mark_pop_error_on_return.peekError()); - } - return bio; - } - - // Encode SPKI as DER. - if (i2d_PUBKEY_bio(bio.get(), get()) != 1) { - return Result<BIOPointer, bool>(false, mark_pop_error_on_return.peekError()); - } - return bio; -} - -bool EVPKeyPointer::isRsaVariant() const { - if (!pkey_) - return false; - int type = id(); - return type == EVP_PKEY_RSA || type == EVP_PKEY_RSA2 || type == EVP_PKEY_RSA_PSS; -} - -bool EVPKeyPointer::isOneShotVariant() const { - if (!pkey_) - return false; - int type = id(); - switch (type) { - case EVP_PKEY_ED25519: - case EVP_PKEY_ED448: -#if OPENSSL_WITH_PQC - case EVP_PKEY_ML_DSA_44: - case EVP_PKEY_ML_DSA_65: - case EVP_PKEY_ML_DSA_87: - case EVP_PKEY_SLH_DSA_SHA2_128F: - case EVP_PKEY_SLH_DSA_SHA2_128S: - case EVP_PKEY_SLH_DSA_SHA2_192F: - case EVP_PKEY_SLH_DSA_SHA2_192S: - case EVP_PKEY_SLH_DSA_SHA2_256F: - case EVP_PKEY_SLH_DSA_SHA2_256S: - case EVP_PKEY_SLH_DSA_SHAKE_128F: - case EVP_PKEY_SLH_DSA_SHAKE_128S: - case EVP_PKEY_SLH_DSA_SHAKE_192F: - case EVP_PKEY_SLH_DSA_SHAKE_192S: - case EVP_PKEY_SLH_DSA_SHAKE_256F: - case EVP_PKEY_SLH_DSA_SHAKE_256S: -#endif - return true; - default: - return false; - } -} - -bool EVPKeyPointer::isSigVariant() const { - if (!pkey_) - return false; - int type = id(); - return type == EVP_PKEY_EC || type == EVP_PKEY_DSA; -} - -int EVPKeyPointer::getDefaultSignPadding() const { - return id() == EVP_PKEY_RSA_PSS ? RSA_PKCS1_PSS_PADDING : RSA_PKCS1_PADDING; -} - -std::optional<uint32_t> EVPKeyPointer::getBytesOfRS() const { - if (!pkey_) - return std::nullopt; - const char* parameter; - - switch (base_id()) { - case EVP_PKEY_DSA: - parameter = OSSL_PKEY_PARAM_FFC_Q; - break; - case EVP_PKEY_EC: - parameter = OSSL_PKEY_PARAM_EC_ORDER; - break; - default: - return std::nullopt; - } - - BIGNUM* raw = nullptr; - if (EVP_PKEY_get_bn_param(get(), parameter, &raw) != 1) { - return std::nullopt; - } - BignumPointer value(raw); - return (value.bitLength() + 7) / 8; -} - -EVPKeyPointer EVPKeyPointer::clone() const { - if (!pkey_) - return {}; - if (!EVP_PKEY_up_ref(pkey_.get())) - return {}; - return EVPKeyPointer(pkey_.get()); -} - -bool EVPKeyPointer::validateDsaParameters() const { - if (!pkey_) - return false; - if (EVP_default_properties_is_fips_enabled(nullptr) && EVP_PKEY_DSA == id()) { - BIGNUM* raw_p = nullptr; - BIGNUM* raw_q = nullptr; - if (EVP_PKEY_get_bn_param(get(), OSSL_PKEY_PARAM_FFC_P, &raw_p) != 1 || - EVP_PKEY_get_bn_param(get(), OSSL_PKEY_PARAM_FFC_Q, &raw_q) != 1) { - BN_clear_free(raw_p); - BN_clear_free(raw_q); - return false; - } - BignumPointer p(raw_p); - BignumPointer q(raw_q); - int L = p.bitLength(); - int N = q.bitLength(); - - return (L == 1024 && N == 160) || (L == 2048 && N == 224) || (L == 2048 && N == 256) || (L == 3072 && N == 256); - } - - return true; -} - -// ============================================================================ - -const Cipher Cipher::FromName(const char* name) { - return Cipher(EVP_get_cipherbyname(name)); -} - -const Cipher Cipher::FromNid(int nid) { - return Cipher(EVP_get_cipherbynid(nid)); -} - -const Cipher Cipher::FromCtx(const CipherCtxPointer& ctx) { - return Cipher(EVP_CIPHER_CTX_cipher(ctx.get())); -} - -const Cipher Cipher::EMPTY = Cipher(); -const Cipher Cipher::AES_128_CBC = Cipher::FromNid(NID_aes_128_cbc); -const Cipher Cipher::AES_192_CBC = Cipher::FromNid(NID_aes_192_cbc); -const Cipher Cipher::AES_256_CBC = Cipher::FromNid(NID_aes_256_cbc); -const Cipher Cipher::AES_128_CTR = Cipher::FromNid(NID_aes_128_ctr); -const Cipher Cipher::AES_192_CTR = Cipher::FromNid(NID_aes_192_ctr); -const Cipher Cipher::AES_256_CTR = Cipher::FromNid(NID_aes_256_ctr); -const Cipher Cipher::AES_128_GCM = Cipher::FromNid(NID_aes_128_gcm); -const Cipher Cipher::AES_192_GCM = Cipher::FromNid(NID_aes_192_gcm); -const Cipher Cipher::AES_256_GCM = Cipher::FromNid(NID_aes_256_gcm); -const Cipher Cipher::AES_128_KW = Cipher::FromNid(NID_id_aes128_wrap); -const Cipher Cipher::AES_192_KW = Cipher::FromNid(NID_id_aes192_wrap); -const Cipher Cipher::AES_256_KW = Cipher::FromNid(NID_id_aes256_wrap); - -#ifndef OPENSSL_IS_BORINGSSL -const Cipher Cipher::AES_128_OCB = Cipher::FromNid(NID_aes_128_ocb); -const Cipher Cipher::AES_192_OCB = Cipher::FromNid(NID_aes_192_ocb); -const Cipher Cipher::AES_256_OCB = Cipher::FromNid(NID_aes_256_ocb); -#endif - -const Cipher Cipher::CHACHA20_POLY1305 = Cipher::FromNid(NID_chacha20_poly1305); - -bool Cipher::isGcmMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_GCM_MODE; -} - -bool Cipher::isWrapMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_WRAP_MODE; -} - -bool Cipher::isCtrMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_CTR_MODE; -} - -bool Cipher::isCcmMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_CCM_MODE; -} - -bool Cipher::isOcbMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_OCB_MODE; -} - -bool Cipher::isStreamMode() const { - if (!cipher_) - return false; - return getMode() == EVP_CIPH_STREAM_CIPHER; -} - -bool Cipher::isChaCha20Poly1305() const { - if (!cipher_) - return false; - return getNid() == NID_chacha20_poly1305; -} - -int Cipher::getMode() const { - if (!cipher_) - return 0; - return EVP_CIPHER_mode(cipher_); -} - -int Cipher::getIvLength() const { - if (!cipher_) - return 0; - return EVP_CIPHER_iv_length(cipher_); -} - -int Cipher::getKeyLength() const { - if (!cipher_) - return 0; - return EVP_CIPHER_key_length(cipher_); -} - -int Cipher::getBlockSize() const { - if (!cipher_) - return 0; - return EVP_CIPHER_block_size(cipher_); -} - -int Cipher::getNid() const { - if (!cipher_) - return 0; - return EVP_CIPHER_nid(cipher_); -} - -std::string_view Cipher::getModeLabel() const { - if (!cipher_) - return {}; - switch (getMode()) { - case EVP_CIPH_CCM_MODE: - return "ccm"; - case EVP_CIPH_CFB_MODE: - return "cfb"; - case EVP_CIPH_CBC_MODE: - return "cbc"; - case EVP_CIPH_CTR_MODE: - return "ctr"; - case EVP_CIPH_ECB_MODE: - return "ecb"; - case EVP_CIPH_GCM_MODE: - return "gcm"; - case EVP_CIPH_OCB_MODE: - return "ocb"; - case EVP_CIPH_OFB_MODE: - return "ofb"; - case EVP_CIPH_WRAP_MODE: - return "wrap"; - case EVP_CIPH_XTS_MODE: - return "xts"; - case EVP_CIPH_STREAM_CIPHER: - return "stream"; - } - return "{unknown}"; -} - -const char* Cipher::getName() const { - if (!cipher_) - return {}; - // OBJ_nid2sn(EVP_CIPHER_nid(cipher)) is used here instead of - // EVP_CIPHER_name(cipher) for compatibility with BoringSSL. - return OBJ_nid2sn(getNid()); -} - -bool Cipher::isSupportedAuthenticatedMode() const { - switch (getMode()) { - case EVP_CIPH_CCM_MODE: - case EVP_CIPH_GCM_MODE: -#ifndef OPENSSL_NO_OCB - case EVP_CIPH_OCB_MODE: -#endif - return true; - case EVP_CIPH_STREAM_CIPHER: - return getNid() == NID_chacha20_poly1305; - default: - return false; - } -} - -int Cipher::bytesToKey(const Digest& digest, const Buffer<const unsigned char>& input, unsigned char* key, unsigned char* iv) const { - return EVP_BytesToKey(*this, digest, nullptr, input.data, input.len, 1, key, iv); -} - -// ============================================================================ - -CipherCtxPointer CipherCtxPointer::New() { - auto ret = CipherCtxPointer(EVP_CIPHER_CTX_new()); - if (!ret) - return {}; - EVP_CIPHER_CTX_init(ret.get()); - return ret; -} - -CipherCtxPointer::CipherCtxPointer(EVP_CIPHER_CTX* ctx) : ctx_(ctx) {} - -CipherCtxPointer::CipherCtxPointer(CipherCtxPointer&& other) noexcept : ctx_(other.release()) {} - -CipherCtxPointer& CipherCtxPointer::operator=(CipherCtxPointer&& other) noexcept { - if (this == &other) - return *this; - this->~CipherCtxPointer(); - return *new (this) CipherCtxPointer(std::move(other)); -} - -CipherCtxPointer::~CipherCtxPointer() { - reset(); -} - -void CipherCtxPointer::reset(EVP_CIPHER_CTX* ctx) { - ctx_.reset(ctx); -} - -EVP_CIPHER_CTX* CipherCtxPointer::release() { - return ctx_.release(); -} - -void CipherCtxPointer::setAllowWrap() { - if (!ctx_) - return; - EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); -} - -bool CipherCtxPointer::setKeyLength(size_t length) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_set_key_length(ctx_.get(), length); -} - -bool CipherCtxPointer::setIvLength(size_t length) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_IVLEN, length, nullptr) > 0; -} - -bool CipherCtxPointer::setAeadTag(const Buffer<const char>& tag) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, tag.len, const_cast<char*>(tag.data)) > 0; -} - -bool CipherCtxPointer::setAeadTagLength(size_t length) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, length, nullptr) > 0; -} - -bool CipherCtxPointer::setPadding(bool padding) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_set_padding(ctx_.get(), padding); -} - -int CipherCtxPointer::getBlockSize() const { - if (!ctx_) - return 0; - return EVP_CIPHER_CTX_block_size(ctx_.get()); -} - -int CipherCtxPointer::getMode() const { - if (!ctx_) - return 0; - return EVP_CIPHER_CTX_mode(ctx_.get()); -} - -bool CipherCtxPointer::isGcmMode() const { - if (!ctx_) - return false; - return getMode() == EVP_CIPH_GCM_MODE; -} - -bool CipherCtxPointer::isOcbMode() const { - if (!ctx_) - return false; - return getMode() == EVP_CIPH_OCB_MODE; -} - -bool CipherCtxPointer::isCcmMode() const { - if (!ctx_) - return false; - return getMode() == EVP_CIPH_CCM_MODE; -} - -bool CipherCtxPointer::isWrapMode() const { - if (!ctx_) - return false; - return getMode() == EVP_CIPH_WRAP_MODE; -} - -bool CipherCtxPointer::isChaCha20Poly1305() const { - if (!ctx_) - return false; - return getNid() == NID_chacha20_poly1305; -} - -int CipherCtxPointer::getNid() const { - if (!ctx_) - return 0; - return EVP_CIPHER_CTX_nid(ctx_.get()); -} - -bool CipherCtxPointer::init(const Cipher& cipher, bool encrypt, const unsigned char* key, const unsigned char* iv) { - if (!ctx_) - return false; - return EVP_CipherInit_ex(ctx_.get(), cipher, nullptr, key, iv, encrypt ? 1 : 0) == 1; -} - -bool CipherCtxPointer::update(const Buffer<const unsigned char>& in, unsigned char* out, int* out_len, bool finalize) { - if (!ctx_) - return false; - if (!finalize) { - return EVP_CipherUpdate(ctx_.get(), out, out_len, in.data, in.len) == 1; - } - return EVP_CipherFinal_ex(ctx_.get(), out, out_len) == 1; -} - -bool CipherCtxPointer::getAeadTag(size_t len, unsigned char* out) { - if (!ctx_) - return false; - return EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG, len, out) > 0; -} - -// ============================================================================ - -ECDSASigPointer::ECDSASigPointer() : sig_(nullptr) {} -ECDSASigPointer::ECDSASigPointer(ECDSA_SIG* sig) : sig_(sig) { - if (sig_) { - ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); - } -} -ECDSASigPointer::ECDSASigPointer(ECDSASigPointer&& other) noexcept : sig_(other.release()) { - if (sig_) { - ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); - } -} - -ECDSASigPointer& ECDSASigPointer::operator=(ECDSASigPointer&& other) noexcept { - sig_.reset(other.release()); - if (sig_) { - ECDSA_SIG_get0(sig_.get(), &pr_, &ps_); - } - return *this; -} - -ECDSASigPointer::~ECDSASigPointer() { - reset(); -} - -void ECDSASigPointer::reset(ECDSA_SIG* sig) { - sig_.reset(sig); - pr_ = nullptr; - ps_ = nullptr; -} - -ECDSA_SIG* ECDSASigPointer::release() { - pr_ = nullptr; - ps_ = nullptr; - return sig_.release(); -} - -ECDSASigPointer ECDSASigPointer::New() { - return ECDSASigPointer(ECDSA_SIG_new()); -} - -ECDSASigPointer ECDSASigPointer::Parse(const Buffer<const unsigned char>& sig) { - const unsigned char* ptr = sig.data; - return ECDSASigPointer(d2i_ECDSA_SIG(nullptr, &ptr, sig.len)); -} - -bool ECDSASigPointer::setParams(BignumPointer&& r, BignumPointer&& s) { - if (!sig_) - return false; - return ECDSA_SIG_set0(sig_.get(), r.release(), s.release()); -} - -Buffer<unsigned char> ECDSASigPointer::encode() const { - if (!sig_) - return { - .data = nullptr, - .len = 0, - }; - Buffer<unsigned char> buf; - buf.len = i2d_ECDSA_SIG(sig_.get(), &buf.data); - return buf; -} - -// ============================================================================ - -EVPKeyCtxPointer::EVPKeyCtxPointer() : ctx_(nullptr) {} - -EVPKeyCtxPointer::EVPKeyCtxPointer(EVP_PKEY_CTX* ctx) : ctx_(ctx) {} - -EVPKeyCtxPointer::EVPKeyCtxPointer(EVPKeyCtxPointer&& other) noexcept : ctx_(other.release()) {} - -EVPKeyCtxPointer& EVPKeyCtxPointer::operator=(EVPKeyCtxPointer&& other) noexcept { - ctx_.reset(other.release()); - return *this; -} - -EVPKeyCtxPointer::~EVPKeyCtxPointer() { - reset(); -} - -void EVPKeyCtxPointer::reset(EVP_PKEY_CTX* ctx) { - ctx_.reset(ctx); -} - -EVP_PKEY_CTX* EVPKeyCtxPointer::release() { - return ctx_.release(); -} - -EVPKeyCtxPointer EVPKeyCtxPointer::New(const EVPKeyPointer& key) { - if (!key) - return {}; - return EVPKeyCtxPointer(EVP_PKEY_CTX_new(key.get(), nullptr)); -} - -EVPKeyCtxPointer EVPKeyCtxPointer::NewFromID(int id) { -#ifdef OPENSSL_IS_BORINGSSL - // DSA keys are not supported with BoringSSL - if (id == EVP_PKEY_DSA) - return {}; -#endif - return EVPKeyCtxPointer(EVP_PKEY_CTX_new_id(id, nullptr)); -} - -bool EVPKeyCtxPointer::initForDerive(const EVPKeyPointer& peer) { - if (!ctx_) - return false; - if (EVP_PKEY_derive_init(ctx_.get()) != 1) - return false; - return EVP_PKEY_derive_set_peer(ctx_.get(), peer.get()) == 1; -} - -bool EVPKeyCtxPointer::initForKeygen() { - if (!ctx_) - return false; - return EVP_PKEY_keygen_init(ctx_.get()) == 1; -} - -bool EVPKeyCtxPointer::initForParamgen() { - if (!ctx_) - return false; - return EVP_PKEY_paramgen_init(ctx_.get()) == 1; -} - -int EVPKeyCtxPointer::initForVerify() { - if (!ctx_) - return 0; - return EVP_PKEY_verify_init(ctx_.get()); -} - -int EVPKeyCtxPointer::initForSign() { - if (!ctx_) - return 0; - return EVP_PKEY_sign_init(ctx_.get()); -} - -bool EVPKeyCtxPointer::setDhParameters(int prime_size, uint32_t generator) { -#ifndef OPENSSL_IS_BORINGSSL - if (!ctx_) - return false; - return EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx_.get(), prime_size) == 1 && - EVP_PKEY_CTX_set_dh_paramgen_generator(ctx_.get(), generator) == 1; -#else - // TODO(jasnell): Boringssl appears not to support this operation. - // Is there an alternative approach that Boringssl does support? - return false; -#endif -} - -bool EVPKeyCtxPointer::setDsaParameters(uint32_t bits, std::optional<int> q_bits) { -#ifndef NCRYPTO_NO_DSA_KEYGEN - if (!ctx_) - return false; - if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx_.get(), bits) != 1) { - return false; - } - if (q_bits.has_value() && EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx_.get(), q_bits.value()) != 1) { - return false; - } - return true; -#else - // Older versions of openssl/boringssl do not implement the DSA keygen. - return false; -#endif -} - -bool EVPKeyCtxPointer::setEcParameters(int curve, int encoding) { - if (!ctx_) - return false; - return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx_.get(), curve) == 1 && EVP_PKEY_CTX_set_ec_param_enc(ctx_.get(), encoding) == 1; -} - -bool EVPKeyCtxPointer::setRsaOaepMd(const Digest& md) { - if (!md || !ctx_) - return false; - const EVP_MD* md_ptr = md; - return EVP_PKEY_CTX_set_rsa_oaep_md(ctx_.get(), md_ptr) > 0; -} - -bool EVPKeyCtxPointer::setRsaMgf1Md(const Digest& md) { - if (!md || !ctx_) - return false; - const EVP_MD* md_ptr = md; - return EVP_PKEY_CTX_set_rsa_mgf1_md(ctx_.get(), md_ptr) > 0; -} - -bool EVPKeyCtxPointer::setRsaPadding(int padding) { - return setRsaPadding(ctx_.get(), padding, std::nullopt); -} - -bool EVPKeyCtxPointer::setRsaPadding(EVP_PKEY_CTX* ctx, int padding, std::optional<int> salt_len) { - if (ctx == nullptr) - return false; - if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0) { - return false; - } - if (padding == RSA_PKCS1_PSS_PADDING && salt_len.has_value()) { - return EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, salt_len.value()) > 0; - } - return true; -} - -bool EVPKeyCtxPointer::setRsaKeygenBits(int bits) { - if (!ctx_) - return false; - return EVP_PKEY_CTX_set_rsa_keygen_bits(ctx_.get(), bits) == 1; -} - -bool EVPKeyCtxPointer::setRsaKeygenPubExp(BignumPointer&& e) { - if (!ctx_) - return false; - return EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx_.get(), e.get()) == 1; -} - -bool EVPKeyCtxPointer::setRsaPssKeygenMd(const Digest& md) { - if (!md || !ctx_) - return false; - // OpenSSL < 3 accepts a void* for the md parameter. - const EVP_MD* md_ptr = md; - return EVP_PKEY_CTX_set_rsa_pss_keygen_md(ctx_.get(), md_ptr) > 0; -} - -bool EVPKeyCtxPointer::setRsaPssKeygenMgf1Md(const Digest& md) { - if (!md || !ctx_) - return false; - const EVP_MD* md_ptr = md; - return EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(ctx_.get(), md_ptr) > 0; -} - -bool EVPKeyCtxPointer::setRsaPssSaltlen(int salt_len) { - if (!ctx_) - return false; - return EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(ctx_.get(), salt_len) > 0; -} - -bool EVPKeyCtxPointer::setRsaImplicitRejection() { -#ifndef OPENSSL_IS_BORINGSSL - if (!ctx_) - return false; - return EVP_PKEY_CTX_ctrl_str(ctx_.get(), "rsa_pkcs1_implicit_rejection", "1") > 0; - // From the doc -2 means that the option is not supported. - // The default for the option is enabled and if it has been - // specifically disabled we want to respect that so we will - // not throw an error if the option is supported regardless - // of how it is set. The call to set the value - // will not affect what is used since a different context is - // used in the call if the option is supported -#else - // TODO(jasnell): Boringssl appears not to support this operation. - // Is there an alternative approach that Boringssl does support? - return true; -#endif -} - -bool EVPKeyCtxPointer::setRsaOaepLabel(DataPointer&& data) { - if (!ctx_) - return false; - if (EVP_PKEY_CTX_set0_rsa_oaep_label(ctx_.get(), static_cast<unsigned char*>(data.get()), data.size()) > 0) { - // The ctx_ takes ownership of data on success. - data.release(); - return true; - } - return false; -} - -bool EVPKeyCtxPointer::setSignatureMd(const EVPMDCtxPointer& md) { - if (!ctx_) - return false; - return EVP_PKEY_CTX_set_signature_md(ctx_.get(), EVP_MD_CTX_get0_md(md.get())) == 1; -} - -bool EVPKeyCtxPointer::initForEncrypt() { - if (!ctx_) - return false; - return EVP_PKEY_encrypt_init(ctx_.get()) == 1; -} - -bool EVPKeyCtxPointer::initForDecrypt() { - if (!ctx_) - return false; - return EVP_PKEY_decrypt_init(ctx_.get()) == 1; -} - -DataPointer EVPKeyCtxPointer::derive() const { - if (!ctx_) - return {}; - size_t len = 0; - if (EVP_PKEY_derive(ctx_.get(), nullptr, &len) != 1) - return {}; - auto data = DataPointer::Alloc(len); - if (!data) - return {}; - if (EVP_PKEY_derive(ctx_.get(), static_cast<unsigned char*>(data.get()), &len) != 1) { - return {}; - } - return data; -} - -EVPKeyPointer EVPKeyCtxPointer::paramgen() const { - if (!ctx_) - return {}; - EVP_PKEY* key = nullptr; - if (EVP_PKEY_paramgen(ctx_.get(), &key) != 1) - return {}; - return EVPKeyPointer(key); -} - -bool EVPKeyCtxPointer::publicCheck() const { - if (!ctx_) - return false; -#ifndef OPENSSL_IS_BORINGSSL -#if OPENSSL_VERSION_MAJOR >= 3 - return EVP_PKEY_public_check_quick(ctx_.get()) == 1; -#else - return EVP_PKEY_public_check(ctx_.get()) == 1; -#endif -#else // OPENSSL_IS_BORINGSSL - // Boringssl appears not to support this operation. - // TODO(jasnell): Is there an alternative approach that Boringssl does - // support? - return true; -#endif -} - -bool EVPKeyCtxPointer::privateCheck() const { - if (!ctx_) - return false; -#ifndef OPENSSL_IS_BORINGSSL - return EVP_PKEY_check(ctx_.get()) == 1; -#else - // Boringssl appears not to support this operation. - // TODO(jasnell): Is there an alternative approach that Boringssl does - // support? - return true; -#endif -} - -bool EVPKeyCtxPointer::verify(const Buffer<const unsigned char>& sig, const Buffer<const unsigned char>& data) { - if (!ctx_) - return false; - return EVP_PKEY_verify(ctx_.get(), sig.data, sig.len, data.data, data.len) == 1; -} - -DataPointer EVPKeyCtxPointer::sign(const Buffer<const unsigned char>& data) { - if (!ctx_) - return {}; - size_t len = 0; - if (EVP_PKEY_sign(ctx_.get(), nullptr, &len, data.data, data.len) != 1) { - return {}; - } - auto buf = DataPointer::Alloc(len); - if (!buf) - return {}; - if (EVP_PKEY_sign(ctx_.get(), static_cast<unsigned char*>(buf.get()), &len, data.data, data.len) != 1) { - return {}; - } - return buf.resize(len); -} - -bool EVPKeyCtxPointer::signInto(const Buffer<const unsigned char>& data, Buffer<unsigned char>* sig) { - if (!ctx_) - return false; - size_t len = sig->len; - if (EVP_PKEY_sign(ctx_.get(), sig->data, &len, data.data, data.len) != 1) { - return false; - } - sig->len = len; - return true; -} - -// ============================================================================ - -namespace { - - using EVP_PKEY_cipher_init_t = int(EVP_PKEY_CTX* ctx); - using EVP_PKEY_cipher_t = int(EVP_PKEY_CTX* ctx, unsigned char* out, size_t* outlen, const unsigned char* in, size_t inlen); - - template <EVP_PKEY_cipher_init_t init, EVP_PKEY_cipher_t cipher> - DataPointer CipherImpl(const EVPKeyPointer& key, const Cipher::CipherParams& params, const Buffer<const void> in) { - if (!key) - return {}; - EVPKeyCtxPointer ctx = key.newCtx(); - if (!ctx || init(ctx.get()) <= 0 || !ctx.setRsaPadding(params.padding) || - (params.digest != nullptr && !ctx.setRsaOaepMd(params.digest))) { - return {}; - } - - if (params.label.len != 0 && params.label.data != nullptr && !ctx.setRsaOaepLabel(DataPointer::Copy(params.label))) { - return {}; - } - - size_t out_len = 0; - if (cipher(ctx.get(), nullptr, &out_len, static_cast<const unsigned char*>(in.data), in.len) <= 0) { - return {}; - } - - auto buf = DataPointer::Alloc(out_len); - if (!buf) - return {}; - - if (cipher(ctx.get(), static_cast<unsigned char*>(buf.get()), &out_len, static_cast<const unsigned char*>(in.data), in.len) <= 0) { - return {}; - } - - return buf.resize(out_len); - } -} // namespace - -DataPointer Cipher::encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in) { - // public operation - return CipherImpl<EVP_PKEY_encrypt_init, EVP_PKEY_encrypt>(key, params, in); -} - -DataPointer Cipher::decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in) { - // private operation - return CipherImpl<EVP_PKEY_decrypt_init, EVP_PKEY_decrypt>(key, params, in); -} - -DataPointer Cipher::sign(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in) { - // private operation - return CipherImpl<EVP_PKEY_sign_init, EVP_PKEY_sign>(key, params, in); -} - -DataPointer Cipher::recover(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in) { - // public operation - return CipherImpl<EVP_PKEY_verify_recover_init, EVP_PKEY_verify_recover>(key, params, in); -} - -namespace { - struct CipherCallbackContext { - Cipher::CipherNameCallback cb; - void operator()(const char* name) { - cb(name); - } - }; - -#if OPENSSL_VERSION_MAJOR >= 3 - template <class TypeName, TypeName* fetch_type(OSSL_LIB_CTX*, const char*, const char*), void free_type(TypeName*), - const TypeName* getbyname(const char*), const char* getname(const TypeName*)> - void array_push_back(const TypeName*, const char* from, const char*, void* arg) { - if (from == nullptr) - return; - - const TypeName* real_instance = getbyname(from); - if (!real_instance) - return; - - const char* real_name = getname(real_instance); - if (!real_name) - return; - - // EVP_*_fetch() does not support alias names, so we need to pass it the - // real/original algorithm name. - // We use EVP_*_fetch() as a filter here because it will only return an - // instance if the algorithm is supported by the public OpenSSL APIs (some - // algorithms are used internally by OpenSSL and are also passed to this - // callback). - TypeName* fetched = fetch_type(nullptr, real_name, nullptr); - if (fetched == nullptr) - return; - - free_type(fetched); - auto& cb = *(static_cast<CipherCallbackContext*>(arg)); - cb(from); - } -#else - template <class TypeName> - void array_push_back(const TypeName* evp_ref, const char* from, const char* to, void* arg) { - if (!from) - return; - auto& cb = *(static_cast<CipherCallbackContext*>(arg)); - cb(from); - } -#endif -} // namespace - -void Cipher::ForEach(Cipher::CipherNameCallback callback) { - ClearErrorOnReturn clearErrorOnReturn; - CipherCallbackContext context; - context.cb = std::move(callback); - - EVP_CIPHER_do_all_sorted( -#if OPENSSL_VERSION_MAJOR >= 3 - array_push_back<EVP_CIPHER, EVP_CIPHER_fetch, EVP_CIPHER_free, EVP_get_cipherbyname, EVP_CIPHER_get0_name>, -#else - array_push_back<EVP_CIPHER>, -#endif - &context); -} - -EVPMDCtxPointer::EVPMDCtxPointer() : ctx_(nullptr) {} - -EVPMDCtxPointer::EVPMDCtxPointer(EVP_MD_CTX* ctx) : ctx_(ctx) {} - -EVPMDCtxPointer::EVPMDCtxPointer(EVPMDCtxPointer&& other) noexcept : ctx_(other.release()) {} - -EVPMDCtxPointer& EVPMDCtxPointer::operator=(EVPMDCtxPointer&& other) noexcept { - ctx_.reset(other.release()); - return *this; -} - -EVPMDCtxPointer::~EVPMDCtxPointer() { - reset(); -} - -void EVPMDCtxPointer::reset(EVP_MD_CTX* ctx) { - ctx_.reset(ctx); -} - -EVP_MD_CTX* EVPMDCtxPointer::release() { - return ctx_.release(); -} - -bool EVPMDCtxPointer::digestInit(const Digest& digest) { - if (!ctx_) - return false; - return EVP_DigestInit_ex(ctx_.get(), digest, nullptr) > 0; -} - -bool EVPMDCtxPointer::digestUpdate(const Buffer<const void>& in) { - if (!ctx_) - return false; - return EVP_DigestUpdate(ctx_.get(), in.data, in.len) > 0; -} - -DataPointer EVPMDCtxPointer::digestFinal(size_t length) { - if (!ctx_) - return {}; - - auto buf = DataPointer::Alloc(length); - if (!buf) - return {}; - - Buffer<void> buffer = buf; - - if (!digestFinalInto(&buffer)) [[unlikely]] { - return {}; - } - - return buf; -} - -bool EVPMDCtxPointer::digestFinalInto(Buffer<void>* buf) { - if (!ctx_) - return false; - - auto ptr = static_cast<unsigned char*>(buf->data); - - int ret = (buf->len == getExpectedSize()) ? EVP_DigestFinal_ex(ctx_.get(), ptr, nullptr) : EVP_DigestFinalXOF(ctx_.get(), ptr, buf->len); - - if (ret != 1) [[unlikely]] - return false; - - return true; -} - -size_t EVPMDCtxPointer::getExpectedSize() { - if (!ctx_) - return 0; - return EVP_MD_CTX_size(ctx_.get()); -} - -size_t EVPMDCtxPointer::getDigestSize() const { - return EVP_MD_size(getDigest()); -} - -const EVP_MD* EVPMDCtxPointer::getDigest() const { - if (!ctx_) - return nullptr; - return EVP_MD_CTX_get0_md(ctx_.get()); -} - -bool EVPMDCtxPointer::hasXofFlag() const { - if (!ctx_) - return false; - return (EVP_MD_flags(getDigest()) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF; -} - -bool EVPMDCtxPointer::copyTo(const EVPMDCtxPointer& other) const { - if (!ctx_ || !other) - return {}; - if (EVP_MD_CTX_copy(other.get(), ctx_.get()) != 1) - return false; - return true; -} - -std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInit(const EVPKeyPointer& key, const Digest& digest) { - EVP_PKEY_CTX* ctx = nullptr; - if (!EVP_DigestSignInit(ctx_.get(), &ctx, digest, nullptr, key.get())) { - return std::nullopt; - } - return ctx; -} - -std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInit(const EVPKeyPointer& key, const Digest& digest) { - EVP_PKEY_CTX* ctx = nullptr; - if (!EVP_DigestVerifyInit(ctx_.get(), &ctx, digest, nullptr, key.get())) { - return std::nullopt; - } - return ctx; -} - -std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInitWithContext(const EVPKeyPointer& key, const Digest& digest, - const Buffer<const unsigned char>& context_string) { - (void)digest; -#ifdef OSSL_SIGNATURE_PARAM_CONTEXT_STRING - EVP_PKEY_CTX* ctx = nullptr; - -#ifdef OSSL_SIGNATURE_PARAM_INSTANCE - // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. - // Without it, OpenSSL silently ignores the context string. - if (key.id() == EVP_PKEY_ED25519) { - const OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_INSTANCE, const_cast<char*>("Ed25519ctx"), 0), - OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, - const_cast<unsigned char*>(context_string.data), context_string.len), - OSSL_PARAM_END}; - - if (!EVP_DigestSignInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { - return std::nullopt; - } - return ctx; - } -#endif // OSSL_SIGNATURE_PARAM_INSTANCE - - const OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, - const_cast<unsigned char*>(context_string.data), context_string.len), - OSSL_PARAM_END}; - - if (!EVP_DigestSignInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { - return std::nullopt; - } - return ctx; -#else - return std::nullopt; -#endif -} - -std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInitWithContext(const EVPKeyPointer& key, const Digest& digest, - const Buffer<const unsigned char>& context_string) { - (void)digest; -#ifdef OSSL_SIGNATURE_PARAM_CONTEXT_STRING - EVP_PKEY_CTX* ctx = nullptr; - -#ifdef OSSL_SIGNATURE_PARAM_INSTANCE - // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. - // Without it, OpenSSL silently ignores the context string. - if (key.id() == EVP_PKEY_ED25519) { - const OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_INSTANCE, const_cast<char*>("Ed25519ctx"), 0), - OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, - const_cast<unsigned char*>(context_string.data), context_string.len), - OSSL_PARAM_END}; - - if (!EVP_DigestVerifyInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { - return std::nullopt; - } - return ctx; - } -#endif // OSSL_SIGNATURE_PARAM_INSTANCE - - const OSSL_PARAM params[] = {OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, - const_cast<unsigned char*>(context_string.data), context_string.len), - OSSL_PARAM_END}; - - if (!EVP_DigestVerifyInit_ex(ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) { - return std::nullopt; - } - return ctx; -#else - return std::nullopt; -#endif -} - -DataPointer EVPMDCtxPointer::signOneShot(const Buffer<const unsigned char>& buf) const { - if (!ctx_) - return {}; - size_t len; - if (!EVP_DigestSign(ctx_.get(), nullptr, &len, buf.data, buf.len)) { - return {}; - } - auto data = DataPointer::Alloc(len); - if (!data) [[unlikely]] - return {}; - - if (!EVP_DigestSign(ctx_.get(), static_cast<unsigned char*>(data.get()), &len, buf.data, buf.len)) { - return {}; - } - return data; -} - -DataPointer EVPMDCtxPointer::sign(const Buffer<const unsigned char>& buf) const { - if (!ctx_) [[unlikely]] - return {}; - size_t len; - if (!EVP_DigestSignUpdate(ctx_.get(), buf.data, buf.len) || !EVP_DigestSignFinal(ctx_.get(), nullptr, &len)) { - return {}; - } - auto data = DataPointer::Alloc(len); - if (!data) [[unlikely]] - return {}; - if (!EVP_DigestSignFinal(ctx_.get(), static_cast<unsigned char*>(data.get()), &len)) { - return {}; - } - return data.resize(len); -} - -bool EVPMDCtxPointer::verify(const Buffer<const unsigned char>& buf, const Buffer<const unsigned char>& sig) const { - if (!ctx_) - return false; - int ret = EVP_DigestVerify(ctx_.get(), sig.data, sig.len, buf.data, buf.len); - return ret == 1; -} - -EVPMDCtxPointer EVPMDCtxPointer::New() { - return EVPMDCtxPointer(EVP_MD_CTX_new()); -} - -// ============================================================================ - -bool extractP1363(const Buffer<const unsigned char>& buf, unsigned char* dest, size_t n) { - auto asn1_sig = ECDSASigPointer::Parse(buf); - if (!asn1_sig) - return false; - - return BignumPointer::EncodePaddedInto(asn1_sig.r(), dest, n) > 0 && BignumPointer::EncodePaddedInto(asn1_sig.s(), dest + n, n) > 0; -} - -#if OPENSSL_VERSION_MAJOR >= 3 -EVPMacPointer::EVPMacPointer(EVP_MAC* mac) : mac_(mac) {} - -EVPMacPointer::EVPMacPointer(EVPMacPointer&& other) noexcept : mac_(std::move(other.mac_)) {} - -EVPMacPointer& EVPMacPointer::operator=(EVPMacPointer&& other) noexcept { - if (this == &other) - return *this; - mac_ = std::move(other.mac_); - return *this; -} - -EVPMacPointer::~EVPMacPointer() { - mac_.reset(); -} - -void EVPMacPointer::reset(EVP_MAC* mac) { - mac_.reset(mac); -} - -EVP_MAC* EVPMacPointer::release() { - return mac_.release(); -} - -EVPMacPointer EVPMacPointer::Fetch(const char* algorithm) { - return EVPMacPointer(EVP_MAC_fetch(nullptr, algorithm, nullptr)); -} - -EVPMacCtxPointer::EVPMacCtxPointer(EVP_MAC_CTX* ctx) : ctx_(ctx) {} - -EVPMacCtxPointer::EVPMacCtxPointer(EVPMacCtxPointer&& other) noexcept : ctx_(std::move(other.ctx_)) {} - -EVPMacCtxPointer& EVPMacCtxPointer::operator=(EVPMacCtxPointer&& other) noexcept { - if (this == &other) - return *this; - ctx_ = std::move(other.ctx_); - return *this; -} - -EVPMacCtxPointer::~EVPMacCtxPointer() { - ctx_.reset(); -} - -void EVPMacCtxPointer::reset(EVP_MAC_CTX* ctx) { - ctx_.reset(ctx); -} - -EVP_MAC_CTX* EVPMacCtxPointer::release() { - return ctx_.release(); -} - -bool EVPMacCtxPointer::init(const Buffer<const void>& key, const OSSL_PARAM* params) { - if (!ctx_) - return false; - return EVP_MAC_init(ctx_.get(), static_cast<const unsigned char*>(key.data), key.len, params) == 1; -} - -bool EVPMacCtxPointer::update(const Buffer<const void>& data) { - if (!ctx_) - return false; - return EVP_MAC_update(ctx_.get(), static_cast<const unsigned char*>(data.data), data.len) == 1; -} - -DataPointer EVPMacCtxPointer::final(size_t length) { - if (!ctx_) - return {}; - auto buf = DataPointer::Alloc(length); - if (!buf) - return {}; - - size_t result_len = length; - if (EVP_MAC_final(ctx_.get(), static_cast<unsigned char*>(buf.get()), &result_len, length) != 1) { - return {}; - } - - return buf; -} - -EVPMacCtxPointer EVPMacCtxPointer::New(EVP_MAC* mac) { - if (!mac) - return EVPMacCtxPointer(); - return EVPMacCtxPointer(EVP_MAC_CTX_new(mac)); -} -#endif // OPENSSL_VERSION_MAJOR >= 3 - -DataPointer hashDigest(const Buffer<const unsigned char>& buf, const EVP_MD* md) { - if (md == nullptr) - return {}; - size_t md_len = EVP_MD_size(md); - unsigned int result_size; - auto data = DataPointer::Alloc(md_len); - if (!data) - return {}; - - if (!EVP_Digest(buf.data, buf.len, reinterpret_cast<unsigned char*>(data.get()), &result_size, md, nullptr)) { - return {}; - } - - return data.resize(result_size); -} - -DataPointer xofHashDigest(const Buffer<const unsigned char>& buf, const EVP_MD* md, size_t output_length) { - if (md == nullptr) - return {}; - - EVPMDCtxPointer ctx = EVPMDCtxPointer::New(); - if (!ctx) - return {}; - if (ctx.digestInit(md) != 1) { - return {}; - } - if (ctx.digestUpdate(reinterpret_cast<const Buffer<const void>&>(buf)) != 1) { - return {}; - } - return ctx.digestFinal(output_length); -} - -// ============================================================================ - -size_t Digest::size() const { - if (md_ == nullptr) - return 0; - return EVP_MD_size(md_); -} - -const Digest Digest::MD5 = Digest(EVP_md5()); -const Digest Digest::SHA1 = Digest(EVP_sha1()); -const Digest Digest::SHA256 = Digest(EVP_sha256()); -const Digest Digest::SHA384 = Digest(EVP_sha384()); -const Digest Digest::SHA512 = Digest(EVP_sha512()); - -const Digest Digest::FromName(const char* name) { - return ncrypto::getDigestByName(name); -} - -// ============================================================================ -// KEM Implementation -#if OPENSSL_VERSION_MAJOR >= 3 -#if !OPENSSL_VERSION_PREREQ(3, 5) -bool KEM::SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key) { - const char* operation = nullptr; - - switch (EVP_PKEY_id(key.get())) { - case EVP_PKEY_RSA: - operation = OSSL_KEM_PARAM_OPERATION_RSASVE; - break; -#if OPENSSL_VERSION_PREREQ(3, 2) - case EVP_PKEY_EC: - case EVP_PKEY_X25519: - case EVP_PKEY_X448: - operation = OSSL_KEM_PARAM_OPERATION_DHKEM; - break; -#endif - default: - unreachable(); - } - - if (operation != nullptr) { - OSSL_PARAM params[] = {OSSL_PARAM_utf8_string(OSSL_KEM_PARAM_OPERATION, const_cast<char*>(operation), 0), OSSL_PARAM_END}; - - if (EVP_PKEY_CTX_set_params(ctx, params) <= 0) { - return false; - } - } - - return true; -} -#endif - -std::optional<KEM::EncapsulateResult> KEM::Encapsulate(const EVPKeyPointer& public_key) { - ClearErrorOnReturn clear_error_on_return; - - auto ctx = public_key.newCtx(); - if (!ctx) - return std::nullopt; - - if (EVP_PKEY_encapsulate_init(ctx.get(), nullptr) <= 0) { - return std::nullopt; - } - -#if !OPENSSL_VERSION_PREREQ(3, 5) - if (!SetOperationParameter(ctx.get(), public_key)) { - return std::nullopt; - } -#endif - - // Determine output buffer sizes - size_t ciphertext_len = 0; - size_t shared_key_len = 0; - - if (EVP_PKEY_encapsulate(ctx.get(), nullptr, &ciphertext_len, nullptr, &shared_key_len) <= 0) { - return std::nullopt; - } - - auto ciphertext = DataPointer::Alloc(ciphertext_len); - auto shared_key = DataPointer::Alloc(shared_key_len); - if (!ciphertext || !shared_key) - return std::nullopt; - - if (EVP_PKEY_encapsulate(ctx.get(), static_cast<unsigned char*>(ciphertext.get()), &ciphertext_len, - static_cast<unsigned char*>(shared_key.get()), &shared_key_len) <= 0) { - return std::nullopt; - } - - return EncapsulateResult(std::move(ciphertext), std::move(shared_key)); -} - -DataPointer KEM::Decapsulate(const EVPKeyPointer& private_key, const Buffer<const void>& ciphertext) { - ClearErrorOnReturn clear_error_on_return; - - auto ctx = private_key.newCtx(); - if (!ctx) - return {}; - - if (EVP_PKEY_decapsulate_init(ctx.get(), nullptr) <= 0) { - return {}; - } - -#if !OPENSSL_VERSION_PREREQ(3, 5) - if (!SetOperationParameter(ctx.get(), private_key)) { - return {}; - } -#endif - - // First pass: determine shared secret size - size_t shared_key_len = 0; - if (EVP_PKEY_decapsulate(ctx.get(), nullptr, &shared_key_len, static_cast<const unsigned char*>(ciphertext.data), ciphertext.len) <= 0) { - return {}; - } - - auto shared_key = DataPointer::Alloc(shared_key_len); - if (!shared_key) - return {}; - - if (EVP_PKEY_decapsulate(ctx.get(), static_cast<unsigned char*>(shared_key.get()), &shared_key_len, - static_cast<const unsigned char*>(ciphertext.data), ciphertext.len) <= 0) { - return {}; - } - - return shared_key; -} - -#endif // OPENSSL_VERSION_MAJOR >= 3 - -} // namespace ncrypto - -// =========================================================================== -#if NCRYPTO_BSSL_LIBDECREPIT_MISSING -// While BoringSSL implements EVP_CIPHER_do_all_sorted, it includes this -// inplementation in a library called "libdecrepit", which might not be included -// depending on how boringssl was built. In such cases, a copy of the function -// is provided here: - -extern "C" void EVP_CIPHER_do_all_sorted(void (*callback)(const EVP_CIPHER* cipher, const char* name, const char* unused, void* arg), - void* arg) { - callback(EVP_aes_128_cbc(), "AES-128-CBC", NULL, arg); - callback(EVP_aes_192_cbc(), "AES-192-CBC", NULL, arg); - callback(EVP_aes_256_cbc(), "AES-256-CBC", NULL, arg); - callback(EVP_aes_128_ctr(), "AES-128-CTR", NULL, arg); - callback(EVP_aes_192_ctr(), "AES-192-CTR", NULL, arg); - callback(EVP_aes_256_ctr(), "AES-256-CTR", NULL, arg); - callback(EVP_aes_128_ecb(), "AES-128-ECB", NULL, arg); - callback(EVP_aes_192_ecb(), "AES-192-ECB", NULL, arg); - callback(EVP_aes_256_ecb(), "AES-256-ECB", NULL, arg); - callback(EVP_aes_128_ofb(), "AES-128-OFB", NULL, arg); - callback(EVP_aes_192_ofb(), "AES-192-OFB", NULL, arg); - callback(EVP_aes_256_ofb(), "AES-256-OFB", NULL, arg); - callback(EVP_aes_128_gcm(), "AES-128-GCM", NULL, arg); - callback(EVP_aes_192_gcm(), "AES-192-GCM", NULL, arg); - callback(EVP_aes_256_gcm(), "AES-256-GCM", NULL, arg); - callback(EVP_des_cbc(), "DES-CBC", NULL, arg); - callback(EVP_des_ecb(), "DES-ECB", NULL, arg); - callback(EVP_des_ede(), "DES-EDE", NULL, arg); - callback(EVP_des_ede_cbc(), "DES-EDE-CBC", NULL, arg); - callback(EVP_des_ede3_cbc(), "DES-EDE3-CBC", NULL, arg); - callback(EVP_rc2_cbc(), "RC2-CBC", NULL, arg); - callback(EVP_rc4(), "RC4", NULL, arg); - - // OpenSSL returns everything twice, the second time in lower case. - callback(EVP_aes_128_cbc(), "aes-128-cbc", NULL, arg); - callback(EVP_aes_192_cbc(), "aes-192-cbc", NULL, arg); - callback(EVP_aes_256_cbc(), "aes-256-cbc", NULL, arg); - callback(EVP_aes_128_ctr(), "aes-128-ctr", NULL, arg); - callback(EVP_aes_192_ctr(), "aes-192-ctr", NULL, arg); - callback(EVP_aes_256_ctr(), "aes-256-ctr", NULL, arg); - callback(EVP_aes_128_ecb(), "aes-128-ecb", NULL, arg); - callback(EVP_aes_192_ecb(), "aes-192-ecb", NULL, arg); - callback(EVP_aes_256_ecb(), "aes-256-ecb", NULL, arg); - callback(EVP_aes_128_ofb(), "aes-128-ofb", NULL, arg); - callback(EVP_aes_192_ofb(), "aes-192-ofb", NULL, arg); - callback(EVP_aes_256_ofb(), "aes-256-ofb", NULL, arg); - callback(EVP_aes_128_gcm(), "aes-128-gcm", NULL, arg); - callback(EVP_aes_192_gcm(), "aes-192-gcm", NULL, arg); - callback(EVP_aes_256_gcm(), "aes-256-gcm", NULL, arg); - callback(EVP_des_cbc(), "des-cbc", NULL, arg); - callback(EVP_des_ecb(), "des-ecb", NULL, arg); - callback(EVP_des_ede(), "des-ede", NULL, arg); - callback(EVP_des_ede_cbc(), "des-ede-cbc", NULL, arg); - callback(EVP_des_ede3_cbc(), "des-ede3-cbc", NULL, arg); - callback(EVP_rc2_cbc(), "rc2-cbc", NULL, arg); - callback(EVP_rc4(), "rc4", NULL, arg); -} -#endif From fb6c9eec5bc6f1b463be8b41c5fd22c9dc0d4084 Mon Sep 17 00:00:00 2001 From: Brad Anderson <brad@sankatygroup.com> Date: Mon, 26 Oct 2026 12:28:16 -0400 Subject: [PATCH 5/8] fix: pin one ncrypto compatibility commit on upstream Keep the fork main identical to upstream and carry RNQC compatibility on a separate single-commit branch. Cover explicit EC parameter export and record linear-history and fork maintenance rules. --- .agents/rules/architecture.md | 7 +++++++ .agents/rules/git-safety.md | 1 + AGENTS.md | 1 + example/src/fixtures/keys/ec_explicit_oakley.ts | 17 +++++++++++++++++ example/src/tests/keys/create_keys.ts | 17 +++++++++++++++++ packages/react-native-quick-crypto/deps/ncrypto | 2 +- 6 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 example/src/fixtures/keys/ec_explicit_oakley.ts diff --git a/.agents/rules/architecture.md b/.agents/rules/architecture.md index 6318721d8..f6117277c 100644 --- a/.agents/rules/architecture.md +++ b/.agents/rules/architecture.md @@ -21,6 +21,13 @@ Always on. - Avoid comments unless the code is complex enough to need them. - Tests run in the example React Native app, not a standard Node.js runner. +## ncrypto fork maintenance + +- Keep ncrypto as a Git submodule pointing to `boorad/ncrypto`. +- Keep the fork's `main` identical to `nodejs/ncrypto:main`. +- Maintain RNQC's compatibility changes as one commit on a separate branch based on upstream `main`; pin that commit in RNQC. +- Do not merge RNQC's compatibility branch into the fork's mirrored `main`. Preserve a backup ref before rewriting published history. + ## References - `$REPOS/node`: Node.js crypto/subtle reference. diff --git a/.agents/rules/git-safety.md b/.agents/rules/git-safety.md index 1c271dc77..4d816fe13 100644 --- a/.agents/rules/git-safety.md +++ b/.agents/rules/git-safety.md @@ -7,6 +7,7 @@ - If hooks fail, fix the underlying issue. - Use a 120000ms timeout for `git commit`; hooks run lint-staged, clang-format, tsc, and bob build. - Never commit on `main`. +- Prefer linear history: rebase feature branches and use squash or fast-forward integration. Do not create merge commits unless the user explicitly requests them. - Before committing, check the current branch. - If on `main`, create `feat/`, `fix/`, or `refactor/` branch first. diff --git a/AGENTS.md b/AGENTS.md index bc7e72035..91a02b35c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,7 @@ Always inspect Node.js `deps/ncrypto` before implementing new crypto behavior, t - Never use `--no-verify` for commits or pushes. - Preserve unrelated working-tree changes and stage task files explicitly. - All changes land through pull requests. +- Prefer linear history. Rebase feature branches and use squash or fast-forward integration; do not create merge commits unless explicitly requested. If rewriting a dependency commit changes its SHA, update its downstream pins. - `/implement` is explicitly authorized to push a qualified branch and create or update its PR. `/pr` is explicitly authorized to make the qualified push needed to create or update the PR. Standalone `/commit` never pushes implicitly. ## Plans diff --git a/example/src/fixtures/keys/ec_explicit_oakley.ts b/example/src/fixtures/keys/ec_explicit_oakley.ts new file mode 100644 index 000000000..0c2e54f23 --- /dev/null +++ b/example/src/fixtures/keys/ec_explicit_oakley.ts @@ -0,0 +1,17 @@ +// Generated with OpenSSL 3.6.2 using `openssl ecparam -param_enc explicit` +// followed by `openssl pkey -pubout -outform DER`. These curves are the +// no-OID cases covered by Node.js test/parallel/test-crypto-keygen-missing-oid.js. +export const explicitOakleySpkiFixtures = [ + { + namedCurve: 'Oakley-EC2N-3', + spkiHex: + '3081cf3081a006072a8648ce3d0201308194020101301d06072a8648ce3d010230120202009b06092a8648ce3d0102030202013e302c041400000000000000000000000000000000000000000414000000000000000000000000000000000007338f042904000000000000000000000000000000000000007b00000000000000000000000000000000000001c8021402aaaaaaaaaaaaaaaaaac7f3c7881bd0868fa86c020103032a0004058af006890627abd13cc38f768f2a564a835f9104f6a17ab00869e638e91b8aa84d11581c7eae5a', + spkiLength: 210, + }, + { + namedCurve: 'Oakley-EC2N-4', + spkiHex: + '3081eb3081b406072a8648ce3d02013081a8020101301d06072a8648ce3d01023012020200b906092a8648ce3d01020302020145303404180000000000000000000000000000000000000000000000000418000000000000000000000000000000000000000000001ee904310400000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000d021800ffffffffffffffffffffffedf97c44db9f2420bafca75e02010203320004005401a9ba6b63deb137dbec67550ebbf8aa49426749dde600584de3e879e46f9653447922b4a266be0356d1fe5bde92', + spkiLength: 238, + }, +] as const; diff --git a/example/src/tests/keys/create_keys.ts b/example/src/tests/keys/create_keys.ts index d44f033ae..df7278aea 100644 --- a/example/src/tests/keys/create_keys.ts +++ b/example/src/tests/keys/create_keys.ts @@ -10,6 +10,7 @@ import { } from 'react-native-quick-crypto'; import type { JWK, KeyObject } from 'react-native-quick-crypto'; import { expect } from 'chai'; +import { explicitOakleySpkiFixtures } from '../../fixtures/keys/ec_explicit_oakley'; import { test, assertThrowsAsync, decodeHex } from '../util'; import { rsaPrivateKeyPem, @@ -208,6 +209,22 @@ test(SUITE, 'createPublicKey EC P-256', async () => { expect(key.asymmetricKeyType).to.equal('ec'); }); +test(SUITE, 'exports explicit EC parameters without a curve OID', () => { + for (const { + namedCurve, + spkiHex, + spkiLength, + } of explicitOakleySpkiFixtures) { + const fixture = Buffer.from(spkiHex, 'hex'); + const key = createPublicKey({ key: fixture, format: 'der', type: 'spki' }); + const exported = key.export({ format: 'der', type: 'spki' }) as Buffer; + + expect(key.asymmetricKeyType, namedCurve).to.equal('ec'); + expect(exported.length, namedCurve).to.equal(spkiLength); + expect(Buffer.compare(exported, fixture), namedCurve).to.equal(0); + } +}); + test(SUITE, 'createPublicKey Ed25519', async () => { const { publicKey } = await new Promise<{ privateKey: string; diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto index 1d46de3e3..c24987b0d 160000 --- a/packages/react-native-quick-crypto/deps/ncrypto +++ b/packages/react-native-quick-crypto/deps/ncrypto @@ -1 +1 @@ -Subproject commit 1d46de3e39c471dfa16c4e9db5b85a71c2e4c46d +Subproject commit c24987b0db08c2a966d3d954d682551cf9e846c2 From ce0f69c49e8d032b76e6c954cb176a94e8553dd8 Mon Sep 17 00:00:00 2001 From: Brad Anderson <brad@sankatygroup.com> Date: Mon, 26 Oct 2026 12:42:10 -0400 Subject: [PATCH 6/8] docs: align agent workflows with local E2E attestations Keep the local runner introduced in #1083, verify default-branch trust inputs before signing or uploads, and finish all commits before final-head qualification. Refresh the CocoaPods checksum for the updated source list. --- .agents/agents/app-debug-specialist.md | 85 ++++++++++--------------- .agents/agents/orchestrator.md | 4 +- .agents/agents/testing-specialist.md | 8 +-- .agents/commands/address-pr-feedback.md | 2 + .agents/commands/commit.md | 2 +- .agents/commands/handoff.md | 2 +- .agents/commands/implement.md | 5 +- .agents/commands/pr.md | 15 ++++- .agents/commands/review.md | 4 +- .agents/rules/architecture.md | 2 +- .agents/rules/ci-caching.md | 7 +- .agents/rules/test-verification.md | 14 +++- AGENTS.md | 7 +- docs/local-e2e.md | 5 +- example/ios/Podfile.lock | 2 +- 15 files changed, 84 insertions(+), 80 deletions(-) diff --git a/.agents/agents/app-debug-specialist.md b/.agents/agents/app-debug-specialist.md index 3cc83d1fd..d4c6847c2 100644 --- a/.agents/agents/app-debug-specialist.md +++ b/.agents/agents/app-debug-specialist.md @@ -5,43 +5,44 @@ ## Responsibilities ### Test & Debug Workflow -- Run Maestro tests and capture iOS simulator logs +- Run the repository's app tests and capture simulator or emulator logs - Parse and analyze console output for specific issues - Set up automated logging with react-native-logs -- Manage Metro bundler lifecycle (start, restart, monitor) +- Respect the distinction between targeted interactive debugging and the self-contained canonical E2E runner - Coordinate test runs with log capture ### Log Management - Capture iOS simulator logs: `xcrun simctl spawn booted log stream --predicate 'processImagePath endswith "QuickCryptoExample"' --level debug` - Filter logs for relevant patterns - Save logs to `/tmp/rnqc-session.log` for analysis -- Monitor Metro bundler output at `/tmp/metro.log` +- Monitor interactive Metro client output at `/tmp/rnqc-metro.log` ### Iteration Speed Tools -- Keep Metro running in background (PID in `/tmp/metro.pid`) -- Reload app without full rebuild when possible -- Use Maestro for automated UI testing -- Chain commands efficiently (rebuild TS → rebuild iOS → run test → capture logs) +- Attach to an existing RNQC Metro process for targeted debugging without restarting another project or taking over its port +- Reload the app without a full rebuild when possible +- Use the canonical runner for full-app automated qualification +- Chain targeted commands efficiently without overlapping runner-owned app, device, or Metro resources ## Key Scripts -### Debug Test Runner +### Canonical E2E Runner ```bash -./scripts/debug-test.sh [test-flow] [--rebuild-ts] +bun run e2e:ios +bun run e2e:android ``` +Run these serially from the repository root. The workspace wrappers invoke `example/test/e2e/runner.mjs`, which selects the configured platform target and owns its RNQC app, simulator or emulator, isolated Metro port, artifacts, and cleanup. Follow `docs/local-e2e.md` when signed qualification is required. + ### Manual Workflow ```bash -# 1. Ensure Metro is running -bun start > /tmp/metro.log 2>&1 & echo $! > /tmp/metro.pid +# 1. Attach to the existing RNQC app and Metro; do not restart another project's process # 2. Capture logs xcrun simctl spawn booted log stream \ --predicate 'processImagePath endswith "QuickCryptoExample"' \ --level debug > /tmp/rnqc-session.log 2>&1 & LOG_PID=$! -# 3. Run test -cd example && maestro test test/e2e/import-export-local.yml +# 3. Drive the relevant flow in the RNQC example app # 4. Stop log capture and view kill $LOG_PID @@ -53,20 +54,18 @@ grep -E "pattern" /tmp/rnqc-session.log ### Rebuild & Test Cycle ```bash # Full rebuild (TypeScript + iOS) -cd packages/react-native-quick-crypto && npm run prepare +cd packages/react-native-quick-crypto && bun run prepare cd ../../example && bun ios -# Then run debug test -./scripts/debug-test.sh +# Then drive the affected RNQC example-app flow ``` ### TypeScript-only Changes ```bash # Rebuild TypeScript -cd packages/react-native-quick-crypto && npm run prepare +cd packages/react-native-quick-crypto && bun run prepare -# Metro will auto-reload, or manually restart it -pkill -P $(cat /tmp/metro.pid) && bun start & echo $! > /tmp/metro.pid +# The existing RNQC Metro process should reload the bundle; do not take over its port ``` ### C++ Changes @@ -92,53 +91,33 @@ grep -E "asymmetricKeyDetails|keyDetail|rsaImportKey" /tmp/rnqc-session.log tail -f /tmp/rnqc-session.log ``` -## Metro Management - -### Check if Running -```bash -[ -f /tmp/metro.pid ] && ps -p $(cat /tmp/metro.pid) && echo "Running" || echo "Not running" -``` - -### Start Metro -```bash -cd example && bun start > /tmp/metro.log 2>&1 & echo $! > /tmp/metro.pid -``` +## Metro Diagnostics -### Stop Metro -```bash -kill $(cat /tmp/metro.pid) 2>/dev/null && rm /tmp/metro.pid -``` +For interactive debugging, attach to the existing RNQC process. Never kill or restart another project's Metro or claim its port. The canonical E2E runner starts and cleans up its own isolated Metro process. -### View Metro Logs +### View RNQC Metro Logs ```bash -tail -f /tmp/metro.log +tail -f /tmp/rnqc-metro.log ``` -## Maestro Tests +## Full-App Tests -### Available Flows -- `test/e2e/import-export-local.yml` - Just the importKey/exportKey suite -- `test/e2e/test-suites-flow.yml` - Full test suite - -### Run Specific Test -```bash -cd example && maestro test test/e2e/import-export-local.yml -``` +Use `bun run e2e:ios` followed by `bun run e2e:android` from the repository root. Do not substitute removed Maestro flows. For narrower debugging, drive the relevant existing example-app test path and record exactly what was exercised. ## Debugging Tips -1. **Always keep Metro running** - Don't kill it between test runs -2. **TypeScript changes** - Require Metro reload, not full rebuild -3. **C++ changes** - Require full iOS rebuild -4. **Log capture timing** - Start before test, stop 3-5s after test completes -5. **Check PID files** - Metro and log capture PIDs in `/tmp/` +1. **Respect process ownership** - Attach for interactive work; let the canonical runner own and clean up its resources +2. **TypeScript changes** - Usually require Metro reload, not a full native rebuild +3. **C++ changes** - Require a native rebuild +4. **Log capture timing** - Start before the targeted flow and stop after the relevant output is complete +5. **Platform target** - Verify the runner or interactive session is using the intended RNQC simulator or emulator ## Files to Monitor - `/tmp/rnqc-session.log` - iOS simulator logs -- `/tmp/metro.log` - Metro bundler output -- `/tmp/metro.pid` - Metro process ID -- `example/test/e2e/*.yml` - Maestro test flows +- `/tmp/rnqc-metro.log` - Interactive RNQC Metro client output +- `example/build/e2e/<platform>/<run-id>/` - Canonical runner results, screenshots, and logs +- `example/test/e2e/runner.mjs` - Canonical full-app runner ## Integration with Main Workflow diff --git a/.agents/agents/orchestrator.md b/.agents/agents/orchestrator.md index 7a13fb65d..ccd9523aa 100644 --- a/.agents/agents/orchestrator.md +++ b/.agents/agents/orchestrator.md @@ -56,11 +56,13 @@ Run the package Jest script only for actual Node-side changes: `cd packages/reac Documentation-only work needs path, link, command, and consistency validation rather than runtime tests. +When the native merge gate applies, use the canonical root `bun run e2e:ios` then `bun run e2e:android` recipe and attestation workflow in `docs/local-e2e.md`. The producer owns that serial run, so do not schedule a needless duplicate suite immediately beforehand. Raw evidence can support review, but final delivery requires the trusted pinned patched producer to sign the exact clean committed HEAD after plan completion and all fixes; posting waits until the remote PR head matches. Keep AgentSCM coordination availability distinct from the local attestation producer. + ## Review and delivery Use a fresh independent reviewer for the complete `origin/main...HEAD` diff and uncommitted work. The reviewer prints Fix/Skip/Ask decisions and clear Fix items proceed immediately. Local review never waits for a bot. -Before PR delivery, verify commits, clean status, scoped evidence, and any diff-changing runtime behavior. Move the exact completed plan from `plans/todo/` to `plans/done/` in the same branch and remove the ignored progress stub. Then use `/pr` to push and create or update the PR. +Before PR delivery, verify commits, clean status, scoped evidence, and any diff-changing runtime behavior. Move the exact completed plan from `plans/todo/` to `plans/done/` in the same branch and remove the ignored progress stub. Commit and complete static review before final native attestation. Then use `/pr` to push, create or update the PR, and post authorized attestation evidence for the matching remote SHA. ## Final report diff --git a/.agents/agents/testing-specialist.md b/.agents/agents/testing-specialist.md index 41a787053..44f59acd8 100644 --- a/.agents/agents/testing-specialist.md +++ b/.agents/agents/testing-specialist.md @@ -346,12 +346,6 @@ You work closely with: - Performance characteristics differ - No access to Node.js-specific APIs -**Don't assume you can run tests** - your job is to: -1. Design comprehensive test strategies -2. Identify test cases and edge cases -3. Provide test vectors and expected outputs -4. Document testing methodology - -The actual test execution happens in the example React Native app. +Agents may execute tests in the example React Native app; no separate human-only permission round is required. For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root and follow `docs/local-e2e.md` when an attestation is required. Continue to design comprehensive strategies, identify edge cases, provide authoritative vectors and expected outputs, and document exactly what was exercised. Remember: Comprehensive testing is the last line of defense against bugs. Be thorough, be creative in finding edge cases, and always validate against authoritative sources. diff --git a/.agents/commands/address-pr-feedback.md b/.agents/commands/address-pr-feedback.md index dd974d70b..065e6d262 100644 --- a/.agents/commands/address-pr-feedback.md +++ b/.agents/commands/address-pr-feedback.md @@ -115,6 +115,8 @@ test "$LOCAL_SHA" = "$REMOTE_SHA" test "$LOCAL_SHA" = "$PR_SHA" ``` +If the native merge gate applies and feedback changed HEAD, the old receipt is not current. After every fix and documentation or plan commit is final, follow `docs/local-e2e.md` to attest the exact clean committed HEAD with the trusted inputs and pinned patched producer, verify the remote PR head equals the signed SHA, and post through the documented CLI. Do not fabricate evidence from earlier logs or manually post the status. Reuse a still-valid receipt after an unrelated base fast-forward only when its bound merge-base and other context are unchanged. + If no code or documentation changed because every item is Dismiss or Stale, skip commit and push, use the current PR head SHA, and proceed to replies. ## 6. Reply after verification diff --git a/.agents/commands/commit.md b/.agents/commands/commit.md index f747cb5ad..64af80551 100644 --- a/.agents/commands/commit.md +++ b/.agents/commands/commit.md @@ -37,7 +37,7 @@ Format and verify what the commit changes: - TypeScript API or implementation: run the relevant `bun tsc`. - Node-side behavior: run `cd packages/react-native-quick-crypto && bun run test` only when actual Node-side code changed. - ncrypto/OpenSSL changes: run `scripts/check-ncrypto-openssl-deprecations.sh` and other affected native checks. -- Documentation-only changes: run link/path/command consistency checks and `git diff --check`; no runtime test is required. +- Documentation-only changes: run link/path/command consistency checks and `git diff --check`; no runtime test is required. If this commit follows a native attestation, note that delivery needs a new receipt for the new final HEAD rather than treating the prior receipt as current. Reuse current evidence when it covers the staged diff. Do not run a broad suite by default. diff --git a/.agents/commands/handoff.md b/.agents/commands/handoff.md index d660b61ed..ded3b8c51 100644 --- a/.agents/commands/handoff.md +++ b/.agents/commands/handoff.md @@ -21,7 +21,7 @@ Include only relevant sections: - **State:** branch, HEAD SHA, clean or exact uncommitted paths, issue, PR URL/state/head SHA, and active plan phase. - **Completed:** concrete work with commit SHAs or file paths. -- **Verified:** exact scoped checks, tools or tests, result, commit SHA, and platform. Distinguish native build, installed-app, simulator/device, Node-side, and documentation evidence. +- **Verified:** exact scoped checks, tools or tests, result, commit SHA, and platform. Distinguish native build, installed-app, simulator/device, Node-side, documentation evidence, raw E2E results, and a final signed attestation. For attestation, include the bound SHA and whether the remote PR head matched and posting completed; do not imply GitHub ran the mobile suites. - **Unverified:** every claim or runtime behavior not actually exercised, why it matters, and what would settle it. - **Decisions:** non-obvious choices and rationale. - **Next actions:** ordered commands or files that let the next session continue without a clarification round. diff --git a/.agents/commands/implement.md b/.agents/commands/implement.md index 81dc965ea..32deef541 100644 --- a/.agents/commands/implement.md +++ b/.agents/commands/implement.md @@ -103,6 +103,7 @@ Select checks from the actual diff and reuse valid phase evidence keyed by SHA, - Build and install the example app when a native change requires a rebuild. Drive the affected tests or flow when feasible and record the platform. - Do not rerun broad suites per phase. A full foundational shared-crypto suite requires a stated cross-cutting reason or unexplained failure, one owner, and one reusable result. - Documentation-only changes need link and consistency checks, not a runtime retest. +- When full native qualification is required, preserve still-current targeted evidence but leave the canonical serial iOS-then-Android run to the attestation producer described in `docs/local-e2e.md`; do not run a duplicate broad suite immediately before it. A missing credential, unavailable platform, or unverified behavior blocks delivery only when a failure could require changing the diff. Stop and state the exact check needed. If the user explicitly directs shipment, disclose the unverified behavior and residual risk in the PR. @@ -128,9 +129,11 @@ rm -f .agents/progress/claude-progress.md Carry any genuinely outstanding verification item with an owner and disclosure. Commit the plan move before opening the PR. If more than one plan could match, move none and stop for disambiguation. Work that is not implemented remains in `plans/todo/`. +Finish this lifecycle before signing native qualification evidence. After the plan move and every documentation or review-fix commit, confirm the final SHA and clean tree, complete static review, then use `/pr` for push, final attestation, and posting. Do not discard a valid receipt merely because `main` fast-forwarded when its bound merge-base and other context are unchanged. + ## 9. Finish with /pr -Read and execute `.agents/commands/pr.md` completely. Recompute scope, verification, and delivery from the actual diff rather than recon. Use `Closes #<N>`, push the qualified commits, reuse an existing PR for the branch when present, and create one otherwise. +Read and execute `.agents/commands/pr.md` completely. Recompute scope, verification, and delivery from the actual diff rather than recon. Use `Closes #<N>`, push the qualified commits, reuse an existing PR for the branch when present, and create one otherwise. When the native gate applies, the final signed evidence must bind the exact delivered HEAD and be posted only after the remote PR head matches that SHA. If the host exposes a PR-link registration tool, register the full PR URL with the current thread immediately after creating or taking ownership of the PR. diff --git a/.agents/commands/pr.md b/.agents/commands/pr.md index 71cd46347..7b14e7971 100644 --- a/.agents/commands/pr.md +++ b/.agents/commands/pr.md @@ -26,6 +26,7 @@ Review current evidence for the actual HEAD and every changed toolchain. A quali - Native behavior built and exercised on the relevant platform when the diff requires it. - No unverified runtime behavior that could change the diff, unless the user explicitly directed shipment and the PR discloses the gap and risk. - An independent local review completed without waiting for a bot. +- When the native merge gate applies, final attestation is still pending until it binds the final committed HEAD; earlier raw E2E evidence may support review but does not replace that receipt. Do not rerun still-current broad evidence merely to open the PR. @@ -88,6 +89,16 @@ gh pr create --title "<title>" --body-file <body-file> --base main --assignee @m Use a conventional-commit-style title unless the user supplied one. -### 7. Register and report +### 7. Complete attested native qualification when required -Immediately register the full PR URL with the host thread when a PR-link tool is available. Report the URL, pushed SHA, qualification evidence, and any disclosed unverified behavior. +Follow `docs/local-e2e.md` rather than duplicating its commands. Use the trusted recipe, policy, and registry from `main` with the documented pinned, patched AgentSCM producer on reviewed code only. The checkout must be clean and the attestation must bind the exact final committed HEAD after the plan move, documentation commits, and all fixes. Keep the private key and state owner-private outside the checkout and never read or print secrets. + +Before signing or publishing screenshot evidence, fetch `origin/main` and run `git diff --exit-code origin/main -- .github/local-validation/recipe.json .github/local-validation/policy.json .github/local-validation/registry.json`. Stop if any differ: checkout-relative inputs are trusted only after this check. A PR changing the trust inputs must first get those changes reviewed and landed through the trusted default-branch process. + +The qualified push may happen before or after the local run, but before posting verify that local HEAD, the remote branch, and the pull request head all equal the signed SHA. Use the documented `local-validation post` command when this workflow or the user authorizes posting; never fabricate a receipt from logs or raw test results and never post the status manually. Screenshot posting is a separate, explicit action and is required only when authorized and material. + +Do not run a duplicate broad suite immediately before the producer: its trusted recipe already owns the serial `bun run e2e:ios` then `bun run e2e:android` run. A valid receipt remains usable across an unrelated base fast-forward when its bound merge-base and other context are unchanged. Describe `agentscm/local-validation` as worker-asserted coverage with the limitations in `docs/local-e2e.md`, not as GitHub-run mobile testing or a currently enforced required check unless the live ruleset was verified. + +### 8. Register and report + +Immediately register the full PR URL with the host thread when a PR-link tool is available. Report the URL, pushed SHA, qualification evidence, signed SHA and posting result when applicable, and any disclosed unverified behavior. diff --git a/.agents/commands/review.md b/.agents/commands/review.md index ef41ecf9c..a867491fd 100644 --- a/.agents/commands/review.md +++ b/.agents/commands/review.md @@ -50,11 +50,13 @@ Reuse evidence only when it names the commit SHA, exact tool or test, result, an - C++: `clang-format --dry-run --Werror` over the changed native scope plus relevant compile or OpenSSL checks. - ncrypto/OpenSSL: `scripts/check-ncrypto-openssl-deprecations.sh` when applicable. - Node-side code: `cd packages/react-native-quick-crypto && bun run test`. Run this only for actual Node-side changes; never use bare `bun test` as a substitute. -- Native runtime: build, install, and exercise the affected example-app behavior on the relevant iOS or Android platform when feasible. Attach to an existing RNQC app and Metro first and use `/tmp/rnqc-metro.log`. +- Native runtime: build, install, and exercise the affected example-app behavior on the relevant iOS or Android platform when feasible. For targeted debugging, attach to an existing RNQC app and Metro first and use `/tmp/rnqc-metro.log`. For canonical full-app coverage, use the root `bun run e2e:ios` then `bun run e2e:android` flow documented in `docs/local-e2e.md`; its runner owns the app, device, isolated Metro port, and cleanup. - Docs-only: validate links, paths, command names, and repository claims; do not rerun runtime suites. Do not repeat a broad suite merely because review started. A full foundational shared-crypto suite needs a stated cross-cutting reason or concrete unexplained failure, one owner, and a reusable result. +Review may reuse current raw E2E evidence even before final attestation. Do not treat logs or raw results as a signed merge-gate receipt. After all review fixes and documentation or plan commits, delivery must attest the exact final clean committed HEAD with the trusted inputs and pinned patched producer described in `docs/local-e2e.md`. Do not claim GitHub ran the device suites or that the status context is currently required unless live ruleset verification proves it. + ### 4. Report findings Return: diff --git a/.agents/rules/architecture.md b/.agents/rules/architecture.md index f6117277c..f3e5d81ec 100644 --- a/.agents/rules/architecture.md +++ b/.agents/rules/architecture.md @@ -33,7 +33,7 @@ Always on. - `$REPOS/node`: Node.js crypto/subtle reference. - `$REPOS/ncrypto`: OpenSSL abstraction and Node-derived crypto utilities. - `$REPOS/nitro`: Nitro bridging examples and iOS CI caching. -- `$REPOS/spicy`: Android E2E and Maestro workflow examples. +- `$REPOS/spicy`: shared agent-workflow and Android E2E patterns only; RNQC's canonical runner remains the repository-local flow documented in `docs/local-e2e.md`. - Use local Nitro llms docs when available. ## Output diff --git a/.agents/rules/ci-caching.md b/.agents/rules/ci-caching.md index d78d8414b..6aaa7994c 100644 --- a/.agents/rules/ci-caching.md +++ b/.agents/rules/ci-caching.md @@ -5,7 +5,7 @@ Use when editing GitHub Actions or CI caching. ## References - `$REPOS/nitro`: fast iOS build caching, especially `.github/workflows/build-ios.yml`. -- `$REPOS/spicy`: Android E2E and Maestro patterns. +- `$REPOS/spicy`: historical Android E2E and caching patterns only; do not replace RNQC's repository-local runner or import Spicy services and scripts. ## Blocking @@ -30,11 +30,6 @@ Pods: runner.os-pods-${{ hashFiles('example/ios/Podfile.lock', 'example/Gemfile. DD: runner.os-dd-${{ hashFiles('...lockfiles...') }}-xcode26.2 ``` -## Android Maestro - -- Do not launch the app with `adb` before Maestro. -- Install the APK, then let Maestro run `launchApp`. - ## Debugging ```bash diff --git a/.agents/rules/test-verification.md b/.agents/rules/test-verification.md index f53218e40..66adf9851 100644 --- a/.agents/rules/test-verification.md +++ b/.agents/rules/test-verification.md @@ -26,7 +26,9 @@ Do not routinely run every test suite after each phase, commit, review, or docum Agents may run native builds, simulators or devices, app tests, and driven verification. A genuinely current successful result qualifies without a separate user passphrase or approval round. -Attach to an existing RNQC app and Metro first. Do not restart or kill another project's process and do not take over its port. If a native change requires rebuilding, use the example app's real scripts, such as `cd example && bun ios`, `bun android`, `bun run build:ios`, or `bun run build:android`, then run the relevant app flow. Full Maestro runners are `example/test/e2e/run-ios.sh` and `example/test/e2e/run-android.sh` when full-app coverage is justified. +For targeted interactive work, attach to an existing RNQC app and Metro first. Do not restart or kill another project's process and do not take over its port. If a native change requires rebuilding, use the example app's real scripts, such as `cd example && bun ios`, `bun android`, `bun run build:ios`, or `bun run build:android`, then run the relevant app flow. + +For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root. The wrappers invoke `example/test/e2e/runner.mjs`, which selects the configured platform target, creates and owns its RNQC simulator or emulator, uses an isolated Metro port, writes per-run evidence, and cleans up its resources. Do not point it at another project's app, reuse an overlapping server, or substitute a Maestro flow. RNQC Metro client logs are tee'd to `/tmp/rnqc-metro.log`. Diagnose failures with: @@ -39,3 +41,13 @@ grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20 Unverified runtime behavior blocks push or PR delivery when failure could require changing the diff. Missing credentials, unavailable hardware, or irreversible external actions qualify only when they affect that decision. The user may explicitly direct shipment despite a gap. In that case, disclose the exact unverified behavior, affected platform, and residual risk in the handoff and PR. Do not describe it as passing. + +## Attested native qualification + +When the native merge gate applies, `docs/local-e2e.md` is canonical. Produce the final attestation with the trusted recipe, policy, and registry from `main` and the documented pinned, patched AgentSCM build, not an arbitrary release binary. The signing key and state stay owner-private and outside the checkout; never read or print secrets. + +Raw platform evidence may remain useful through review while no relevant edit invalidates it, but it is not the delivery attestation. The final attestation must cover the exact clean committed HEAD after every plan move, documentation commit, and fix, binding its tree, base ref, and merge-base. A later base fast-forward alone does not invalidate a receipt when the bound merge-base and other context remain unchanged. + +The producer owns one serial iOS-then-Android recipe run; do not add a duplicate broad suite immediately beforehand. Never create an attestation from logs or raw test output, never post a status manually, and post the actual attestation only through the documented CLI when the active workflow or user authorizes posting. Before posting, verify the pull request remote head equals the signed SHA. Screenshot publication is separate and requires explicit authorization when it is material. + +`agentscm/local-validation` represents a signed AgentSCM `worker_asserted` record with the coverage and limitations documented in `docs/local-e2e.md`; it does not mean GitHub ran the mobile suites. Do not claim the context is enforced by branch protection unless the live ruleset has been verified; the documented rollout says it is not yet required. diff --git a/AGENTS.md b/AGENTS.md index 91a02b35c..c634c32ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,10 @@ Before opening a PR for completed planned work, move the one exact matching plan - Run the package Jest suite only for actual Node-side code changes: `cd packages/react-native-quick-crypto && bun run test`. Bare `bun test` invokes Bun's test runner and is not this package's Jest script. - C++ changes use formatting plus the relevant native/compiler checks, including `scripts/check-ncrypto-openssl-deprecations.sh` when ncrypto/OpenSSL compatibility is in scope. - Native runtime behavior is tested in the example React Native app. Agents may build, install, drive, and test the app; user confirmation is not inherently required when current successful evidence is available. -- Attach to the existing RNQC app and Metro process first. Do not restart another project's process or take over its port. Metro client logs belong at `/tmp/rnqc-metro.log`; inspect them with `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` when diagnosing failures. +- For targeted interactive debugging, attach to the existing RNQC app and Metro process first. Do not restart another project's process or take over its port. Metro client logs belong at `/tmp/rnqc-metro.log`; inspect them with `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` when diagnosing failures. +- For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root. The runner owns its RNQC app, simulator or emulator, isolated Metro port, artifacts, and cleanup; do not substitute another project's app or an overlapping manually managed server. +- When the native merge gate applies, follow `docs/local-e2e.md`: use the trusted recipe, policy, and registry from `main` with the pinned patched AgentSCM producer; sign the exact clean committed HEAD, tree, base ref, and merge-base with owner-private key and state outside the checkout. Never fabricate an attestation from logs or raw test results and never post the status manually. +- Reuse still-current raw evidence during implementation and review, but the final delivery attestation must bind the final committed HEAD after plan moves, documentation commits, review fixes, and other changes. Its `agentscm/local-validation` context is worker-asserted evidence, not a claim that GitHub ran the mobile suites, and it is not currently a required branch-protection check unless live settings are separately verified. - Pure documentation, plan, and `.agents/` changes do not require runtime retesting. - Unverified runtime behavior that could change the diff blocks push/PR delivery unless the user explicitly directs shipment; disclose the unverified behavior and residual risk when they do. @@ -94,7 +97,7 @@ Useful scripts and flows include: - Node-side Jest: `cd packages/react-native-quick-crypto && bun run test`. - Example app: `cd example && bun ios` or `bun android`. - Explicit native builds: `cd example && bun run build:ios` or `bun run build:android`. -- Full app E2E when justified: `example/test/e2e/run-ios.sh`, `example/test/e2e/run-android.sh`, or the CI Maestro flow in `example/test/e2e/test-suites-flow.yml`. +- Full app E2E when justified: from the repository root run `bun run e2e:ios` and then `bun run e2e:android`; the workspace wrappers invoke the Node runner. See `docs/local-e2e.md` for attested qualification and its coverage limits. ## Local references diff --git a/docs/local-e2e.md b/docs/local-e2e.md index ee2a11259..9f0b6e47e 100644 --- a/docs/local-e2e.md +++ b/docs/local-e2e.md @@ -73,6 +73,7 @@ Run only reviewed code on the signing host. The private key and state directory ```bash git fetch origin main git status --short +git diff --exit-code origin/main -- .github/local-validation/recipe.json .github/local-validation/policy.json .github/local-validation/registry.json mkdir -m 700 /absolute/private/path/rnqc-attestations /tmp/rnqc-agentscm-24b70c0 local-validation run \ @@ -87,7 +88,7 @@ mkdir -m 700 /absolute/private/path/rnqc-attestations --base-rev origin/main ``` -`git status --short` must print nothing before `run`. Save the `envelope_sha256` from its JSON output as `ATTESTATION`. AgentSCM retains the signed envelope, record and two commands' stdout/stderr under the state directory. A successful run contains both results; a failed iOS command intentionally omits Android and verifies as failure. +`git status --short` must print nothing before `run`, and the trust-input comparison must exit successfully. Checkout-relative recipe, policy, and registry paths are safe here only because they exactly match fetched `origin/main`. If the PR changes those inputs, stop; their trusted default-branch update must be reviewed and landed first. Save the `envelope_sha256` from its JSON output as `ATTESTATION`. AgentSCM retains the signed envelope, record and two commands' stdout/stderr under the state directory. A successful run contains both results; a failed iOS command intentionally omits Android and verifies as failure. Create an owner-private, single-line GitHub token file with permission to read the pull request and write its comments, then explicitly post the attestation: @@ -106,7 +107,7 @@ Create an owner-private, single-line GitHub token file with permission to read t Screenshot posting is separate because AgentSCM `local-validation post` carries only the signed envelope and record. The helper uploads to ImgBB using the same 30-day expiry as the removed hosted-E2E action and creates or updates one PR comment bound to the PR head and attestation digest. It does nothing without the explicit `--post` flag. -Use the two run directories printed by the E2E runner: +Before uploading, repeat the fetch and trust-input comparison above; stop on any mismatch. The helper reads checkout-relative trust inputs, so this check is required even when reusing an existing attestation. Use the two run directories printed by the E2E runner: ```bash ./scripts/local-validation/post-screenshots.sh \ diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 4373aca29..190c0c87d 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -2837,7 +2837,7 @@ SPEC CHECKSUMS: MMKVCore: f2dd4c9befea04277a55e84e7812f930537993df NitroMmkv: afbc5b2fbf963be567c6c545aa1efcf6a9cec68e NitroModules: 11bba9d065af151eae51e38a6425e04c3b223ff3 - QuickCrypto: 34c79e9b554ac964e4ebc42e3190abfa99099a40 + QuickCrypto: 7d3fed653542fb138b2bc555896e428357f4155a RCT-Folly: 846fda9475e61ec7bcbf8a3fe81edfcaeb090669 RCTDeprecation: c4b9e2fd0ab200e3af72b013ed6113187c607077 RCTRequired: e97dd5dafc1db8094e63bc5031e0371f092ae92a From d11ff58b39d832b0c4fd75e0b8ce7a4baa9518fa Mon Sep 17 00:00:00 2001 From: Brad Anderson <brad@sankatygroup.com> Date: Mon, 26 Oct 2026 13:31:07 -0400 Subject: [PATCH 7/8] fix: preserve upstream ncrypto with an opt-in EVP profile Replace the reduced fork with a focused default-off profile, retain all upstream APIs and infrastructure, and enable the profile consistently in RNQC native builds and the compiler gate. --- example/ios/Podfile.lock | 2 +- packages/react-native-quick-crypto/QuickCrypto.podspec | 9 ++++----- .../react-native-quick-crypto/android/CMakeLists.txt | 3 +++ packages/react-native-quick-crypto/deps/ncrypto | 2 +- packages/react-native-quick-crypto/package.json | 1 + scripts/check-ncrypto-openssl-deprecations.sh | 3 +++ 6 files changed, 13 insertions(+), 7 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 190c0c87d..06ee2a2df 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -2837,7 +2837,7 @@ SPEC CHECKSUMS: MMKVCore: f2dd4c9befea04277a55e84e7812f930537993df NitroMmkv: afbc5b2fbf963be567c6c545aa1efcf6a9cec68e NitroModules: 11bba9d065af151eae51e38a6425e04c3b223ff3 - QuickCrypto: 7d3fed653542fb138b2bc555896e428357f4155a + QuickCrypto: 5780aa6e5542e1e958fbece6813e1d63741b82b0 RCT-Folly: 846fda9475e61ec7bcbf8a3fe81edfcaeb090669 RCTDeprecation: c4b9e2fd0ab200e3af72b013ed6113187c607077 RCTRequired: e97dd5dafc1db8094e63bc5031e0371f092ae92a diff --git a/packages/react-native-quick-crypto/QuickCrypto.podspec b/packages/react-native-quick-crypto/QuickCrypto.podspec index 216afa2a1..8e026e553 100644 --- a/packages/react-native-quick-crypto/QuickCrypto.podspec +++ b/packages/react-native-quick-crypto/QuickCrypto.podspec @@ -130,8 +130,7 @@ Pod::Spec.new do |s| "cpp/**/*.{hpp,cpp}", # dependencies (C++) - ncrypto "deps/ncrypto/include/**/*.{h}", - "deps/ncrypto/src/aead.cpp", - "deps/ncrypto/src/ncrypto.cpp", + "deps/ncrypto/src/*.{cpp}", # dependencies (C++) - simdutf "deps/simdutf/include/**/*.{h}", "deps/simdutf/src/simdutf.cpp", @@ -190,7 +189,7 @@ Pod::Spec.new do |s| xcconfig = { # C++ compiler flags, mainly for folly. - "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES", + "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES NCRYPTO_EVP_ONLY=1", # Set C++ standard to C++20 "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", "CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES" => "YES", @@ -199,7 +198,7 @@ Pod::Spec.new do |s| # Disable x86 SIMD intrinsics on iOS simulator — the .c implementation files are already # excluded above, but blake3_dispatch.c still references the symbols unless these macros # are defined. Mirrors the Android CMakeLists.txt approach (line 18-22). - "GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*][arch=x86_64]" => "$(inherited) BLAKE3_NO_AVX512 BLAKE3_NO_AVX2 BLAKE3_NO_SSE41 BLAKE3_NO_SSE2" + "GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*][arch=x86_64]" => "$(inherited) BLAKE3_NO_AVX512 BLAKE3_NO_AVX2 BLAKE3_NO_SSE41 BLAKE3_NO_SSE2 NCRYPTO_EVP_ONLY=1" } # Every translation unit calls the renamed OpenSSL symbols. Missing a rename @@ -240,7 +239,7 @@ Pod::Spec.new do |s| "\"#{real_sodium_include}/sodium\"" ] xcconfig["HEADER_SEARCH_PATHS"] = (cpp_headers + sodium_headers).join(' ') - xcconfig["GCC_PREPROCESSOR_DEFINITIONS"] = "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES BLSALLOC_SODIUM=1" + xcconfig["GCC_PREPROCESSOR_DEFINITIONS"] = "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES BLSALLOC_SODIUM=1 NCRYPTO_EVP_ONLY=1" else xcconfig["HEADER_SEARCH_PATHS"] = cpp_headers.join(' ') end diff --git a/packages/react-native-quick-crypto/android/CMakeLists.txt b/packages/react-native-quick-crypto/android/CMakeLists.txt index 2ec7cdd7e..4cb275971 100644 --- a/packages/react-native-quick-crypto/android/CMakeLists.txt +++ b/packages/react-native-quick-crypto/android/CMakeLists.txt @@ -67,10 +67,13 @@ add_library( ${BLAKE3_SOURCES} ../deps/fastpbkdf2/fastpbkdf2.c ../deps/ncrypto/src/aead.cpp + ../deps/ncrypto/src/engine.cpp ../deps/ncrypto/src/ncrypto.cpp ../deps/simdutf/src/simdutf.cpp ) +target_compile_definitions(${PACKAGE_NAME} PRIVATE NCRYPTO_EVP_ONLY=1) + # add Nitrogen specs include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/QuickCrypto+autolinking.cmake) diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto index c24987b0d..43328edbb 160000 --- a/packages/react-native-quick-crypto/deps/ncrypto +++ b/packages/react-native-quick-crypto/deps/ncrypto @@ -1 +1 @@ -Subproject commit c24987b0db08c2a966d3d954d682551cf9e846c2 +Subproject commit 43328edbba8c5901222821348ebd0fe4766f713c diff --git a/packages/react-native-quick-crypto/package.json b/packages/react-native-quick-crypto/package.json index ebbe6cae9..d2be13895 100644 --- a/packages/react-native-quick-crypto/package.json +++ b/packages/react-native-quick-crypto/package.json @@ -39,6 +39,7 @@ "deps/fastpbkdf2", "deps/ncrypto/include", "deps/ncrypto/src/aead.cpp", + "deps/ncrypto/src/engine.cpp", "deps/ncrypto/src/ncrypto.cpp", "deps/ncrypto/LICENSE", "deps/ncrypto/README.md", diff --git a/scripts/check-ncrypto-openssl-deprecations.sh b/scripts/check-ncrypto-openssl-deprecations.sh index ef60176f0..5c987cf5f 100755 --- a/scripts/check-ncrypto-openssl-deprecations.sh +++ b/scripts/check-ncrypto-openssl-deprecations.sh @@ -37,6 +37,7 @@ cat >"$work_dir/header-consumer.cpp" <<'EOF' #include <ncrypto/aead.h> static_assert(OPENSSL_VERSION_NUMBER >= 0x30600000L); +static_assert(NCRYPTO_EVP_ONLY == 1); EOF cat >"$work_dir/prime-check-regression.cpp" <<'EOF' @@ -71,12 +72,14 @@ warning_flags=( -Wextra -Werror -Wdeprecated-declarations + -DNCRYPTO_EVP_ONLY=1 "-I$ncrypto_dir/include" "${openssl_cflags[@]}" ) "$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/ncrypto.cpp" "$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/aead.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/engine.cpp" "$compiler" "${warning_flags[@]}" -fsyntax-only "$work_dir/header-consumer.cpp" "$compiler" "${warning_flags[@]}" \ "$ncrypto_dir/src/ncrypto.cpp" \ From 642518e529538a9dc1d4685205243fcdd5597619 Mon Sep 17 00:00:00 2001 From: Brad Anderson <brad@sankatygroup.com> Date: Mon, 26 Oct 2026 13:44:24 -0400 Subject: [PATCH 8/8] fix: repin ncrypto after strict compiler fix --- packages/react-native-quick-crypto/deps/ncrypto | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto index 43328edbb..ef5d829e2 160000 --- a/packages/react-native-quick-crypto/deps/ncrypto +++ b/packages/react-native-quick-crypto/deps/ncrypto @@ -1 +1 @@ -Subproject commit 43328edbba8c5901222821348ebd0fe4766f713c +Subproject commit ef5d829e27c9fcf539d4bf6b478353b888d607a2