odd segfault / must be something obvious

Dirk-Willem van Gulik dirkx at webweaving.org
Thu Feb 11 09:38:39 UTC 2021


I am hitting a head end and must be missing something obvious.

Below is the code - it verifies a signature. And it segfaults regularly on the PKCS7_free(p7);

And I fail to understand why - and suspect it is very obvious !

Any and all help appreciated.

Dw

#define EXITOUT(args...) { EOUT(args); goto errit; }

    int result = NO;
    BIO *signatureBlob = NULL, *contentBlob = NULL, *certificateBlob = NULL;
    X509_VERIFY_PARAM *verifyParameters = NULL;
    STACK_OF(X509) *signers = NULL;
    X509_STORE *store = NULL;
    X509 *signingCert = NULL;
    PKCS7 *p7 = NULL;
    
    if (NULL == (signatureBlob = BIO_new_mem_buf(sig.bytes, (int)sig.length))) EXITOUT("invalid  signatureBlob");    
    if (NULL == (contentBlob = BIO_new_mem_buf(cont.bytes, (int)cont.length))) EXITOUT("invalid  contentBlob");    
    if (NULL == (certificateBlob = BIO_new_mem_buf(cert.bytes, (int)cert.length))) EXITOUT("invalid certificateBlob");
    
    if (NULL == (p7 = d2i_PKCS7_bio(signatureBlob, NULL)))
        EXITOUT("invalid PKCS#7 structure in signatureBlob");
    
    if (NULL == (signers = PKCS7_get0_signers(p7, NULL, 0)))
        EXITOUT("No signers in PCKS#7 signatureBlob");

    if (sk_X509_num(signers) == 1)
        EXITOUT("Not signer exactly one signer in PCKS#7 signatureBlob");

    // do various validations/comparisons on signingCert = sk_X509_value(signers, 0);
       
    if ((NULL == (store = X509_STORE_new())))
        EXITOUT("store");
    
    for(X509 *cert = NULL;;cnt++) {
        if (NULL == (cert = PEM_read_bio_X509(certificateBlob, NULL, 0, NULL)))
            break;
        
        if (X509_STORE_add_cert(store, cert) != 1)
            EXITOUT("Could not add cert %d to chain.",1+cnt);
        
#ifdef __DEBUG
        print_certificate(cert);
#endif
        X509_free(cert);
    };
    ERR_clear_error();
    
    if (cnt == 0)
        EXITOUT("no trust chain of any length");
    
    if (NULL == (verifyParameters = X509_VERIFY_PARAM_new()))
        EXITOUT("Could create verifyParameters");

    // setup verifyParameters ..

    result = PKCS7_verify(p7, NULL, store, contentBlob, NULL, PKCS7_BINARY);

    // error handling / printing
    
errit:
    if (verifyParameters) X509_VERIFY_PARAM_free(verifyParameters);
    
    if (store) X509_STORE_free(store);
    if (p7) PKCS7_free(p7); // <----- **********************. segfault 
    
    if (signatureBlob) BIO_free(signatureBlob);
    if (contentBlob) BIO_free(contentBlob);
    if (certificateBlob) BIO_free(certificateBlob);
    
    return result == 1;
}


More information about the openssl-users mailing list