[xmlsec] Win32 rsa encryption with Aes192 session key crashes

Bundschuh, Goetz Goetz.Bundschuh at usd.de
Wed Jul 20 02:12:07 PDT 2005


Hi,
I tried to adapt the tutorial example "Using keys manager for encryption."
to work with RSA public keys extracted from certificates in the MS store under
WinXP SP2. I also changed the symmetric algorithm used from 3Des to Aes 192.
While the example worked flawlessly while using OpenSSL and .pem-files, trying
to run it with mscrypto leads to a crash with an access violation during the
xmlSecEncCtxXmlEncrypt() call. My best guess after 2 days of debugging
attempts is that the RSA key extracted from the certificate store is not
correctly added to the Keymanager during the
xmlSecCryptoAppDefaultKeysMngrAdoptKey() call, but I have no clue why.
I use the following Binaries:
xmlsec 1.2.8
libxml2 2.6.19

Thanks in advance,

Goetz


Here's the Code I used:


#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <windows.h>
#include <Wincrypt.h>

#define XMLSEC_CRYPTO_DYNAMIC_LOADING
#define XMLSEC_CRYPTO "mscrypto"
#define DEFAULT_CERT 1
#define USER_CERT_STORE_NAME "My"

#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

#ifndef XMLSEC_NO_XSLT
#include <libxslt/xslt.h>
#endif /* XMLSEC_NO_XSLT */

#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/xmlenc.h>
#include <xmlsec/templates.h>
#include <xmlsec/crypto.h>
#include <xmlsec/mscrypto/certkeys.h>

xmlSecKeysMngrPtr load_rsa_keys(char** key_file, HCERTSTORE  storeHandle);
int encrypt_file(xmlSecKeysMngrPtr mngr, const char* xml_file, const char*
keyName);

int
main(int argc, char **argv) {
    xmlSecKeysMngrPtr mngr;
     HCERTSTORE       storeHandle = NULL;	// Certificate store handle.
    char* keyName = NULL;
    assert(argv);

    if(argc != 2) {
	fprintf(stderr, "Error: wrong number of arguments.\n");
	fprintf(stderr, "Usage: %s <xml-file>\n", argv[0]);
	return(1);
    }

	if ( !(storeHandle = CertOpenSystemStore(NULL,USER_CERT_STORE_NAME)))
	{
		fprintf(stderr, "Error: unable to open certificate store\n");
		return (NULL);
	}
    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1;
#endif /* XMLSEC_NO_XSLT */

    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
	fprintf(stderr, "Error: xmlsec initialization failed.\n");
	return(-1);
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
	fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
	return(-1);
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
	fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make
sure\n"
			"that you have it installed and check shared libraries path\n"
			"(LD_LIBRARY_PATH) envornment variable.\n");
	return(-1);
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
	fprintf(stderr, "Error: crypto initialization failed.\n");
	return(-1);
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
	fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
	return(-1);
    }

    /* create keys manager and load keys */
    mngr = load_rsa_keys(&keyName, storeHandle);
    if(mngr == NULL) {
		return(-1);
    }
    /* we use keyName as key name here */
    if(encrypt_file(mngr, argv[1], (const char*)keyName) < 0)
	{
		xmlSecKeysMngrDestroy(mngr);
		return(-1);
    }
	/* destroy keys manager */

    return(0);
}

/**
 * load_rsa_keys:
 * @keyName:		pointer to key name(out).
 * @storeHandle		handle for Mscrypto store
 *
 * Creates simple keys manager and loads an RSA key from the first certificate
in the MScrypto-store.
 * The caller is responsible for destroing returned keys manager using
 * @xmlSecKeysMngrDestroy.
 *
 * Returns the pointer to newly created keys manager or NULL if an error
 * occurs.
 */
xmlSecKeysMngrPtr
load_rsa_keys(char** keyName,
			  HCERTSTORE storeHandle) {
    xmlSecKeysMngrPtr mngr;					// Security Manager Pointer
    xmlSecKeyPtr key;						// Key Pointer

	PCCERT_CONTEXT   certContext = NULL;	// Certificate context

	certContext= CertEnumCertificatesInStore(storeHandle, certContext);


    /* create and initialize keys manager, we use a simple list based
     * keys manager, implement your own xmlSecKeysStore klass if you need
     * something more sophisticated
     */
    mngr = xmlSecKeysMngrCreate();
    if(mngr == NULL)
	{
		fprintf(stderr, "Error: failed to create keys manager.\n");
		return(NULL);
    }
    if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) < 0)
	{
		fprintf(stderr, "Error: failed to initialize keys manager.\n");
		xmlSecKeysMngrDestroy(mngr);
		return(NULL);
    }


	//Create key from certificate public key data
	key = xmlSecKeyCreate();
	/* load public RSA key */
	xmlSecKeySetValue(key,xmlSecMSCryptoCertAdopt(certContext,
xmlSecKeyDataTypePublic));;


	int size =CertGetNameString(certContext,
							CERT_NAME_FRIENDLY_DISPLAY_TYPE,
							0,
							NULL,
							NULL,
							0);

	if(size>0)
	{
		*keyName = (char *)malloc(size);
		CertGetNameString(certContext,
							CERT_NAME_FRIENDLY_DISPLAY_TYPE,
							0,
							NULL,
							*keyName,
							size);
	}
	else
	{
	// cleaning
		fprintf(stderr, "Error: reading subject name for certificate failed.\n");
		CertFreeCertificateContext(certContext);
		xmlSecKeyDestroy(key);
		xmlSecKeysMngrDestroy(mngr);
		CertCloseStore(storeHandle,0);
		return (NULL);
	}
  /* set key name to the certificate friendly name*/
    if(xmlSecKeySetName(key, BAD_CAST *keyName) < 0)
	{
        fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n",
*keyName);
        xmlSecKeyDestroy(key);
		xmlSecKeysMngrDestroy(mngr);
		return(NULL);
    }

    /* add key to keys manager, from now on keys manager is responsible
     * for destroying key
     */
    if(xmlSecCryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0)
	{
        fprintf(stderr,"Error: failed to add key from \"%s\" to keys
manager\n", *keyName);
        xmlSecKeyDestroy(key);
        xmlSecKeysMngrDestroy(mngr);
        return(NULL);
    }
	CertFreeCertificateContext(certContext);
    return(mngr);
}

