在收据验证期间解压缩PKCS7容器内存泄漏

时间:2018-05-08 06:29:05

标签: swift pkcs#7 receipt-validation

XCode在我的一个功能中检测到内存泄漏: enter image description here

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部分。其他功能来自内置加密模块......坦率地说,我不知道泄漏可以在这里。有谁可以帮助我?

1 个答案:

答案 0 :(得分:0)

您正在分配PKCS7个对象,但似乎您永远不会调用PKCS7_free。例如,您需要在throw ReceiptError.receiptNotSigned之前调用它。

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