From 13e7513b3ba0afa13967daf77af2fb4ad087306c Mon Sep 17 00:00:00 2001 From: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com> Date: Mon, 4 Nov 2024 11:10:03 +0100 Subject: [PATCH] [V4] Fix memory bug when loading keys (#208) Fix leaking pointer Co-authored-by: Tim Condon <0xTim@users.noreply.github.com> --- Sources/JWTKit/Utilities/OpenSSLSigner.swift | 22 +++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Sources/JWTKit/Utilities/OpenSSLSigner.swift b/Sources/JWTKit/Utilities/OpenSSLSigner.swift index df3b7fa4..55bed9f2 100644 --- a/Sources/JWTKit/Utilities/OpenSSLSigner.swift +++ b/Sources/JWTKit/Utilities/OpenSSLSigner.swift @@ -1,5 +1,5 @@ -import Foundation @_implementationOnly import CJWTKitBoringSSL +import Foundation protocol OpenSSLSigner { var algorithm: OpaquePointer { get } @@ -33,23 +33,25 @@ extension OpenSSLSigner { guard CJWTKitBoringSSL_EVP_DigestFinal_ex(context, &digest, &digestLength) == 1 else { throw JWTError.signingAlgorithmFailure(OpenSSLError.digestFinalizationFailure) } - return .init(digest[0..(pem data: Data, _ closure: (UnsafeMutablePointer) -> (T?)) throws -> T where Data: DataProtocol { - let bytes = data.copyBytes() - let bio = CJWTKitBoringSSL_BIO_new_mem_buf(bytes, numericCast(bytes.count)) - defer { CJWTKitBoringSSL_BIO_free(bio) } - - guard let bioPtr = bio, let c = closure(bioPtr) else { - throw JWTError.signingAlgorithmFailure(OpenSSLError.bioConversionFailure) + try data.copyBytes().withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in + let bio = CJWTKitBoringSSL_BIO_new_mem_buf(bytes.baseAddress, numericCast(bytes.count)) + + defer { CJWTKitBoringSSL_BIO_free(bio) } + + guard let bioPtr = bio, let c = closure(bioPtr) else { + throw JWTError.signingAlgorithmFailure(OpenSSLError.bioConversionFailure) + } + return c } - return c } }