/**
 * encrypt_file:
 * @mngr:		the pointer to keys manager.
 * @xml_file:		the encryption template file name.
 * @keyName:		the RSA key name.
 *
 * Encrypts #xml_file using a dynamicaly created template, a session Aes192
key
 * and an RSA key from keys manager.
 *
 * Returns 0 on success or a negative value if an error occurs.
 */
int
encrypt_file(xmlSecKeysMngrPtr mngr, const char* xml_file, const char*
keyName) {
    xmlDocPtr doc = NULL;
    xmlNodePtr encDataNode = NULL;
    xmlNodePtr keyInfoNode = NULL;
    xmlNodePtr encKeyNode = NULL;
    xmlNodePtr keyInfoNode2 = NULL;
    xmlSecEncCtxPtr encCtx = NULL;
    int res = -1;

    assert(mngr);
    assert(xml_file);
    assert(keyName);
    /* load template */
    doc = xmlParseFile(xml_file);
    if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL))
	{
		fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
		goto done;
    }
    /* create encryption template to encrypt XML file and replace
     * its content with encryption result */
    encDataNode = xmlSecTmplEncDataCreate(doc, xmlSecTransformAes192CbcId,
				NULL, xmlSecTypeEncElement, NULL, NULL);
    if(encDataNode == NULL) {
	fprintf(stderr, "Error: failed to create encryption template\n");
	goto done;
    }

    /* we want to put encrypted data in the <enc:CipherValue/> node */
    if(xmlSecTmplEncDataEnsureCipherValue(encDataNode) == NULL) {
	fprintf(stderr, "Error: failed to add CipherValue node\n");
	goto done;
    }

    /* add <dsig:KeyInfo/> */
    keyInfoNode = xmlSecTmplEncDataEnsureKeyInfo(encDataNode, NULL);
    if(keyInfoNode == NULL) {
	fprintf(stderr, "Error: failed to add key info\n");
	goto done;
    }

    /* add <enc:EncryptedKey/> to store the encrypted session key */
    encKeyNode = xmlSecTmplKeyInfoAddEncryptedKey(keyInfoNode,
				    xmlSecTransformRsaPkcs1Id,
				    NULL, NULL, NULL);
    if(encKeyNode == NULL)
	{
		fprintf(stderr, "Error: failed to add key info\n");
		goto done;
    }

    /* we want to put encrypted key in the <enc:CipherValue/> node */
    if(xmlSecTmplEncDataEnsureCipherValue(encKeyNode) == NULL)
	{
		fprintf(stderr, "Error: failed to add CipherValue node\n");
		goto done;
    }

    /* add <dsig:KeyInfo/> and <dsig:KeyName/> nodes to <enc:EncryptedKey/> */
    keyInfoNode2 = xmlSecTmplEncDataEnsureKeyInfo(encKeyNode, NULL);
    if(keyInfoNode2 == NULL)
	{
		fprintf(stderr, "Error: failed to add key info\n");
		goto done;
    }

    /* set key name so we can lookup key when needed */
    if(xmlSecTmplKeyInfoAddKeyName(keyInfoNode2, (const unsigned
char*)keyName) == NULL) {
		fprintf(stderr, "Error: failed to add key name\n");
		goto done;
    }
    /* create encryption context */
    encCtx = xmlSecEncCtxCreate(mngr);
    if(encCtx == NULL)
	{
        fprintf(stderr,"Error: failed to create encryption context\n");
		goto done;
    }

    /* generate a Aes192 DES key */
    encCtx->encKey = xmlSecKeyGenerate(xmlSecKeyDataAesId, 192,
xmlSecKeyDataTypeSession);
    if(encCtx->encKey == NULL) {
        fprintf(stderr,"Error: failed to generate session des key\n");
	goto done;
    }
    /* encrypt the data */
    if(xmlSecEncCtxXmlEncrypt(encCtx, encDataNode, xmlDocGetRootElement(doc))
< 0) {
        fprintf(stderr,"Error: encryption failed\n");
		goto done;
    }

    /* we template is inserted in the doc */
    encDataNode = NULL;

    /* print encrypted data with document to stdout */
    xmlDocDump(stdout, doc);

    /* success */
    res = 0;

done:

    /* cleanup */
    if(encCtx != NULL)
	{
	xmlSecEncCtxDestroy(encCtx);
    }

    if(encDataNode != NULL) {
	xmlFreeNode(encDataNode);
    }

    if(doc != NULL) {
	xmlFreeDoc(doc);
    }
    return(res);
}




-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3328 bytes
Desc: not available
Url : http://www.aleksey.com/pipermail/xmlsec/attachments/20050720/98bfee47/smime-0002.bin


More information about the xmlsec mailing list