From 36756a5b205b1e67005b5093ce27d1cc96229410 Mon Sep 17 00:00:00 2001 From: Moritz Date: Tue, 17 Nov 2026 15:11:57 +0000 Subject: [PATCH] fix(ffi): clear BoringSSL errors left by other code before each operation With package:boring, every package using BoringSSL on a thread shares its error queue, while webcrypto's own copy of BoringSSL had a separate one. An error that another package left behind was reported as the message of webcrypto's next failure, because extractBoringSslError() reports the least recent (most specific) error. For example, a leftover EC UNKNOWN_GROUP error replaced the DECODE_ERROR of a malformed RSA PKCS#8 key. Run all BoringSSL calls in _arena / _arenaStream, which clear the queue before the operation, like package:boring's README recommends. No other isolate runs on the thread until the operation awaits, and errors are already consumed right after each failing call, so this covers every synchronous call. Results don't change: only error messages could be wrong. --- lib/src/impl_ffi/impl_ffi.aescbc.dart | 2 +- lib/src/impl_ffi/impl_ffi.aesctr.dart | 2 +- lib/src/impl_ffi/impl_ffi.aesgcm.dart | 2 +- lib/src/impl_ffi/impl_ffi.digest.dart | 2 +- lib/src/impl_ffi/impl_ffi.ec_common.dart | 16 +++--- lib/src/impl_ffi/impl_ffi.ecdh.dart | 2 +- lib/src/impl_ffi/impl_ffi.ecdsa.dart | 4 +- lib/src/impl_ffi/impl_ffi.hkdf.dart | 2 +- lib/src/impl_ffi/impl_ffi.hmac.dart | 4 +- lib/src/impl_ffi/impl_ffi.pbkdf2.dart | 2 +- lib/src/impl_ffi/impl_ffi.random.dart | 2 +- lib/src/impl_ffi/impl_ffi.rsa_common.dart | 10 ++-- lib/src/impl_ffi/impl_ffi.rsaoaep.dart | 2 +- lib/src/impl_ffi/impl_ffi.utils.dart | 29 ++++++++-- test/ffi/stale_boringssl_errors_test.dart | 64 +++++++++++++++++++++++ 15 files changed, 115 insertions(+), 30 deletions(-) create mode 100644 test/ffi/stale_boringssl_errors_test.dart diff --git a/lib/src/impl_ffi/impl_ffi.aescbc.dart b/lib/src/impl_ffi/impl_ffi.aescbc.dart index 943664c1..4d980237 100644 --- a/lib/src/impl_ffi/impl_ffi.aescbc.dart +++ b/lib/src/impl_ffi/impl_ffi.aescbc.dart @@ -33,7 +33,7 @@ Stream _aesCbcEncryptOrDecrypt( Stream> source, List iv, ) { - return BoringArena.stream((scope) async* { + return _arenaStream((scope) async* { assert(key.length == 16 || key.length == 32); final cipher = key.length == 16 ? ssl.EVP_aes_128_cbc() diff --git a/lib/src/impl_ffi/impl_ffi.aesctr.dart b/lib/src/impl_ffi/impl_ffi.aesctr.dart index 6097392b..c4c52e1d 100644 --- a/lib/src/impl_ffi/impl_ffi.aesctr.dart +++ b/lib/src/impl_ffi/impl_ffi.aesctr.dart @@ -59,7 +59,7 @@ Stream _aesCtrEncryptOrDecrypt( // Heavily inspired by Chromium Web Crypto implementation, see: // https://chromium.googlesource.com/chromium/src/+/43d62c50b705f88c67b14539e91fd8fd017f70c4/components/webcrypto/algorithms/aes_ctr.cc#144 - return BoringArena.stream((scope) async* { + return _arenaStream((scope) async* { assert(counter.length == 16); assert(key.length == 16 || key.length == 32); final cipher = key.length == 16 diff --git a/lib/src/impl_ffi/impl_ffi.aesgcm.dart b/lib/src/impl_ffi/impl_ffi.aesgcm.dart index 96e55ad6..025de676 100644 --- a/lib/src/impl_ffi/impl_ffi.aesgcm.dart +++ b/lib/src/impl_ffi/impl_ffi.aesgcm.dart @@ -55,7 +55,7 @@ Future _aesGcmEncryptDecrypt( // what chrome does, how firefox passes tests. And check if other // primitives that accept an iv/nonce has size limitations on it. - return BoringArena.using((scope) async { + return _arena((scope) async { assert(key.length == 16 || key.length == 32); final aead = key.length == 16 ? ssl.EVP_aead_aes_128_gcm() diff --git a/lib/src/impl_ffi/impl_ffi.digest.dart b/lib/src/impl_ffi/impl_ffi.digest.dart index 95ba3349..8ae83092 100644 --- a/lib/src/impl_ffi/impl_ffi.digest.dart +++ b/lib/src/impl_ffi/impl_ffi.digest.dart @@ -42,7 +42,7 @@ abstract class _HashImpl implements HashImpl { @override Future digestStream(Stream> data) { - return BoringArena.using((scope) async { + return _arena((scope) async { final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free); // Initialize with hash function _checkOp(ssl.EVP_DigestInit(ctx, _md) == 1); diff --git a/lib/src/impl_ffi/impl_ffi.ec_common.dart b/lib/src/impl_ffi/impl_ffi.ec_common.dart index 1ebc02f0..292c86a8 100644 --- a/lib/src/impl_ffi/impl_ffi.ec_common.dart +++ b/lib/src/impl_ffi/impl_ffi.ec_common.dart @@ -66,7 +66,7 @@ String _ecCurveToJwkCrv(EllipticCurve curve) { /// Perform some post-import validation for EC keys. void _validateEllipticCurveKey(_EvpPKey key, EllipticCurve curve) { - return BoringArena.using((scope) { + return _arena((scope) { _checkData( ssl.EVP_PKEY_id.invoke(key) == EVP_PKEY_EC, message: 'key is not an EC key', @@ -94,7 +94,7 @@ void _validateEllipticCurveKey(_EvpPKey key, EllipticCurve curve) { } _EvpPKey _importPkcs8EcPrivateKey(List keyData, EllipticCurve curve) { - return BoringArena.using((scope) { + return _arena((scope) { final cbs = scope.cbs(keyData); final k = ssl.EVP_parse_private_key(cbs); @@ -108,7 +108,7 @@ _EvpPKey _importPkcs8EcPrivateKey(List keyData, EllipticCurve curve) { } _EvpPKey _importSpkiEcPublicKey(List keyData, EllipticCurve curve) { - return BoringArena.using((scope) { + return _arena((scope) { final cbs = scope.cbs(keyData); final k = ssl.EVP_parse_public_key(cbs); @@ -169,7 +169,7 @@ _EvpPKey _importJwkEcPrivateOrPublicKey( // TODO: Reject keys with key_ops in inconsistent with isPrivateKey // Also in the js implementation... - return BoringArena.using((scope) { + return _arena((scope) { final ec = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve)); _checkOp(ec.address != 0, fallback: 'internal failure to use curve'); scope.register(ec, ssl.EC_KEY_free); @@ -225,7 +225,7 @@ _EvpPKey _importJwkEcPrivateOrPublicKey( _EvpPKey _importRawEcPublicKey(List keyData, EllipticCurve curve) { // See: https://chromium.googlesource.com/chromium/src/+/43d62c50b705f88c67b14539e91fd8fd017f70c4/components/webcrypto/algorithms/ec.cc#332 - return BoringArena.using((scope) { + return _arena((scope) { // Create EC_KEY for the curve final ec = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve)); _checkOp(ec.address != 0, fallback: 'internal failure to use curve'); @@ -262,7 +262,7 @@ _EvpPKey _importRawEcPublicKey(List keyData, EllipticCurve curve) { } Uint8List _exportRawEcPublicKey(_EvpPKey key) { - return BoringArena.using((scope) { + return _arena((scope) { final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key); _checkOp(ec.address != 0, fallback: 'internal key type invariant error'); scope.register(ec, ssl.EC_KEY_free); @@ -287,7 +287,7 @@ Map _exportJwkEcPrivateOrPublicKey( required bool isPrivateKey, String? jwkUse, }) { - return BoringArena.using((scope) { + return _arena((scope) { final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key); _checkOp(ec.address != 0, fallback: 'internal key type invariant error'); scope.register(ec, ssl.EC_KEY_free); @@ -338,7 +338,7 @@ Map _exportJwkEcPrivateOrPublicKey( } KeyPair<_EvpPKey, _EvpPKey> _generateEcKeyPair(EllipticCurve curve) { - return BoringArena.using((scope) { + return _arena((scope) { final ecPriv = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve)); _checkOp(ecPriv.address != 0, fallback: 'internal failure to use curve'); scope.register(ecPriv, ssl.EC_KEY_free); diff --git a/lib/src/impl_ffi/impl_ffi.ecdh.dart b/lib/src/impl_ffi/impl_ffi.ecdh.dart index b08e79d5..b9e53777 100644 --- a/lib/src/impl_ffi/impl_ffi.ecdh.dart +++ b/lib/src/impl_ffi/impl_ffi.ecdh.dart @@ -115,7 +115,7 @@ final class _EcdhPrivateKeyImpl implements EcdhPrivateKeyImpl { throw ArgumentError.value(length, 'length', 'must be non-negative'); } - return BoringArena.using((scope) async { + return _arena((scope) async { final pubEcKey = ssl.EVP_PKEY_get1_EC_KEY.invoke(publicKey._key); _checkOp(pubEcKey.address != 0, fallback: 'not an ec key'); scope.register(pubEcKey, ssl.EC_KEY_free); diff --git a/lib/src/impl_ffi/impl_ffi.ecdsa.dart b/lib/src/impl_ffi/impl_ffi.ecdsa.dart index b20af32f..311ce683 100644 --- a/lib/src/impl_ffi/impl_ffi.ecdsa.dart +++ b/lib/src/impl_ffi/impl_ffi.ecdsa.dart @@ -92,7 +92,7 @@ Uint8List _convertEcdsaDerSignatureToWebCryptoSignature( _EvpPKey key, Uint8List signature, ) { - return BoringArena.using((scope) { + return _arena((scope) { // TODO: Check if cbs is empty after parsing, consider using ECDSA_SIG_from_bytes instead (like chrome does) final ecdsa = ssl.ECDSA_SIG_parse(scope.cbs(signature)); _checkOp( @@ -139,7 +139,7 @@ Uint8List? _convertEcdsaWebCryptoSignatureToDerSignature( _EvpPKey key, List signature, ) { - return BoringArena.using((scope) { + return _arena((scope) { // Read EC key and get the number of bytes required to encode R and S. final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key); _checkOp(ec.address != 0, message: 'internal key type invariant violation'); diff --git a/lib/src/impl_ffi/impl_ffi.hkdf.dart b/lib/src/impl_ffi/impl_ffi.hkdf.dart index 42e5bd2f..6bd2003e 100644 --- a/lib/src/impl_ffi/impl_ffi.hkdf.dart +++ b/lib/src/impl_ffi/impl_ffi.hkdf.dart @@ -64,7 +64,7 @@ final class _HkdfSecretKeyImpl implements HkdfSecretKeyImpl { throw operationError(lengthTooLong); } - return BoringArena.using((scope) async { + return _arena((scope) async { final out = scope(lengthInBytes); final r = ssl.HKDF( out, diff --git a/lib/src/impl_ffi/impl_ffi.hmac.dart b/lib/src/impl_ffi/impl_ffi.hmac.dart index 95b7722d..e720257f 100644 --- a/lib/src/impl_ffi/impl_ffi.hmac.dart +++ b/lib/src/impl_ffi/impl_ffi.hmac.dart @@ -146,7 +146,7 @@ final class _HmacSecretKeyImpl implements HmacSecretKeyImpl { @override Future signStream(Stream> data) { - return BoringArena.using((scope) async { + return _arena((scope) async { final ctx = scope.create(ssl.HMAC_CTX_new, ssl.HMAC_CTX_free); _checkOpIsOne( ssl.HMAC_Init_ex( @@ -180,7 +180,7 @@ final class _HmacSecretKeyImpl implements HmacSecretKeyImpl { if (signature.length != other.length) { return false; } - return BoringArena.using((scope) { + return _arena((scope) { final cmp = ssl.CRYPTO_memcmp( scope.copyBytes(signature), scope.copyBytes(other), diff --git a/lib/src/impl_ffi/impl_ffi.pbkdf2.dart b/lib/src/impl_ffi/impl_ffi.pbkdf2.dart index 01b53d67..7b58496e 100644 --- a/lib/src/impl_ffi/impl_ffi.pbkdf2.dart +++ b/lib/src/impl_ffi/impl_ffi.pbkdf2.dart @@ -72,7 +72,7 @@ final class _Pbkdf2SecretKeyImpl implements Pbkdf2SecretKeyImpl { final lengthInBytes = length ~/ 8; - return BoringArena.using((scope) async { + return _arena((scope) async { final out = scope(lengthInBytes); _checkOpIsOne( await _PKCS5_PBKDF2_HMAC( diff --git a/lib/src/impl_ffi/impl_ffi.random.dart b/lib/src/impl_ffi/impl_ffi.random.dart index 62cf516e..bce82efe 100644 --- a/lib/src/impl_ffi/impl_ffi.random.dart +++ b/lib/src/impl_ffi/impl_ffi.random.dart @@ -19,7 +19,7 @@ final class _RandomImpl implements RandomImpl { @override void fillRandomBytes(TypedData destination) { - return BoringArena.using((scope) { + return _arena((scope) { final dest = destination.buffer.asUint8List( destination.offsetInBytes, destination.lengthInBytes, diff --git a/lib/src/impl_ffi/impl_ffi.rsa_common.dart b/lib/src/impl_ffi/impl_ffi.rsa_common.dart index fbef84ca..40a59749 100644 --- a/lib/src/impl_ffi/impl_ffi.rsa_common.dart +++ b/lib/src/impl_ffi/impl_ffi.rsa_common.dart @@ -15,7 +15,7 @@ part of 'impl_ffi.dart'; _EvpPKey _importPkcs8RsaPrivateKey(List keyData) { - return BoringArena.using((scope) { + return _arena((scope) { final cbs = scope.cbs(keyData); final k = ssl.EVP_parse_private_key(cbs); @@ -39,7 +39,7 @@ _EvpPKey _importPkcs8RsaPrivateKey(List keyData) { } _EvpPKey _importSpkiRsaPublicKey(List keyData) { - return BoringArena.using((scope) { + return _arena((scope) { final cbs = scope.cbs(keyData); final k = ssl.EVP_parse_public_key(cbs); @@ -68,7 +68,7 @@ _EvpPKey _importJwkRsaPrivateOrPublicKey( required String expectedAlg, required String expectedUse, }) { - return BoringArena.using((scope) { + return _arena((scope) { void checkJwk( bool condition, String prop, [ @@ -175,7 +175,7 @@ Map _exportJwkRsaPrivateOrPublicKey( required String jwkAlg, required String jwkUse, }) { - return BoringArena.using((scope) { + return _arena((scope) { final rsa = ssl.EVP_PKEY_get1_RSA.invoke(key); _checkOp(rsa.address != 0, fallback: 'internal key type error'); scope.register(rsa, ssl.RSA_free); @@ -258,7 +258,7 @@ Future> _generateRsaKeyPair( throw UnsupportedError('publicExponent is not supported, try 3 or 65537'); } - return BoringArena.using((scope) async { + return _arena((scope) async { // Generate private RSA key final privRSA = scope.createRSA(); diff --git a/lib/src/impl_ffi/impl_ffi.rsaoaep.dart b/lib/src/impl_ffi/impl_ffi.rsaoaep.dart index 1b7d4eab..3ebb35c5 100644 --- a/lib/src/impl_ffi/impl_ffi.rsaoaep.dart +++ b/lib/src/impl_ffi/impl_ffi.rsaoaep.dart @@ -105,7 +105,7 @@ Future _rsaOaepeEncryptOrDecryptBytes( List data, { List? label, }) async { - return BoringArena.using((scope) { + return _arena((scope) { final ctx = scope.create( () => ssl.EVP_PKEY_CTX_new.invoke(key, ffi.nullptr), ssl.EVP_PKEY_CTX_free, diff --git a/lib/src/impl_ffi/impl_ffi.utils.dart b/lib/src/impl_ffi/impl_ffi.utils.dart index a37e1089..d1f29d9b 100644 --- a/lib/src/impl_ffi/impl_ffi.utils.dart +++ b/lib/src/impl_ffi/impl_ffi.utils.dart @@ -36,6 +36,27 @@ extension type _EvpPKey._(NativeHandle _handle) // failing call, using _checkOp / _checkData or ERR_clear_error, rather than // deferring it to a `finally` or BoringArena release that may run after an // `await`. In tests, checkErrorStack fails if errors are left behind. +// +// Every package using package:boring on a thread shares its queue, so other +// code may leave errors behind, which _checkOp / _checkData would report for +// webcrypto's next failure. So run all BoringSSL calls in _arena or +// _arenaStream, which clear the queue first. + +/// Runs [computation] with a new [BoringArena], like [BoringArena.using], +/// after clearing errors that other code left on BoringSSL's error queue. +R _arena(R Function(BoringArena scope) computation) { + ssl.ERR_clear_error(); + return BoringArena.using(computation); +} + +/// Returns the stream of [computation] with a new [BoringArena], like +/// [BoringArena.stream], after clearing errors that other code left on +/// BoringSSL's error queue when the stream is listened to. +Stream _arenaStream(Stream Function(BoringArena scope) computation) => + BoringArena.stream((scope) { + ssl.ERR_clear_error(); + return computation(scope); + }); /// Throw [OperationError] if [condition] is `false`. /// @@ -151,7 +172,7 @@ Future _signStream( Stream> data, { void Function(ffi.Pointer ctx)? config, }) { - return BoringArena.using((scope) async { + return _arena((scope) async { final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free); final pctx = config != null ? scope>() @@ -186,7 +207,7 @@ Future _verifyStream( Stream> data, { void Function(ffi.Pointer ctx)? config, }) { - return BoringArena.using((scope) async { + return _arena((scope) async { // Create and initialize verification context final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free); final pctx = config != null @@ -221,7 +242,7 @@ Future _verifyStream( /// Export private [key] as PKCS8. Uint8List _exportPkcs8Key(_EvpPKey key) { - return BoringArena.using((scope) { + return _arena((scope) { final cbb = scope.cbb(); _checkOpIsOne(ssl.EVP_marshal_private_key.invoke(cbb, key)); return cbb.toBytes(); @@ -230,7 +251,7 @@ Uint8List _exportPkcs8Key(_EvpPKey key) { /// Export public [key] as SPKI. Uint8List _exportSpkiKey(_EvpPKey key) { - return BoringArena.using((scope) { + return _arena((scope) { final cbb = scope.cbb(); _checkOpIsOne(ssl.EVP_marshal_public_key.invoke(cbb, key)); return cbb.toBytes(); diff --git a/test/ffi/stale_boringssl_errors_test.dart b/test/ffi/stale_boringssl_errors_test.dart new file mode 100644 index 00000000..44bbdd86 --- /dev/null +++ b/test/ffi/stale_boringssl_errors_test.dart @@ -0,0 +1,64 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +@TestOn('vm') +library; + +import 'dart:ffi' as ffi; + +import 'package:boring/bindings.dart' as ssl; +import 'package:test/test.dart'; +import 'package:webcrypto/webcrypto.dart'; + +/// Leaves an `EC_R_UNKNOWN_GROUP` error on BoringSSL's error queue, like +/// another package using package:boring on this thread might. +void _leaveStaleError() { + ssl.ERR_clear_error(); + expect(ssl.EC_KEY_new_by_curve_name(-1), equals(ffi.nullptr)); + expect(ssl.ERR_peek_error(), isNot(0)); +} + +void main() { + tearDown(ssl.ERR_clear_error); + + test('errors left by other code are not reported for RSA imports', () async { + _leaveStaleError(); + await expectLater( + RsaOaepPrivateKey.importPkcs8Key([1, 2, 3], Hash.sha256), + throwsA( + isA().having( + (e) => e.message, + 'message', + allOf(contains('DECODE_ERROR'), isNot(contains('UNKNOWN_GROUP'))), + ), + ), + ); + expect(ssl.ERR_peek_error(), equals(0)); + }); + + test('errors left by other code are not reported for EC imports', () async { + _leaveStaleError(); + await expectLater( + EcdhPublicKey.importSpkiKey([1, 2, 3], EllipticCurve.p256), + throwsA( + isA().having( + (e) => e.message, + 'message', + isNot(contains('UNKNOWN_GROUP')), + ), + ), + ); + expect(ssl.ERR_peek_error(), equals(0)); + }); +}