On Mon, Feb 18, 2013, Nick wrote: > On Mon, 2013-02-18 at 00:37 +0100, Dr. Stephen Henson wrote: > > That's because it is attempting to free up parts of a pointer that > > haven't > > been allocated with OPENSSL_malloc. See: > > > > http://www.openssl.org/docs/crypto/d2i_X509.html#WARNINGS > > > > Changing the code to allocate the struct via OPENSSL_malloc does not seg > fault in a standalone app, but the same exact code seg faults in a > slightly larger app (dump still points to d2i_RSAPrivateKey_fp). > > Does that mean any non-NULL ptr passed to the function must be allocated > via OPENSSL_malloc? This line in the man page for d2i_X509 suggested to > me that a non-NULL ptr need only point to a real structure (ie. could > not simply be an uninitialized ptr): > > "If *px is not NULL then it is assumed that *px contains a valid > X509 structure and an attempt is made to reuse it." > > > Accordingly, I currently have this d2i_X509_fp code which does not > segfault: > > X509 x509; > X509 *pTmpX509(&x509); > X509 *pX509 = d2i_X509_fp(pFile2, &pTmpX509); > > It's semantically the same as how I'm calling d2i_RSAPrivateKey_fp: > > RSA rsa; > RSA *pTmpRsa(&rsa); > RSA *pRSA = d2i_RSAPrivateKey_fp(pFile, &pTmpRsa); > > > The former (d2i_X509_fp) works fine while the latter > (d2i_RSAPrivateKey_fp) seg faults. > > Are the APIs different in their expectations of the 2nd param? Or have > I just been getting lucky w/ my calls to d2i_X509_fp? > > Must the non-NULL ptr that's passed as the 2nd param always be allocated > with OPENSSL_malloc? Can it not come from the stack or some other heap > allocator? >
Here's what's happening in detail. If you pass a non-NULL pointer for the second parameter it will attempt to reuse the structure. In the case of the RSA structure the outer (RSA *) is allocated via OPENSSL_malloc and so are many internal structures (e.g. BIGNUM key components), which it will also attempt to reuse. So all the internals need to be initialised to something sensible too or it may attempt to free up unintialised pointers with unpredictable results. Where possible applications shouldn't mess around at this level. There are utility functions of the form X509_new (and RSA_new for (RSA *)) that allocate and initialise the structures correctly. So you could do something like this: RSA *prsa1, *prsa2; prsa1 = RSA_new(); prsa2 = d2i_RSAPrivateKey_fp(pFile, &prsa1); But there isn't really any point as you can just do: rsa = d2i_RSAPrivateKey_fp(pFile, NULL); Which will call RSA_new() internally. Steve. -- Dr Stephen N. Henson. OpenSSL project core developer. Commercial tech support now available see: http://www.openssl.org ______________________________________________________________________ OpenSSL Project http://www.openssl.org User Support Mailing List [email protected] Automated List Manager [email protected]
