【问题标题】:Extract PKCS7 Container memory leak during receipt validation在收据验证期间提取 PKCS7 容器内存泄漏
【发布时间】:2018-05-08 06:29:05
【问题描述】:

XCode 在我的一个函数中检测到内存泄漏:

func 负责提取 PKCS7 容器。这里是func的代码:

func extractPKCS7Container() throws -> UnsafeMutablePointer<PKCS7> {
    guard let receiptURL = Bundle.main.appStoreReceiptURL,
        let certificateURL = Bundle.main.url(forResource: "AppleIncRootCertificate", withExtension: "cer"),
        let receiptData = NSData(contentsOf: receiptURL),
        let certificateData = NSData(contentsOf: certificateURL) else {
            throw ReceiptError.couldNotFindReceipt
    }
    let bio = BIOWrapper(data: receiptData)
    let p7 = d2i_PKCS7_bio(bio.bio, nil)
    guard p7 != nil else {
        throw ReceiptError.emptyReceiptContents
    }
    OpenSSL_add_all_digests()

    let x509Store = X509StoreWrapper()
    let certificate = X509Wrapper(data: certificateData)
    x509Store.addCert(x509: certificate)
    let payload = BIOWrapper()
    guard PKCS7_verify(p7, nil, x509Store.store, nil, payload.bio, 0) == 1 else {
        throw ReceiptError.receiptNotSigned
    }
    return p7!
}

我还有补课:

class BIOWrapper {
    let bio = BIO_new(BIO_s_mem())
    init(data:NSData) {
        BIO_write(bio, data.bytes, Int32(data.length))
    }
    init() {}
    deinit {
        BIO_free(bio)
    }
}

class X509StoreWrapper {
    let store = X509_STORE_new()
    deinit {
        X509_STORE_free(store)
    }
    func addCert(x509:X509Wrapper) {
        X509_STORE_add_cert(store, x509.x509)
    }
}

class X509Wrapper {
    let x509 : UnsafeMutablePointer<X509>!
    init(data:NSData){
        let certBIO = BIOWrapper(data: data)
        x509 = d2i_X509_bio(certBIO.bio, nil)
    }
    deinit {
        X509_free(x509)
    }
}

所有包装器都有 init 和 deinit 部分。其他功能来自内置 Crypto 模块......坦率地说,我不知道泄漏可能在这里。谁能帮帮我?

【问题讨论】:

    标签: swift pkcs#7 receipt-validation


    【解决方案1】:

    您正在分配一个PKCS7 对象,但您似乎从未调用过PKCS7_free。例如,您需要在 throw ReceiptError.receiptNotSigned 之前调用它。

    请注意右侧的堆栈跟踪中缺少堆栈帧。您可以通过单击图标来查看它们,该图标看起来像一个正方形,上面和下面都有一条线。这样你就可以准确地知道哪个函数调用负责分配(因此很可能是什么泄露了)。

    【讨论】:

    • 我在throw ReceiptError.receiptNotSigned 之后添加了PKSC7_free 呼叫。不幸的是没有任何效果。我也按下了你提到的按钮。这是我的堆栈跟踪 - ibb.co/g43yR7。我不明白 - 看起来 CRYPTO_malloc 会导致问题?我的堆栈顶部的 CRYPTO_malloc。
    • 据我了解 malloc 分配的内存超出了必要?
    • 如果我做的一切都正确,问题仍然存在于 func extractPKCS7Container() - 截图:ibb.co/cR8UzS
    • PKCS7_free 的调用需要在guard 子句内,但之前 throw ReceiptError.receiptNotSigned(无法访问throw 之后的代码)。 malloc 根本没有释放。致电extractPKCS7Container() 后,您需要PKCS7_free 您的container 变量。
    • 对不起 - 输入错误。我按照你提到的那样插入它:guard PKCS7_verify(p7, nil, x509Store.store, nil, payload.bio, 0) == 1 else { PKCS7_free(p7) throw ... } 我正在尝试在主函数的正确位置插入PKCS7_free...
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 2016-07-04
    • 2021-11-21
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多