Blame nss/lib/pk11wrap/pk11skey.c

Packit 40b132
/* This Source Code Form is subject to the terms of the Mozilla Public
Packit 40b132
 * License, v. 2.0. If a copy of the MPL was not distributed with this
Packit 40b132
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
Packit 40b132
/*
Packit 40b132
 * This file implements the Symkey wrapper and the PKCS context
Packit 40b132
 * Interfaces.
Packit 40b132
 */
Packit 40b132
Packit 40b132
#include "seccomon.h"
Packit 40b132
#include "secmod.h"
Packit 40b132
#include "nssilock.h"
Packit 40b132
#include "secmodi.h"
Packit 40b132
#include "secmodti.h"
Packit 40b132
#include "pkcs11.h"
Packit 40b132
#include "pk11func.h"
Packit 40b132
#include "secitem.h"
Packit 40b132
#include "secoid.h"
Packit 40b132
#include "secerr.h"
Packit 40b132
#include "hasht.h"
Packit 40b132
Packit 40b132
static void
Packit 40b132
pk11_EnterKeyMonitor(PK11SymKey *symKey) {
Packit 40b132
    if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe)) 
Packit 40b132
	PK11_EnterSlotMonitor(symKey->slot);
Packit 40b132
}
Packit 40b132
Packit 40b132
static void
Packit 40b132
pk11_ExitKeyMonitor(PK11SymKey *symKey) {
Packit 40b132
    if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe)) 
Packit 40b132
    	PK11_ExitSlotMonitor(symKey->slot);
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * pk11_getKeyFromList returns a symKey that has a session (if needSession
Packit 40b132
 * was specified), or explicitly does not have a session (if needSession
Packit 40b132
 * was not specified).
Packit 40b132
 */
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_getKeyFromList(PK11SlotInfo *slot, PRBool needSession) {
Packit 40b132
    PK11SymKey *symKey = NULL;
Packit 40b132
Packit 40b132
    PZ_Lock(slot->freeListLock);
Packit 40b132
    /* own session list are symkeys with sessions that the symkey owns.
Packit 40b132
     * 'most' symkeys will own their own session. */
Packit 40b132
    if (needSession) {
Packit 40b132
	if (slot->freeSymKeysWithSessionHead) {
Packit 40b132
    	    symKey = slot->freeSymKeysWithSessionHead;
Packit 40b132
	    slot->freeSymKeysWithSessionHead = symKey->next;
Packit 40b132
	    slot->keyCount--;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
    /* if we don't need a symkey with its own session, or we couldn't find
Packit 40b132
     * one on the owner list, get one from the non-owner free list. */
Packit 40b132
    if (!symKey) {
Packit 40b132
	if (slot->freeSymKeysHead) {
Packit 40b132
    	    symKey = slot->freeSymKeysHead;
Packit 40b132
	    slot->freeSymKeysHead = symKey->next;
Packit 40b132
	    slot->keyCount--;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
    PZ_Unlock(slot->freeListLock);
Packit 40b132
    if (symKey) {
Packit 40b132
	symKey->next = NULL;
Packit 40b132
	if (!needSession) {
Packit 40b132
	    return symKey;
Packit 40b132
	}
Packit 40b132
	/* if we are getting an owner key, make sure we have a valid session.
Packit 40b132
         * session could be invalid if the token has been removed or because
Packit 40b132
         * we got it from the non-owner free list */
Packit 40b132
	if ((symKey->series != slot->series) || 
Packit 40b132
			 (symKey->session == CK_INVALID_SESSION)) {
Packit 40b132
	    symKey->session = pk11_GetNewSession(slot, &symKey->sessionOwner);
Packit 40b132
	}
Packit 40b132
	PORT_Assert(symKey->session != CK_INVALID_SESSION);
Packit 40b132
	if (symKey->session != CK_INVALID_SESSION)
Packit 40b132
	    return symKey;
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	/* if we are here, we need a session, but couldn't get one, it's 
Packit 40b132
	 * unlikely we pk11_GetNewSession will succeed if we call it a second
Packit 40b132
	 * time. */
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey = PORT_New(PK11SymKey);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->next = NULL;
Packit 40b132
    if (needSession) {
Packit 40b132
	symKey->session = pk11_GetNewSession(slot,&symKey->sessionOwner);
Packit 40b132
	PORT_Assert(symKey->session != CK_INVALID_SESSION);
Packit 40b132
        if (symKey->session == CK_INVALID_SESSION) {
Packit 40b132
	    PK11_FreeSymKey(symKey);
Packit 40b132
	    symKey = NULL;
Packit 40b132
	}
Packit 40b132
    } else {
Packit 40b132
	symKey->session = CK_INVALID_SESSION;
Packit 40b132
    }
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* Caller MUST hold slot->freeListLock (or ref count == 0?) !! */
Packit 40b132
void
Packit 40b132
PK11_CleanKeyList(PK11SlotInfo *slot)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey = NULL;
Packit 40b132
Packit 40b132
    while (slot->freeSymKeysWithSessionHead) {
Packit 40b132
    	symKey = slot->freeSymKeysWithSessionHead;
Packit 40b132
	slot->freeSymKeysWithSessionHead = symKey->next;
Packit 40b132
	pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
Packit 40b132
	PORT_Free(symKey);
Packit 40b132
    }
Packit 40b132
    while (slot->freeSymKeysHead) {
Packit 40b132
    	symKey = slot->freeSymKeysHead;
Packit 40b132
	slot->freeSymKeysHead = symKey->next;
Packit 40b132
	pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
Packit 40b132
	PORT_Free(symKey);
Packit 40b132
    }
Packit 40b132
    return;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * create a symetric key:
Packit 40b132
 *      Slot is the slot to create the key in.
Packit 40b132
 *      type is the mechanism type 
Packit 40b132
 *      owner is does this symKey structure own it's object handle (rare
Packit 40b132
 *        that this is false).
Packit 40b132
 *      needSession means the returned symKey will return with a valid session
Packit 40b132
 *        allocated already.
Packit 40b132
 */
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_CreateSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, 
Packit 40b132
		  PRBool owner, PRBool needSession, void *wincx)
Packit 40b132
{
Packit 40b132
Packit 40b132
    PK11SymKey *symKey = pk11_getKeyFromList(slot, needSession);
Packit 40b132
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    /* if needSession was specified, make sure we have a valid session.
Packit 40b132
     * callers which specify needSession as false should do their own
Packit 40b132
     * check of the session before returning the symKey */
Packit 40b132
    if (needSession && symKey->session == CK_INVALID_SESSION) {
Packit 40b132
    	PK11_FreeSymKey(symKey);
Packit 40b132
	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->type = type;
Packit 40b132
    symKey->data.type = siBuffer;
Packit 40b132
    symKey->data.data = NULL;
Packit 40b132
    symKey->data.len = 0;
Packit 40b132
    symKey->owner = owner;
Packit 40b132
    symKey->objectID = CK_INVALID_HANDLE;
Packit 40b132
    symKey->slot = slot;
Packit 40b132
    symKey->series = slot->series;
Packit 40b132
    symKey->cx = wincx;
Packit 40b132
    symKey->size = 0;
Packit 40b132
    symKey->refCount = 1;
Packit 40b132
    symKey->origin = PK11_OriginNULL;
Packit 40b132
    symKey->parent = NULL;
Packit 40b132
    symKey->freeFunc = NULL;
Packit 40b132
    symKey->userData = NULL;
Packit 40b132
    PK11_ReferenceSlot(slot);
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * destroy a symetric key
Packit 40b132
 */
Packit 40b132
void
Packit 40b132
PK11_FreeSymKey(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot;
Packit 40b132
    PRBool freeit = PR_TRUE;
Packit 40b132
Packit 40b132
    if (PR_ATOMIC_DECREMENT(&symKey->refCount) == 0) {
Packit 40b132
	PK11SymKey *parent = symKey->parent;
Packit 40b132
Packit 40b132
	symKey->parent = NULL;
Packit 40b132
	if ((symKey->owner) && symKey->objectID != CK_INVALID_HANDLE) {
Packit 40b132
	    pk11_EnterKeyMonitor(symKey);
Packit 40b132
	    (void) PK11_GETTAB(symKey->slot)->
Packit 40b132
		C_DestroyObject(symKey->session, symKey->objectID);
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
	}
Packit 40b132
	if (symKey->data.data) {
Packit 40b132
	    PORT_Memset(symKey->data.data, 0, symKey->data.len);
Packit 40b132
	    PORT_Free(symKey->data.data);
Packit 40b132
	}
Packit 40b132
	/* free any existing data */
Packit 40b132
	if (symKey->userData && symKey->freeFunc) {
Packit 40b132
	    (*symKey->freeFunc)(symKey->userData);
Packit 40b132
	}
Packit 40b132
        slot = symKey->slot;
Packit 40b132
        PZ_Lock(slot->freeListLock);
Packit 40b132
	if (slot->keyCount < slot->maxKeyCount) {
Packit 40b132
	    /* 
Packit 40b132
             * freeSymkeysWithSessionHead contain a list of reusable
Packit 40b132
	     *  SymKey structures with valid sessions.
Packit 40b132
	     *    sessionOwner must be true.
Packit 40b132
             *    session must be valid.
Packit 40b132
             * freeSymKeysHead contain a list of SymKey structures without
Packit 40b132
             *  valid session.
Packit 40b132
             *    session must be CK_INVALID_SESSION.
Packit 40b132
	     *    though sessionOwner is false, callers should not depend on
Packit 40b132
	     *    this fact.
Packit 40b132
	     */
Packit 40b132
	    if (symKey->sessionOwner) {
Packit 40b132
		PORT_Assert (symKey->session != CK_INVALID_SESSION);
Packit 40b132
		symKey->next = slot->freeSymKeysWithSessionHead;
Packit 40b132
		slot->freeSymKeysWithSessionHead = symKey;
Packit 40b132
	    } else {
Packit 40b132
		symKey->session = CK_INVALID_SESSION;
Packit 40b132
		symKey->next = slot->freeSymKeysHead;
Packit 40b132
		slot->freeSymKeysHead = symKey;
Packit 40b132
	    }
Packit 40b132
	    slot->keyCount++;
Packit 40b132
	    symKey->slot = NULL;
Packit 40b132
	    freeit = PR_FALSE;
Packit 40b132
        }
Packit 40b132
	PZ_Unlock(slot->freeListLock);
Packit 40b132
        if (freeit) {
Packit 40b132
	    pk11_CloseSession(symKey->slot, symKey->session,
Packit 40b132
							symKey->sessionOwner);
Packit 40b132
	    PORT_Free(symKey);
Packit 40b132
	}
Packit 40b132
	PK11_FreeSlot(slot);
Packit 40b132
Packit 40b132
	if (parent) {
Packit 40b132
	    PK11_FreeSymKey(parent);
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_ReferenceSymKey(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    PR_ATOMIC_INCREMENT(&symKey->refCount);
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Accessors
Packit 40b132
 */
Packit 40b132
CK_MECHANISM_TYPE
Packit 40b132
PK11_GetMechanism(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return symKey->type;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * return the slot associated with a symetric key
Packit 40b132
 */
Packit 40b132
PK11SlotInfo *
Packit 40b132
PK11_GetSlotFromKey(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return PK11_ReferenceSlot(symKey->slot);
Packit 40b132
}
Packit 40b132
Packit 40b132
CK_KEY_TYPE PK11_GetSymKeyType(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return PK11_GetKeyType(symKey->type,symKey->size);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_GetNextSymKey(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return symKey ? symKey->next : NULL;
Packit 40b132
}
Packit 40b132
Packit 40b132
char *
Packit 40b132
PK11_GetSymKeyNickname(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return PK11_GetObjectNickname(symKey->slot,symKey->objectID);
Packit 40b132
}
Packit 40b132
Packit 40b132
SECStatus
Packit 40b132
PK11_SetSymKeyNickname(PK11SymKey *symKey, const char *nickname)
Packit 40b132
{
Packit 40b132
    return PK11_SetObjectNickname(symKey->slot,symKey->objectID,nickname);
Packit 40b132
}
Packit 40b132
Packit 40b132
void *
Packit 40b132
PK11_GetSymKeyUserData(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return symKey->userData;
Packit 40b132
}
Packit 40b132
Packit 40b132
void
Packit 40b132
PK11_SetSymKeyUserData(PK11SymKey *symKey, void *userData, 
Packit 40b132
                                              PK11FreeDataFunc freeFunc)
Packit 40b132
{
Packit 40b132
    /* free any existing data */
Packit 40b132
    if (symKey->userData && symKey->freeFunc) {
Packit 40b132
	(*symKey->freeFunc)(symKey->userData);
Packit 40b132
    }
Packit 40b132
    symKey->userData = userData;
Packit 40b132
    symKey->freeFunc = freeFunc;
Packit 40b132
    return;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * turn key handle into an appropriate key object
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent, PK11Origin origin,
Packit 40b132
    CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID, PRBool owner, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    PRBool needSession = !(owner && parent);
Packit 40b132
Packit 40b132
    if (keyID == CK_INVALID_HANDLE) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey = pk11_CreateSymKey(slot, type, owner, needSession, wincx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->objectID = keyID;
Packit 40b132
    symKey->origin = origin;
Packit 40b132
Packit 40b132
    /* adopt the parent's session */
Packit 40b132
    /* This is only used by SSL. What we really want here is a session
Packit 40b132
     * structure with a ref count so  the session goes away only after all the
Packit 40b132
     * keys do. */
Packit 40b132
    if (!needSession) {
Packit 40b132
	symKey->sessionOwner = PR_FALSE;
Packit 40b132
	symKey->session = parent->session;
Packit 40b132
	symKey->parent = PK11_ReferenceSymKey(parent);
Packit 40b132
        /* This is the only case where pk11_CreateSymKey does not explicitly
Packit 40b132
	 * check symKey->session. We need to assert here to make sure.
Packit 40b132
	 * the session isn't invalid. */
Packit 40b132
	PORT_Assert(parent->session != CK_INVALID_SESSION);
Packit 40b132
	if (parent->session == CK_INVALID_SESSION) {
Packit 40b132
	    PK11_FreeSymKey(symKey);
Packit 40b132
	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
Packit 40b132
	    return NULL;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * turn key handle into an appropriate key object
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_GetWrapKey(PK11SlotInfo *slot, int wrap, CK_MECHANISM_TYPE type,
Packit 40b132
						    int series, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey = NULL;
Packit 40b132
Packit 40b132
    if (slot->series != series) return NULL;
Packit 40b132
    if (slot->refKeys[wrap] == CK_INVALID_HANDLE) return NULL;
Packit 40b132
    if (type == CKM_INVALID_MECHANISM) type = slot->wrapMechanism;
Packit 40b132
Packit 40b132
    symKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive,
Packit 40b132
		 slot->wrapMechanism, slot->refKeys[wrap], PR_FALSE, wincx);
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This function is not thread-safe because it sets wrapKey->sessionOwner
Packit 40b132
 * without using a lock or atomic routine.  It can only be called when
Packit 40b132
 * only one thread has a reference to wrapKey.
Packit 40b132
 */
Packit 40b132
void
Packit 40b132
PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey)
Packit 40b132
{
Packit 40b132
    /* save the handle and mechanism for the wrapping key */
Packit 40b132
    /* mark the key and session as not owned by us to they don't get freed
Packit 40b132
     * when the key goes way... that lets us reuse the key later */
Packit 40b132
    slot->refKeys[wrap] = wrapKey->objectID;
Packit 40b132
    wrapKey->owner = PR_FALSE;
Packit 40b132
    wrapKey->sessionOwner = PR_FALSE;
Packit 40b132
    slot->wrapMechanism = wrapKey->type;
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * figure out if a key is still valid or if it is stale.
Packit 40b132
 */
Packit 40b132
PRBool
Packit 40b132
PK11_VerifyKeyOK(PK11SymKey *key) {
Packit 40b132
    if (!PK11_IsPresent(key->slot)) {
Packit 40b132
	return PR_FALSE;
Packit 40b132
    }
Packit 40b132
    return (PRBool)(key->series == key->slot->series);
Packit 40b132
}
Packit 40b132
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_ImportSymKeyWithTempl(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
                  PK11Origin origin, PRBool isToken, CK_ATTRIBUTE *keyTemplate,
Packit 40b132
		  unsigned int templateCount, SECItem *key, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *    symKey;
Packit 40b132
    SECStatus	    rv;
Packit 40b132
Packit 40b132
    symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE, wincx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->size = key->len;
Packit 40b132
Packit 40b132
    PK11_SETATTRS(&keyTemplate[templateCount], CKA_VALUE, key->data, key->len);
Packit 40b132
    templateCount++;
Packit 40b132
Packit 40b132
    if (SECITEM_CopyItem(NULL,&symKey->data,key) != SECSuccess) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->origin = origin;
Packit 40b132
Packit 40b132
    /* import the keys */
Packit 40b132
    rv = PK11_CreateNewObject(slot, symKey->session, keyTemplate,
Packit 40b132
		 	templateCount, isToken, &symKey->objectID);
Packit 40b132
    if ( rv != SECSuccess) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * turn key bits into an appropriate key object
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
     PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *    symKey;
Packit 40b132
    unsigned int    templateCount = 0;
Packit 40b132
    CK_OBJECT_CLASS keyClass 	= CKO_SECRET_KEY;
Packit 40b132
    CK_KEY_TYPE     keyType 	= CKK_GENERIC_SECRET;
Packit 40b132
    CK_BBOOL        cktrue 	= CK_TRUE; /* sigh */
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[5];
Packit 40b132
    CK_ATTRIBUTE *  attrs 	= keyTemplate;
Packit 40b132
Packit 40b132
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
Packit 40b132
    templateCount = attrs - keyTemplate;
Packit 40b132
    PR_ASSERT(templateCount+1 <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    keyType = PK11_GetKeyType(type,key->len);
Packit 40b132
    symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, PR_FALSE, 
Packit 40b132
				keyTemplate, templateCount, key, wincx);
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * turn key bits into an appropriate key object
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_ImportSymKeyWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
     PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
Packit 40b132
     CK_FLAGS flags, PRBool isPerm, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *    symKey;
Packit 40b132
    unsigned int    templateCount = 0;
Packit 40b132
    CK_OBJECT_CLASS keyClass 	= CKO_SECRET_KEY;
Packit 40b132
    CK_KEY_TYPE     keyType 	= CKK_GENERIC_SECRET;
Packit 40b132
    CK_BBOOL        cktrue 	= CK_TRUE; /* sigh */
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    CK_ATTRIBUTE *  attrs 	= keyTemplate;
Packit 40b132
Packit 40b132
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
Packit 40b132
    if (isPerm) {
Packit 40b132
	PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue) ); attrs++;
Packit 40b132
	/* sigh some tokens think CKA_PRIVATE = false is a reasonable 
Packit 40b132
	 * default for secret keys */
Packit 40b132
	PK11_SETATTRS(attrs, CKA_PRIVATE, &cktrue, sizeof(cktrue) ); attrs++;
Packit 40b132
    }
Packit 40b132
    attrs += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
Packit 40b132
    if ((operation != CKA_FLAGS_ONLY) &&
Packit 40b132
    	 !pk11_FindAttrInTemplate(keyTemplate, attrs-keyTemplate, operation)) {
Packit 40b132
        PK11_SETATTRS(attrs, operation, &cktrue, sizeof(cktrue)); attrs++;
Packit 40b132
    }
Packit 40b132
    templateCount = attrs - keyTemplate;
Packit 40b132
    PR_ASSERT(templateCount+1 <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    keyType = PK11_GetKeyType(type,key->len);
Packit 40b132
    symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, isPerm,
Packit 40b132
				 keyTemplate, templateCount, key, wincx);
Packit 40b132
    if (symKey && isPerm) {
Packit 40b132
	symKey->owner = PR_FALSE;
Packit 40b132
    }
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *keyID,
Packit 40b132
								void *wincx)
Packit 40b132
{
Packit 40b132
    CK_ATTRIBUTE findTemp[4];
Packit 40b132
    CK_ATTRIBUTE *attrs;
Packit 40b132
    CK_BBOOL ckTrue = CK_TRUE;
Packit 40b132
    CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
Packit 40b132
    int tsize = 0;
Packit 40b132
    CK_OBJECT_HANDLE key_id;
Packit 40b132
Packit 40b132
    attrs = findTemp;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++;
Packit 40b132
    if (keyID) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len); attrs++;
Packit 40b132
    }
Packit 40b132
    tsize = attrs - findTemp;
Packit 40b132
    PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    key_id = pk11_FindObjectByTemplate(slot,findTemp,tsize);
Packit 40b132
    if (key_id == CK_INVALID_HANDLE) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    return PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive, type, key_id,
Packit 40b132
		 				PR_FALSE, wincx);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_ListFixedKeysInSlot(PK11SlotInfo *slot, char *nickname, void *wincx)
Packit 40b132
{
Packit 40b132
    CK_ATTRIBUTE findTemp[4];
Packit 40b132
    CK_ATTRIBUTE *attrs;
Packit 40b132
    CK_BBOOL ckTrue = CK_TRUE;
Packit 40b132
    CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
Packit 40b132
    int tsize = 0;
Packit 40b132
    int objCount = 0;
Packit 40b132
    CK_OBJECT_HANDLE *key_ids;
Packit 40b132
    PK11SymKey *nextKey = NULL;
Packit 40b132
    PK11SymKey *topKey = NULL;
Packit 40b132
    int i,len;
Packit 40b132
Packit 40b132
    attrs = findTemp;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++;
Packit 40b132
    if (nickname) {
Packit 40b132
	len = PORT_Strlen(nickname);
Packit 40b132
	PK11_SETATTRS(attrs, CKA_LABEL, nickname, len); attrs++;
Packit 40b132
    }
Packit 40b132
    tsize = attrs - findTemp;
Packit 40b132
    PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    key_ids = pk11_FindObjectsByTemplate(slot,findTemp,tsize,&objCount);
Packit 40b132
    if (key_ids == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    for (i=0; i < objCount ; i++) {
Packit 40b132
	SECItem typeData;
Packit 40b132
	CK_KEY_TYPE type = CKK_GENERIC_SECRET;
Packit 40b132
        SECStatus rv = PK11_ReadAttribute(slot, key_ids[i], 
Packit 40b132
						CKA_KEY_TYPE, NULL, &typeData);
Packit 40b132
	if (rv == SECSuccess) {
Packit 40b132
	    if (typeData.len == sizeof(CK_KEY_TYPE)) {
Packit 40b132
	    	type = *(CK_KEY_TYPE *)typeData.data;
Packit 40b132
	    }
Packit 40b132
	    PORT_Free(typeData.data);
Packit 40b132
	}
Packit 40b132
	nextKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive, 
Packit 40b132
		PK11_GetKeyMechanism(type), key_ids[i], PR_FALSE, wincx);
Packit 40b132
	if (nextKey) {
Packit 40b132
	    nextKey->next = topKey;
Packit 40b132
	    topKey = nextKey;
Packit 40b132
	}
Packit 40b132
   }
Packit 40b132
   PORT_Free(key_ids);
Packit 40b132
   return topKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
void *
Packit 40b132
PK11_GetWindow(PK11SymKey *key)
Packit 40b132
{
Packit 40b132
   return key->cx;
Packit 40b132
}
Packit 40b132
    
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * extract a symetric key value. NOTE: if the key is sensitive, we will
Packit 40b132
 * not be able to do this operation. This function is used to move
Packit 40b132
 * keys from one token to another */
Packit 40b132
SECStatus
Packit 40b132
PK11_ExtractKeyValue(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    SECStatus rv;
Packit 40b132
Packit 40b132
    if (symKey->data.data != NULL) {
Packit 40b132
	if (symKey->size == 0) {
Packit 40b132
	   symKey->size = symKey->data.len;
Packit 40b132
	}
Packit 40b132
	return SECSuccess;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (symKey->slot == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_KEY );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    rv = PK11_ReadAttribute(symKey->slot,symKey->objectID,CKA_VALUE,NULL,
Packit 40b132
				&symKey->data);
Packit 40b132
    if (rv == SECSuccess) {
Packit 40b132
	symKey->size = symKey->data.len;
Packit 40b132
    }
Packit 40b132
    return rv;
Packit 40b132
}
Packit 40b132
Packit 40b132
SECStatus
Packit 40b132
PK11_DeleteTokenSymKey(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    if (!PK11_IsPermObject(symKey->slot, symKey->objectID)) {
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
    PK11_DestroyTokenObject(symKey->slot,symKey->objectID);
Packit 40b132
    symKey->objectID = CK_INVALID_HANDLE;
Packit 40b132
    return SECSuccess;
Packit 40b132
}
Packit 40b132
Packit 40b132
SECItem *
Packit 40b132
PK11_GetKeyData(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return &symKey->data;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* This symbol is exported for backward compatibility. */
Packit 40b132
SECItem *
Packit 40b132
__PK11_GetKeyData(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return PK11_GetKeyData(symKey);
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * PKCS #11 key Types with predefined length
Packit 40b132
 */
Packit 40b132
unsigned int
Packit 40b132
pk11_GetPredefinedKeyLength(CK_KEY_TYPE keyType)
Packit 40b132
{
Packit 40b132
    int length = 0;
Packit 40b132
    switch (keyType) {
Packit 40b132
      case CKK_DES: length = 8; break;
Packit 40b132
      case CKK_DES2: length = 16; break;
Packit 40b132
      case CKK_DES3: length = 24; break;
Packit 40b132
      case CKK_SKIPJACK: length = 10; break;
Packit 40b132
      case CKK_BATON: length = 20; break;
Packit 40b132
      case CKK_JUNIPER: length = 20; break;
Packit 40b132
      default: break;
Packit 40b132
    }
Packit 40b132
    return length;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* return the keylength if possible.  '0' if not */
Packit 40b132
unsigned int
Packit 40b132
PK11_GetKeyLength(PK11SymKey *key)
Packit 40b132
{
Packit 40b132
    CK_KEY_TYPE keyType;
Packit 40b132
Packit 40b132
    if (key->size != 0) return key->size;
Packit 40b132
Packit 40b132
    /* First try to figure out the key length from its type */
Packit 40b132
    keyType = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_KEY_TYPE);
Packit 40b132
    key->size = pk11_GetPredefinedKeyLength(keyType);
Packit 40b132
    if ((keyType == CKK_GENERIC_SECRET) &&
Packit 40b132
	(key->type == CKM_SSL3_PRE_MASTER_KEY_GEN))  {
Packit 40b132
	key->size=48;
Packit 40b132
    }
Packit 40b132
Packit 40b132
   if( key->size != 0 ) return key->size;
Packit 40b132
Packit 40b132
   if (key->data.data == NULL) {
Packit 40b132
	PK11_ExtractKeyValue(key);
Packit 40b132
   }
Packit 40b132
   /* key is probably secret. Look up its length */
Packit 40b132
   /*  this is new PKCS #11 version 2.0 functionality. */
Packit 40b132
   if (key->size == 0) {
Packit 40b132
	CK_ULONG keyLength;
Packit 40b132
Packit 40b132
	keyLength = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_VALUE_LEN);
Packit 40b132
	if (keyLength != CK_UNAVAILABLE_INFORMATION) {
Packit 40b132
	    key->size = (unsigned int)keyLength;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
   return key->size;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* return the strength of a key. This is different from length in that
Packit 40b132
 * 1) it returns the size in bits, and 2) it returns only the secret portions
Packit 40b132
 * of the key minus any checksums or parity.
Packit 40b132
 */
Packit 40b132
unsigned int
Packit 40b132
PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid) 
Packit 40b132
{
Packit 40b132
     int size=0;
Packit 40b132
     CK_MECHANISM_TYPE mechanism= CKM_INVALID_MECHANISM; /* RC2 only */
Packit 40b132
     SECItem *param = NULL; /* RC2 only */
Packit 40b132
     CK_RC2_CBC_PARAMS *rc2_params = NULL; /* RC2 ONLY */
Packit 40b132
     unsigned int effectiveBits = 0; /* RC2 ONLY */
Packit 40b132
Packit 40b132
     switch (PK11_GetKeyType(key->type,0)) {
Packit 40b132
     case CKK_CDMF:
Packit 40b132
	return 40;
Packit 40b132
     case CKK_DES:
Packit 40b132
	return 56;
Packit 40b132
     case CKK_DES3:
Packit 40b132
     case CKK_DES2:
Packit 40b132
	size = PK11_GetKeyLength(key);
Packit 40b132
	if (size == 16) {
Packit 40b132
	   /* double des */
Packit 40b132
	   return 112; /* 16*7 */
Packit 40b132
	}
Packit 40b132
	return 168;
Packit 40b132
    /*
Packit 40b132
     * RC2 has is different than other ciphers in that it allows the user
Packit 40b132
     * to deprecating keysize while still requiring all the bits for the 
Packit 40b132
     * original key. The info
Packit 40b132
     * on what the effective key strength is in the parameter for the key.
Packit 40b132
     * In S/MIME this parameter is stored in the DER encoded algid. In Our 
Packit 40b132
     * other uses of RC2, effectiveBits == keyBits, so this code functions
Packit 40b132
     * correctly without an algid.
Packit 40b132
     */
Packit 40b132
    case CKK_RC2:
Packit 40b132
	/* if no algid was provided, fall through to default */
Packit 40b132
        if (!algid) {
Packit 40b132
	    break; 
Packit 40b132
	}
Packit 40b132
	/* verify that the algid is for RC2 */
Packit 40b132
	mechanism = PK11_AlgtagToMechanism(SECOID_GetAlgorithmTag(algid));
Packit 40b132
	if ((mechanism != CKM_RC2_CBC) && (mechanism != CKM_RC2_ECB)) {
Packit 40b132
	    break;
Packit 40b132
	}
Packit 40b132
Packit 40b132
	/* now get effective bits from the algorithm ID. */
Packit 40b132
	param = PK11_ParamFromAlgid(algid);
Packit 40b132
	/* if we couldn't get memory just use key length */
Packit 40b132
	if (param == NULL) {
Packit 40b132
	    break;
Packit 40b132
	}
Packit 40b132
Packit 40b132
	rc2_params = (CK_RC2_CBC_PARAMS *) param->data;
Packit 40b132
	/* paranoia... shouldn't happen */
Packit 40b132
	PORT_Assert(param->data != NULL);
Packit 40b132
	if (param->data == NULL) {
Packit 40b132
	    SECITEM_FreeItem(param,PR_TRUE);
Packit 40b132
	    break;
Packit 40b132
	}
Packit 40b132
	effectiveBits = (unsigned int)rc2_params->ulEffectiveBits;
Packit 40b132
	SECITEM_FreeItem(param,PR_TRUE);
Packit 40b132
	param = NULL; rc2_params=NULL; /* paranoia */
Packit 40b132
Packit 40b132
	/* we have effective bits, is and allocated memory is free, now
Packit 40b132
	 * we need to return the smaller of effective bits and keysize */
Packit 40b132
	size = PK11_GetKeyLength(key);
Packit 40b132
	if ((unsigned int)size*8 > effectiveBits) {
Packit 40b132
	    return effectiveBits;
Packit 40b132
	}
Packit 40b132
Packit 40b132
	return size*8; /* the actual key is smaller, the strength can't be
Packit 40b132
			* greater than the actual key size */
Packit 40b132
	
Packit 40b132
    default:
Packit 40b132
	break;
Packit 40b132
    }
Packit 40b132
    return PK11_GetKeyLength(key) * 8;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * The next three utilities are to deal with the fact that a given operation
Packit 40b132
 * may be a multi-slot affair. This creates a new key object that is copied
Packit 40b132
 * into the new slot.
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
pk11_CopyToSlotPerm(PK11SlotInfo *slot,CK_MECHANISM_TYPE type, 
Packit 40b132
	 	CK_ATTRIBUTE_TYPE operation, CK_FLAGS flags, 
Packit 40b132
		PRBool isPerm, PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    SECStatus rv;
Packit 40b132
    PK11SymKey *newKey = NULL;
Packit 40b132
Packit 40b132
    /* Extract the raw key data if possible */
Packit 40b132
    if (symKey->data.data == NULL) {
Packit 40b132
	rv = PK11_ExtractKeyValue(symKey);
Packit 40b132
	/* KEY is sensitive, we're try key exchanging it. */
Packit 40b132
	if (rv != SECSuccess) {
Packit 40b132
	    return pk11_KeyExchange(slot, type, operation, 
Packit 40b132
						flags, isPerm, symKey);
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    newKey = PK11_ImportSymKeyWithFlags(slot,  type, symKey->origin,
Packit 40b132
	operation, &symKey->data, flags, isPerm, symKey->cx);
Packit 40b132
    if (newKey == NULL) {
Packit 40b132
	newKey = pk11_KeyExchange(slot, type, operation, flags, isPerm, symKey);
Packit 40b132
    }
Packit 40b132
    return newKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
pk11_CopyToSlot(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
Packit 40b132
	CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
   return pk11_CopyToSlotPerm(slot, type, operation, 0, PR_FALSE, symKey);
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Make sure the slot we are in is the correct slot for the operation
Packit 40b132
 * by verifying that it supports all of the specified mechanism types.
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
pk11_ForceSlotMultiple(PK11SymKey *symKey, CK_MECHANISM_TYPE *type,
Packit 40b132
			int mechCount, CK_ATTRIBUTE_TYPE operation)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot = symKey->slot;
Packit 40b132
    PK11SymKey *newKey = NULL;
Packit 40b132
    PRBool needToCopy = PR_FALSE;
Packit 40b132
    int i;
Packit 40b132
Packit 40b132
    if (slot == NULL) {
Packit 40b132
	needToCopy = PR_TRUE;
Packit 40b132
    } else {
Packit 40b132
	i = 0;
Packit 40b132
	while ((i < mechCount) && (needToCopy == PR_FALSE)) {
Packit 40b132
	    if (!PK11_DoesMechanism(slot,type[i])) {
Packit 40b132
		needToCopy = PR_TRUE;
Packit 40b132
	    }
Packit 40b132
	    i++;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (needToCopy == PR_TRUE) {
Packit 40b132
	slot = PK11_GetBestSlotMultiple(type,mechCount,symKey->cx);
Packit 40b132
	if (slot == NULL) {
Packit 40b132
	    PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
	    return NULL;
Packit 40b132
	}
Packit 40b132
	newKey = pk11_CopyToSlot(slot, type[0], operation, symKey);
Packit 40b132
	PK11_FreeSlot(slot);
Packit 40b132
    }
Packit 40b132
    return newKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Make sure the slot we are in is the correct slot for the operation
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
pk11_ForceSlot(PK11SymKey *symKey,CK_MECHANISM_TYPE type,
Packit 40b132
						CK_ATTRIBUTE_TYPE operation)
Packit 40b132
{
Packit 40b132
    return pk11_ForceSlotMultiple(symKey, &type, 1, operation);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_MoveSymKey(PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
			CK_FLAGS flags, PRBool  perm, PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    if (symKey->slot == slot) {
Packit 40b132
	if (perm) {
Packit 40b132
	   return PK11_ConvertSessionSymKeyToTokenSymKey(symKey,symKey->cx);
Packit 40b132
	} else {
Packit 40b132
	   return PK11_ReferenceSymKey(symKey);
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
    
Packit 40b132
    return pk11_CopyToSlotPerm(slot, symKey->type, 
Packit 40b132
					operation, flags, perm, symKey);
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Use the token to generate a key. 
Packit 40b132
 * 
Packit 40b132
 * keySize must be 'zero' for fixed key length algorithms. A nonzero 
Packit 40b132
 *  keySize causes the CKA_VALUE_LEN attribute to be added to the template 
Packit 40b132
 *  for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN 
Packit 40b132
 *  attribute for keys with fixed length. The exception is DES2. If you
Packit 40b132
 *  select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
Packit 40b132
 *  parameter and use the key size to determine which underlying DES keygen
Packit 40b132
 *  function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
Packit 40b132
 *
Packit 40b132
 * keyType must be -1 for most algorithms. Some PBE algorthims cannot 
Packit 40b132
 *  determine the correct key type from the mechanism or the parameters,
Packit 40b132
 *  so key type must be specified. Other PKCS #11 mechanisms may do so in
Packit 40b132
 *  the future. Currently there is no need to export this publically.
Packit 40b132
 *  Keep it private until there is a need in case we need to expand the
Packit 40b132
 *  keygen parameters again...
Packit 40b132
 *
Packit 40b132
 * CK_FLAGS flags: key operation flags
Packit 40b132
 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
pk11_TokenKeyGenWithFlagsAndKeyType(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
    SECItem *param, CK_KEY_TYPE keyType, int keySize, SECItem *keyid, 
Packit 40b132
    CK_FLAGS opFlags, PK11AttrFlags attrFlags, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    CK_ATTRIBUTE genTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    CK_ATTRIBUTE *attrs = genTemplate;
Packit 40b132
    int count = sizeof(genTemplate)/sizeof(genTemplate[0]);
Packit 40b132
    CK_MECHANISM_TYPE keyGenType;
Packit 40b132
    CK_BBOOL cktrue = CK_TRUE;
Packit 40b132
    CK_BBOOL ckfalse = CK_FALSE;
Packit 40b132
    CK_ULONG ck_key_size;       /* only used for variable-length keys */
Packit 40b132
Packit 40b132
    if (pk11_BadAttrFlags(attrFlags)) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if ((keySize != 0) && (type != CKM_DES3_CBC) && 
Packit 40b132
		(type !=CKM_DES3_CBC_PAD) && (type != CKM_DES3_ECB)) {
Packit 40b132
        ck_key_size = keySize; /* Convert to PK11 type */
Packit 40b132
Packit 40b132
        PK11_SETATTRS(attrs, CKA_VALUE_LEN, &ck_key_size, sizeof(ck_key_size)); 
Packit 40b132
							attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (keyType != -1) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(CK_KEY_TYPE)); 
Packit 40b132
							attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* Include key id value if provided */
Packit 40b132
    if (keyid) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_ID, keyid->data, keyid->len); attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
Packit 40b132
    attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
Packit 40b132
Packit 40b132
    count = attrs - genTemplate;
Packit 40b132
    PR_ASSERT(count <= sizeof(genTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    keyGenType = PK11_GetKeyGenWithSize(type, keySize);
Packit 40b132
    if (keyGenType == CKM_FAKE_RANDOM) {
Packit 40b132
        PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
        return NULL;
Packit 40b132
    }
Packit 40b132
    symKey = PK11_KeyGenWithTemplate(slot, type, keyGenType,
Packit 40b132
                                     param, genTemplate, count, wincx);
Packit 40b132
    if (symKey != NULL) {
Packit 40b132
        symKey->size = keySize;
Packit 40b132
    }
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Use the token to generate a key.  - Public
Packit 40b132
 * 
Packit 40b132
 * keySize must be 'zero' for fixed key length algorithms. A nonzero 
Packit 40b132
 *  keySize causes the CKA_VALUE_LEN attribute to be added to the template 
Packit 40b132
 *  for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN 
Packit 40b132
 *  attribute for keys with fixed length. The exception is DES2. If you
Packit 40b132
 *  select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
Packit 40b132
 *  parameter and use the key size to determine which underlying DES keygen
Packit 40b132
 *  function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
Packit 40b132
 *
Packit 40b132
 * CK_FLAGS flags: key operation flags
Packit 40b132
 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_TokenKeyGenWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
    SECItem *param, int keySize, SECItem *keyid, CK_FLAGS opFlags,
Packit 40b132
    PK11AttrFlags attrFlags, void *wincx)
Packit 40b132
{
Packit 40b132
    return pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param, -1, keySize, 
Packit 40b132
	keyid, opFlags, attrFlags, wincx);
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * Use the token to generate a key. keySize must be 'zero' for fixed key
Packit 40b132
 * length algorithms. A nonzero keySize causes the CKA_VALUE_LEN attribute
Packit 40b132
 * to be added to the template for the key. PKCS #11 modules fail if you
Packit 40b132
 * specify the CKA_VALUE_LEN attribute for keys with fixed length.
Packit 40b132
 * NOTE: this means to generate a DES2 key from this interface you must
Packit 40b132
 * specify CKM_DES2_KEY_GEN as the mechanism directly; specifying
Packit 40b132
 * CKM_DES3_CBC as the mechanism and 16 as keySize currently doesn't work.
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
Packit 40b132
    int keySize, SECItem *keyid, PRBool isToken, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    PRBool weird = PR_FALSE;   /* hack for fortezza */
Packit 40b132
    CK_FLAGS opFlags = CKF_SIGN;
Packit 40b132
    PK11AttrFlags attrFlags = 0;
Packit 40b132
Packit 40b132
    if ((keySize == -1) && (type == CKM_SKIPJACK_CBC64)) {
Packit 40b132
	weird = PR_TRUE;
Packit 40b132
	keySize = 0;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    opFlags |= weird ? CKF_DECRYPT : CKF_ENCRYPT;
Packit 40b132
Packit 40b132
    if (isToken) {
Packit 40b132
	attrFlags |= (PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey = pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param, 
Packit 40b132
			-1, keySize, keyid, opFlags, attrFlags, wincx);
Packit 40b132
    if (symKey && weird) {
Packit 40b132
	PK11_SetFortezzaHack(symKey);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
Packit 40b132
						int keySize, void *wincx)
Packit 40b132
{
Packit 40b132
    return PK11_TokenKeyGen(slot, type, param, keySize, 0, PR_FALSE, wincx);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_KeyGenWithTemplate(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
Packit 40b132
                        CK_MECHANISM_TYPE keyGenType,
Packit 40b132
                        SECItem *param, CK_ATTRIBUTE * attrs,
Packit 40b132
                        unsigned int attrsCount, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
    CK_MECHANISM mechanism;
Packit 40b132
    CK_RV crv;
Packit 40b132
    PRBool isToken = CK_FALSE;
Packit 40b132
    CK_ULONG keySize = 0;
Packit 40b132
    unsigned i;
Packit 40b132
Packit 40b132
    /* Extract the template's CKA_VALUE_LEN into keySize and CKA_TOKEN into
Packit 40b132
       isToken. */
Packit 40b132
    for (i = 0; i < attrsCount; ++i) {
Packit 40b132
        switch (attrs[i].type) {
Packit 40b132
            case CKA_VALUE_LEN:
Packit 40b132
                if (attrs[i].pValue == NULL ||
Packit 40b132
                    attrs[i].ulValueLen != sizeof(CK_ULONG)) {
Packit 40b132
                    PORT_SetError(PK11_MapError(CKR_TEMPLATE_INCONSISTENT));
Packit 40b132
                    return NULL;
Packit 40b132
                }
Packit 40b132
                keySize = * (CK_ULONG *) attrs[i].pValue;
Packit 40b132
                break;
Packit 40b132
            case CKA_TOKEN:
Packit 40b132
                if (attrs[i].pValue == NULL || 
Packit 40b132
                    attrs[i].ulValueLen != sizeof(CK_BBOOL)) {
Packit 40b132
                    PORT_SetError(PK11_MapError(CKR_TEMPLATE_INCONSISTENT));
Packit 40b132
                    return NULL;
Packit 40b132
                }
Packit 40b132
                isToken = (*(CK_BBOOL*)attrs[i].pValue) ? PR_TRUE : PR_FALSE;
Packit 40b132
                break;
Packit 40b132
        }
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* find a slot to generate the key into */
Packit 40b132
    /* Only do slot management if this is not a token key */
Packit 40b132
    if (!isToken && (slot == NULL || !PK11_DoesMechanism(slot,type))) {
Packit 40b132
        PK11SlotInfo *bestSlot = PK11_GetBestSlot(type,wincx);
Packit 40b132
        if (bestSlot == NULL) {
Packit 40b132
            PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
            return NULL;
Packit 40b132
        }
Packit 40b132
        symKey = pk11_CreateSymKey(bestSlot, type, !isToken, PR_TRUE, wincx);
Packit 40b132
        PK11_FreeSlot(bestSlot);
Packit 40b132
    } else {
Packit 40b132
        symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE, wincx);
Packit 40b132
    }
Packit 40b132
    if (symKey == NULL) return NULL;
Packit 40b132
Packit 40b132
    symKey->size = keySize;
Packit 40b132
    symKey->origin = PK11_OriginGenerated;
Packit 40b132
Packit 40b132
    /* Set the parameters for the key gen if provided */
Packit 40b132
    mechanism.mechanism = keyGenType;
Packit 40b132
    mechanism.pParameter = NULL;
Packit 40b132
    mechanism.ulParameterLen = 0;
Packit 40b132
    if (param) {
Packit 40b132
        mechanism.pParameter = param->data;
Packit 40b132
        mechanism.ulParameterLen = param->len;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* Get session and perform locking */
Packit 40b132
    if (isToken) {
Packit 40b132
        PK11_Authenticate(symKey->slot,PR_TRUE,wincx);
Packit 40b132
        /* Should always be original slot */
Packit 40b132
        session = PK11_GetRWSession(symKey->slot);  
Packit 40b132
        symKey->owner = PR_FALSE;
Packit 40b132
    } else {
Packit 40b132
        session = symKey->session;
Packit 40b132
        if (session != CK_INVALID_SESSION) 
Packit 40b132
            pk11_EnterKeyMonitor(symKey);
Packit 40b132
    }
Packit 40b132
    if (session == CK_INVALID_SESSION) {
Packit 40b132
        PK11_FreeSymKey(symKey);
Packit 40b132
        PORT_SetError(SEC_ERROR_BAD_DATA);
Packit 40b132
        return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    crv = PK11_GETTAB(symKey->slot)->C_GenerateKey(session,
Packit 40b132
			 &mechanism, attrs, attrsCount, &symKey->objectID);
Packit 40b132
Packit 40b132
    /* Release lock and session */
Packit 40b132
    if (isToken) {
Packit 40b132
        PK11_RestoreROSession(symKey->slot, session);
Packit 40b132
    } else {
Packit 40b132
        pk11_ExitKeyMonitor(symKey);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
        PK11_FreeSymKey(symKey);
Packit 40b132
        PORT_SetError( PK11_MapError(crv) );
Packit 40b132
        return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
/* --- */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_GenDES3TokenKey(PK11SlotInfo *slot, SECItem *keyid, void *cx)
Packit 40b132
{
Packit 40b132
  return PK11_TokenKeyGen(slot, CKM_DES3_CBC, 0, 0, keyid, PR_TRUE, cx);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey*
Packit 40b132
PK11_ConvertSessionSymKeyToTokenSymKey(PK11SymKey *symk, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo* slot = symk->slot;
Packit 40b132
    CK_ATTRIBUTE template[1];
Packit 40b132
    CK_ATTRIBUTE *attrs = template;
Packit 40b132
    CK_BBOOL cktrue = CK_TRUE;
Packit 40b132
    CK_RV crv;
Packit 40b132
    CK_OBJECT_HANDLE newKeyID;
Packit 40b132
    CK_SESSION_HANDLE rwsession;
Packit 40b132
Packit 40b132
    PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue)); attrs++;
Packit 40b132
Packit 40b132
    PK11_Authenticate(slot, PR_TRUE, wincx);
Packit 40b132
    rwsession = PK11_GetRWSession(slot);
Packit 40b132
    if (rwsession == CK_INVALID_SESSION) {
Packit 40b132
	PORT_SetError(SEC_ERROR_BAD_DATA);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    crv = PK11_GETTAB(slot)->C_CopyObject(rwsession, symk->objectID,
Packit 40b132
        template, 1, &newKeyID);
Packit 40b132
    PK11_RestoreROSession(slot, rwsession);
Packit 40b132
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
        PORT_SetError( PK11_MapError(crv) );
Packit 40b132
        return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return PK11_SymKeyFromHandle(slot, NULL /*parent*/, symk->origin,
Packit 40b132
        symk->type, newKeyID, PR_FALSE /*owner*/, NULL /*wincx*/);
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This function does a straight public key wrap (which only RSA can do).
Packit 40b132
 * Use PK11_PubGenKey and PK11_WrapSymKey to implement the FORTEZZA and
Packit 40b132
 * Diffie-Hellman Ciphers. */
Packit 40b132
SECStatus
Packit 40b132
PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
Packit 40b132
				PK11SymKey *symKey, SECItem *wrappedKey)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot;
Packit 40b132
    CK_ULONG len =  wrappedKey->len;
Packit 40b132
    PK11SymKey *newKey = NULL;
Packit 40b132
    CK_OBJECT_HANDLE id;
Packit 40b132
    CK_MECHANISM mechanism;
Packit 40b132
    PRBool owner = PR_TRUE;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
    CK_RV crv;
Packit 40b132
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* if this slot doesn't support the mechanism, go to a slot that does */
Packit 40b132
    newKey = pk11_ForceSlot(symKey,type,CKA_ENCRYPT);
Packit 40b132
    if (newKey != NULL) {
Packit 40b132
	symKey = newKey;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (symKey->slot == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    slot = symKey->slot;
Packit 40b132
    mechanism.mechanism = pk11_mapWrapKeyType(pubKey->keyType);
Packit 40b132
    mechanism.pParameter = NULL;
Packit 40b132
    mechanism.ulParameterLen = 0;
Packit 40b132
Packit 40b132
    id = PK11_ImportPublicKey(slot,pubKey,PR_FALSE);
Packit 40b132
    if (id == CK_INVALID_HANDLE) {
Packit 40b132
	if (newKey) {
Packit 40b132
	    PK11_FreeSymKey(newKey);
Packit 40b132
	}
Packit 40b132
	return SECFailure;   /* Error code has been set. */
Packit 40b132
    }
Packit 40b132
Packit 40b132
    session = pk11_GetNewSession(slot,&owner);
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
Packit 40b132
    crv = PK11_GETTAB(slot)->C_WrapKey(session,&mechanism,
Packit 40b132
		id,symKey->objectID,wrappedKey->data,&len;;
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
    pk11_CloseSession(slot,session,owner);
Packit 40b132
    if (newKey) {
Packit 40b132
	PK11_FreeSymKey(newKey);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
    wrappedKey->len = len;
Packit 40b132
    return SECSuccess;
Packit 40b132
} 
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * this little function uses the Encrypt function to wrap a key, just in
Packit 40b132
 * case we have problems with the wrap implementation for a token.
Packit 40b132
 */
Packit 40b132
static SECStatus
Packit 40b132
pk11_HandWrap(PK11SymKey *wrappingKey, SECItem *param, CK_MECHANISM_TYPE type,
Packit 40b132
			 SECItem *inKey, SECItem *outKey)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot;
Packit 40b132
    CK_ULONG len;
Packit 40b132
    SECItem *data;
Packit 40b132
    CK_MECHANISM mech;
Packit 40b132
    PRBool owner = PR_TRUE;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
    CK_RV crv;
Packit 40b132
Packit 40b132
    slot = wrappingKey->slot;
Packit 40b132
    /* use NULL IV's for wrapping */
Packit 40b132
    mech.mechanism = type;
Packit 40b132
    if (param) {
Packit 40b132
	mech.pParameter = param->data;
Packit 40b132
	mech.ulParameterLen = param->len;
Packit 40b132
    } else {
Packit 40b132
	mech.pParameter = NULL;
Packit 40b132
	mech.ulParameterLen = 0;
Packit 40b132
    }
Packit 40b132
    session = pk11_GetNewSession(slot,&owner);
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
Packit 40b132
    crv = PK11_GETTAB(slot)->C_EncryptInit(session,&mech,
Packit 40b132
							wrappingKey->objectID);
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
        if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
        pk11_CloseSession(slot,session,owner);
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* keys are almost always aligned, but if we get this far,
Packit 40b132
     * we've gone above and beyond anyway... */
Packit 40b132
    data = PK11_BlockData(inKey,PK11_GetBlockSize(type,param));
Packit 40b132
    if (data == NULL) {
Packit 40b132
        if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
        pk11_CloseSession(slot,session,owner);
Packit 40b132
	PORT_SetError(SEC_ERROR_NO_MEMORY);
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
    len = outKey->len;
Packit 40b132
    crv = PK11_GETTAB(slot)->C_Encrypt(session,data->data,data->len,
Packit 40b132
							   outKey->data, &len;;
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
    pk11_CloseSession(slot,session,owner);
Packit 40b132
    SECITEM_FreeItem(data,PR_TRUE);
Packit 40b132
    outKey->len = len;
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	return SECFailure;
Packit 40b132
    }
Packit 40b132
    return SECSuccess;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This function does a symetric based wrap.
Packit 40b132
 */
Packit 40b132
SECStatus
Packit 40b132
PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *param, 
Packit 40b132
	PK11SymKey *wrappingKey, PK11SymKey *symKey, SECItem *wrappedKey)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot;
Packit 40b132
    CK_ULONG len = wrappedKey->len;
Packit 40b132
    PK11SymKey *newKey = NULL;
Packit 40b132
    SECItem *param_save = NULL;
Packit 40b132
    CK_MECHANISM mechanism;
Packit 40b132
    PRBool owner = PR_TRUE;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
    CK_RV crv;
Packit 40b132
    SECStatus rv;
Packit 40b132
Packit 40b132
    /* if this slot doesn't support the mechanism, go to a slot that does */
Packit 40b132
    /* Force symKey and wrappingKey into the same slot */
Packit 40b132
    if ((wrappingKey->slot == NULL) || (symKey->slot != wrappingKey->slot)) {
Packit 40b132
	/* first try copying the wrapping Key to the symKey slot */
Packit 40b132
	if (symKey->slot && PK11_DoesMechanism(symKey->slot,type)) {
Packit 40b132
	    newKey = pk11_CopyToSlot(symKey->slot,type,CKA_WRAP,wrappingKey);
Packit 40b132
	}
Packit 40b132
	/* Nope, try it the other way */
Packit 40b132
	if (newKey == NULL) {
Packit 40b132
	    if (wrappingKey->slot) {
Packit 40b132
	        newKey = pk11_CopyToSlot(wrappingKey->slot,
Packit 40b132
					symKey->type, CKA_ENCRYPT, symKey);
Packit 40b132
	    }
Packit 40b132
	    /* just not playing... one last thing, can we get symKey's data?
Packit 40b132
	     * If it's possible, we it should already be in the 
Packit 40b132
	     * symKey->data.data pointer because pk11_CopyToSlot would have
Packit 40b132
	     * tried to put it there. */
Packit 40b132
	    if (newKey == NULL) {
Packit 40b132
		/* Can't get symKey's data: Game Over */
Packit 40b132
		if (symKey->data.data == NULL) {
Packit 40b132
		    PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
		    return SECFailure;
Packit 40b132
		}
Packit 40b132
		if (param == NULL) {
Packit 40b132
		    param_save = param = PK11_ParamFromIV(type,NULL);
Packit 40b132
		}
Packit 40b132
		rv = pk11_HandWrap(wrappingKey, param, type,
Packit 40b132
						&symKey->data,wrappedKey);
Packit 40b132
		if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
Packit 40b132
		return rv;
Packit 40b132
	    }
Packit 40b132
	    /* we successfully moved the sym Key */
Packit 40b132
	    symKey = newKey;
Packit 40b132
	} else {
Packit 40b132
	    /* we successfully moved the wrapping Key */
Packit 40b132
	    wrappingKey = newKey;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* at this point both keys are in the same token */
Packit 40b132
    slot = wrappingKey->slot;
Packit 40b132
    mechanism.mechanism = type;
Packit 40b132
    /* use NULL IV's for wrapping */
Packit 40b132
    if (param == NULL) {
Packit 40b132
    	param_save = param = PK11_ParamFromIV(type,NULL);
Packit 40b132
    }
Packit 40b132
    if (param) {
Packit 40b132
	mechanism.pParameter = param->data;
Packit 40b132
	mechanism.ulParameterLen = param->len;
Packit 40b132
    } else {
Packit 40b132
	mechanism.pParameter = NULL;
Packit 40b132
	mechanism.ulParameterLen = 0;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    len = wrappedKey->len;
Packit 40b132
Packit 40b132
    session = pk11_GetNewSession(slot,&owner);
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
Packit 40b132
    crv = PK11_GETTAB(slot)->C_WrapKey(session, &mechanism,
Packit 40b132
		 wrappingKey->objectID, symKey->objectID, 
Packit 40b132
						wrappedKey->data, &len;;
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
    pk11_CloseSession(slot,session,owner);
Packit 40b132
    rv = SECSuccess;
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	/* can't wrap it? try hand wrapping it... */
Packit 40b132
	do {
Packit 40b132
	    if (symKey->data.data == NULL) {
Packit 40b132
		rv = PK11_ExtractKeyValue(symKey);
Packit 40b132
		if (rv != SECSuccess) break;
Packit 40b132
	    }
Packit 40b132
	    rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data,
Packit 40b132
								 wrappedKey);
Packit 40b132
	} while (PR_FALSE);
Packit 40b132
    } else {
Packit 40b132
        wrappedKey->len = len;
Packit 40b132
    }
Packit 40b132
    if (newKey) PK11_FreeSymKey(newKey);
Packit 40b132
    if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
Packit 40b132
    return rv;
Packit 40b132
} 
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This Generates a new key based on a symetricKey
Packit 40b132
 */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_Derive( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, SECItem *param, 
Packit 40b132
             CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
Packit 40b132
	     int keySize)
Packit 40b132
{
Packit 40b132
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation, 
Packit 40b132
				   keySize, NULL, 0, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_DeriveWithFlags( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, 
Packit 40b132
	SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
	int keySize, CK_FLAGS flags)
Packit 40b132
{
Packit 40b132
    CK_BBOOL        ckTrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
Packit 40b132
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
Packit 40b132
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation, 
Packit 40b132
		  keySize, keyTemplate, templateCount, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_DeriveWithFlagsPerm( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, 
Packit 40b132
	SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
	int keySize, CK_FLAGS flags, PRBool isPerm)
Packit 40b132
{
Packit 40b132
    CK_BBOOL        cktrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    CK_ATTRIBUTE    *attrs;
Packit 40b132
    unsigned int    templateCount = 0;
Packit 40b132
Packit 40b132
    attrs = keyTemplate;
Packit 40b132
    if (isPerm) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_TOKEN,  &cktrue, sizeof(CK_BBOOL)); attrs++;
Packit 40b132
    }
Packit 40b132
    templateCount = attrs - keyTemplate;
Packit 40b132
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
Packit 40b132
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation, 
Packit 40b132
				   keySize, keyTemplate, templateCount, isPerm);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_DeriveWithTemplate( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, 
Packit 40b132
	SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
	int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs,
Packit 40b132
							 PRBool isPerm)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *  slot	= baseKey->slot;
Packit 40b132
    PK11SymKey *    symKey;
Packit 40b132
    PK11SymKey *    newBaseKey	= NULL;
Packit 40b132
    CK_BBOOL        cktrue	= CK_TRUE; 
Packit 40b132
    CK_OBJECT_CLASS keyClass	= CKO_SECRET_KEY;
Packit 40b132
    CK_KEY_TYPE     keyType	= CKK_GENERIC_SECRET;
Packit 40b132
    CK_ULONG        valueLen	= 0;
Packit 40b132
    CK_MECHANISM    mechanism; 
Packit 40b132
    CK_RV           crv;
Packit 40b132
#define MAX_ADD_ATTRS 4
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS + MAX_ADD_ATTRS];
Packit 40b132
#undef MAX_ADD_ATTRS
Packit 40b132
    CK_ATTRIBUTE *  attrs	= keyTemplate;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
Packit 40b132
    if (numAttrs > MAX_TEMPL_ATTRS) {
Packit 40b132
    	PORT_SetError(SEC_ERROR_INVALID_ARGS);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* first copy caller attributes in. */
Packit 40b132
    for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
Packit 40b132
    	*attrs++ = *userAttr++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* We only add the following attributes to the template if the caller
Packit 40b132
    ** didn't already supply them.
Packit 40b132
    */
Packit 40b132
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
Packit 40b132
	PK11_SETATTRS(attrs, CKA_CLASS,     &keyClass, sizeof keyClass); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
Packit 40b132
	keyType = PK11_GetKeyType(target, keySize);
Packit 40b132
	PK11_SETATTRS(attrs, CKA_KEY_TYPE,  &keyType,  sizeof keyType ); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
    if (keySize > 0 &&
Packit 40b132
    	  !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
Packit 40b132
	valueLen = (CK_ULONG)keySize;
Packit 40b132
	PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
    if ((operation != CKA_FLAGS_ONLY) &&
Packit 40b132
	  !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
Packit 40b132
	PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue); attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    templateCount = attrs - keyTemplate;
Packit 40b132
    PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    /* move the key to a slot that can do the function */
Packit 40b132
    if (!PK11_DoesMechanism(slot,derive)) {
Packit 40b132
	/* get a new base key & slot */
Packit 40b132
	PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
Packit 40b132
Packit 40b132
	if (newSlot == NULL) return NULL;
Packit 40b132
Packit 40b132
        newBaseKey = pk11_CopyToSlot (newSlot, derive, CKA_DERIVE, 
Packit 40b132
				     baseKey);
Packit 40b132
	PK11_FreeSlot(newSlot);
Packit 40b132
	if (newBaseKey == NULL) 
Packit 40b132
	    return NULL;	
Packit 40b132
	baseKey = newBaseKey;
Packit 40b132
	slot = baseKey->slot;
Packit 40b132
    }
Packit 40b132
Packit 40b132
Packit 40b132
    /* get our key Structure */
Packit 40b132
    symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE, baseKey->cx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->size = keySize;
Packit 40b132
Packit 40b132
    mechanism.mechanism = derive;
Packit 40b132
    if (param) {
Packit 40b132
	mechanism.pParameter = param->data;
Packit 40b132
	mechanism.ulParameterLen = param->len;
Packit 40b132
    } else {
Packit 40b132
	mechanism.pParameter = NULL;
Packit 40b132
	mechanism.ulParameterLen = 0;
Packit 40b132
    }
Packit 40b132
    symKey->origin=PK11_OriginDerive;
Packit 40b132
Packit 40b132
    if (isPerm) {
Packit 40b132
	session =  PK11_GetRWSession(slot);
Packit 40b132
    } else {
Packit 40b132
        pk11_EnterKeyMonitor(symKey);
Packit 40b132
	session = symKey->session;
Packit 40b132
    }
Packit 40b132
    if (session == CK_INVALID_SESSION) {
Packit 40b132
	if (!isPerm)
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
	crv = CKR_SESSION_HANDLE_INVALID;
Packit 40b132
    } else {
Packit 40b132
	crv = PK11_GETTAB(slot)->C_DeriveKey(session, &mechanism,
Packit 40b132
	     baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
Packit 40b132
	if (isPerm) {
Packit 40b132
	    PK11_RestoreROSession(slot, session);
Packit 40b132
	} else {
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
    if (newBaseKey) 
Packit 40b132
    	PK11_FreeSymKey(newBaseKey);
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* Create a new key by concatenating base and data
Packit 40b132
 */
Packit 40b132
static PK11SymKey *pk11_ConcatenateBaseAndData(PK11SymKey *base,
Packit 40b132
	CK_BYTE *data, CK_ULONG dataLen, CK_MECHANISM_TYPE target,
Packit 40b132
	CK_ATTRIBUTE_TYPE operation)
Packit 40b132
{
Packit 40b132
    CK_KEY_DERIVATION_STRING_DATA mechParams;
Packit 40b132
    SECItem param;
Packit 40b132
Packit 40b132
    if (base == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    mechParams.pData = data;
Packit 40b132
    mechParams.ulLen = dataLen;
Packit 40b132
    param.data = (unsigned char *)&mechParams;
Packit 40b132
    param.len = sizeof(CK_KEY_DERIVATION_STRING_DATA);
Packit 40b132
Packit 40b132
    return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_DATA,
Packit 40b132
				&param, target, operation, 0);
Packit 40b132
}
Packit 40b132
Packit 40b132
/* Create a new key by concatenating base and key
Packit 40b132
 */
Packit 40b132
static PK11SymKey *pk11_ConcatenateBaseAndKey(PK11SymKey *base,
Packit 40b132
			PK11SymKey *key, CK_MECHANISM_TYPE target,
Packit 40b132
			CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
Packit 40b132
{
Packit 40b132
    SECItem param;
Packit 40b132
Packit 40b132
    if ((base == NULL) || (key == NULL)) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    param.data = (unsigned char *)&(key->objectID);
Packit 40b132
    param.len = sizeof(CK_OBJECT_HANDLE);
Packit 40b132
Packit 40b132
    return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_KEY,
Packit 40b132
				&param, target, operation, keySize);
Packit 40b132
}
Packit 40b132
Packit 40b132
/* Create a new key whose value is the hash of tobehashed.
Packit 40b132
 * type is the mechanism for the derived key.
Packit 40b132
 */
Packit 40b132
static PK11SymKey *pk11_HashKeyDerivation(PK11SymKey *toBeHashed,
Packit 40b132
	CK_MECHANISM_TYPE hashMechanism, CK_MECHANISM_TYPE target,
Packit 40b132
	CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
Packit 40b132
{
Packit 40b132
    return PK11_Derive(toBeHashed, hashMechanism, NULL, target, operation, keySize);
Packit 40b132
}
Packit 40b132
Packit 40b132
/* This function implements the ANSI X9.63 key derivation function
Packit 40b132
 */
Packit 40b132
static PK11SymKey *pk11_ANSIX963Derive(PK11SymKey *sharedSecret,
Packit 40b132
		CK_EC_KDF_TYPE kdf, SECItem *sharedData,
Packit 40b132
		CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
Packit 40b132
		CK_ULONG keySize)
Packit 40b132
{
Packit 40b132
    CK_KEY_TYPE keyType;
Packit 40b132
    CK_MECHANISM_TYPE hashMechanism, mechanismArray[4];
Packit 40b132
    CK_ULONG derivedKeySize, HashLen, counter, maxCounter, bufferLen;
Packit 40b132
    CK_ULONG SharedInfoLen;
Packit 40b132
    CK_BYTE *buffer = NULL;
Packit 40b132
    PK11SymKey *toBeHashed, *hashOutput;
Packit 40b132
    PK11SymKey *newSharedSecret = NULL;
Packit 40b132
    PK11SymKey *oldIntermediateResult, *intermediateResult = NULL;
Packit 40b132
Packit 40b132
    if (sharedSecret == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    switch (kdf) {
Packit 40b132
    case CKD_SHA1_KDF:
Packit 40b132
	HashLen = SHA1_LENGTH;
Packit 40b132
	hashMechanism = CKM_SHA1_KEY_DERIVATION;
Packit 40b132
	break;
Packit 40b132
    case CKD_SHA224_KDF:
Packit 40b132
	HashLen = SHA224_LENGTH;
Packit 40b132
	hashMechanism = CKM_SHA224_KEY_DERIVATION;
Packit 40b132
	break;
Packit 40b132
    case CKD_SHA256_KDF:
Packit 40b132
	HashLen = SHA256_LENGTH;
Packit 40b132
	hashMechanism = CKM_SHA256_KEY_DERIVATION;
Packit 40b132
	break;
Packit 40b132
    case CKD_SHA384_KDF:
Packit 40b132
	HashLen = SHA384_LENGTH;
Packit 40b132
	hashMechanism = CKM_SHA384_KEY_DERIVATION;
Packit 40b132
	break;
Packit 40b132
    case CKD_SHA512_KDF:
Packit 40b132
	HashLen = SHA512_LENGTH;
Packit 40b132
	hashMechanism = CKM_SHA512_KEY_DERIVATION;
Packit 40b132
	break;
Packit 40b132
    default:
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    derivedKeySize = keySize;
Packit 40b132
    if (derivedKeySize == 0) {
Packit 40b132
	keyType = PK11_GetKeyType(target,keySize);
Packit 40b132
	derivedKeySize = pk11_GetPredefinedKeyLength(keyType);
Packit 40b132
	if (derivedKeySize == 0) {
Packit 40b132
	    derivedKeySize = HashLen;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* Check that key_len isn't too long.  The maximum key length could be
Packit 40b132
     * greatly increased if the code below did not limit the 4-byte counter
Packit 40b132
     * to a maximum value of 255. */
Packit 40b132
    if (derivedKeySize > 254 * HashLen) {
Packit 40b132
	PORT_SetError( SEC_ERROR_INVALID_ARGS );
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    maxCounter = derivedKeySize / HashLen;
Packit 40b132
    if (derivedKeySize > maxCounter * HashLen)
Packit 40b132
	maxCounter++;
Packit 40b132
Packit 40b132
    if ((sharedData == NULL) || (sharedData->data == NULL))
Packit 40b132
	SharedInfoLen = 0;
Packit 40b132
    else
Packit 40b132
	SharedInfoLen = sharedData->len;
Packit 40b132
Packit 40b132
    bufferLen = SharedInfoLen + 4;
Packit 40b132
    
Packit 40b132
    /* Populate buffer with Counter || sharedData
Packit 40b132
     * where Counter is 0x00000001. */
Packit 40b132
    buffer = (unsigned char *)PORT_Alloc(bufferLen);
Packit 40b132
    if (buffer == NULL) {
Packit 40b132
	PORT_SetError(SEC_ERROR_NO_MEMORY);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    buffer[0] = 0;
Packit 40b132
    buffer[1] = 0;
Packit 40b132
    buffer[2] = 0;
Packit 40b132
    buffer[3] = 1;
Packit 40b132
    if (SharedInfoLen > 0) {
Packit 40b132
	PORT_Memcpy(&buffer[4], sharedData->data, SharedInfoLen);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* Look for a slot that supports the mechanisms needed
Packit 40b132
     * to implement the ANSI X9.63 KDF as well as the
Packit 40b132
     * target mechanism.
Packit 40b132
     */
Packit 40b132
    mechanismArray[0] = CKM_CONCATENATE_BASE_AND_DATA;
Packit 40b132
    mechanismArray[1] = hashMechanism;
Packit 40b132
    mechanismArray[2] = CKM_CONCATENATE_BASE_AND_KEY;
Packit 40b132
    mechanismArray[3] = target;
Packit 40b132
Packit 40b132
    newSharedSecret = pk11_ForceSlotMultiple(sharedSecret,
Packit 40b132
					 mechanismArray, 4, operation);
Packit 40b132
    if (newSharedSecret != NULL) {
Packit 40b132
	sharedSecret = newSharedSecret;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    for(counter=1; counter <= maxCounter; counter++) {
Packit 40b132
	/* Concatenate shared_secret and buffer */
Packit 40b132
	toBeHashed = pk11_ConcatenateBaseAndData(sharedSecret, buffer,
Packit 40b132
					bufferLen, hashMechanism, operation);
Packit 40b132
	if (toBeHashed == NULL) {
Packit 40b132
	    goto loser;
Packit 40b132
	}
Packit 40b132
Packit 40b132
	/* Hash value */
Packit 40b132
	if (maxCounter == 1) {
Packit 40b132
	    /* In this case the length of the key to be derived is
Packit 40b132
	     * less than or equal to the length of the hash output.
Packit 40b132
	     * So, the output of the hash operation will be the
Packit 40b132
	     * dervied key. */
Packit 40b132
	    hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
Packit 40b132
						target, operation, keySize);
Packit 40b132
	} else {
Packit 40b132
	    /* In this case, the output of the hash operation will be
Packit 40b132
	     * concatenated with other data to create the derived key. */
Packit 40b132
	    hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
Packit 40b132
				CKM_CONCATENATE_BASE_AND_KEY, operation, 0);
Packit 40b132
	}
Packit 40b132
	PK11_FreeSymKey(toBeHashed);
Packit 40b132
	if (hashOutput == NULL) {
Packit 40b132
	    goto loser;
Packit 40b132
	}
Packit 40b132
Packit 40b132
	/* Append result to intermediate result, if necessary */
Packit 40b132
	oldIntermediateResult = intermediateResult;
Packit 40b132
Packit 40b132
	if (oldIntermediateResult == NULL) {
Packit 40b132
	    intermediateResult = hashOutput;
Packit 40b132
	} else {
Packit 40b132
	    if (counter == maxCounter) {
Packit 40b132
		/* This is the final concatenation, and so the output
Packit 40b132
		 * will be the derived key. */
Packit 40b132
		intermediateResult =
Packit 40b132
		    pk11_ConcatenateBaseAndKey(oldIntermediateResult,
Packit 40b132
				hashOutput, target, operation, keySize);
Packit 40b132
	    } else {
Packit 40b132
		/* The output of this concatenation will be concatenated
Packit 40b132
		 * with other data to create the derived key. */
Packit 40b132
		intermediateResult =
Packit 40b132
		    pk11_ConcatenateBaseAndKey(oldIntermediateResult,
Packit 40b132
				hashOutput, CKM_CONCATENATE_BASE_AND_KEY,
Packit 40b132
				operation, 0);
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    PK11_FreeSymKey(hashOutput);
Packit 40b132
	    PK11_FreeSymKey(oldIntermediateResult);
Packit 40b132
	    if (intermediateResult == NULL) {
Packit 40b132
		goto loser;
Packit 40b132
	    }
Packit 40b132
	}
Packit 40b132
Packit 40b132
	/* Increment counter (assumes maxCounter < 255) */
Packit 40b132
	buffer[3]++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    PORT_ZFree(buffer, bufferLen);
Packit 40b132
    if (newSharedSecret != NULL)
Packit 40b132
	PK11_FreeSymKey(newSharedSecret);
Packit 40b132
    return intermediateResult;
Packit 40b132
Packit 40b132
loser:
Packit 40b132
    if (buffer != NULL)
Packit 40b132
	PORT_ZFree(buffer, bufferLen);
Packit 40b132
    if (newSharedSecret != NULL)
Packit 40b132
	PK11_FreeSymKey(newSharedSecret);
Packit 40b132
    if (intermediateResult != NULL)
Packit 40b132
	PK11_FreeSymKey(intermediateResult);
Packit 40b132
    return NULL;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This Generates a wrapping key based on a privateKey, publicKey, and two
Packit 40b132
 * random numbers. For Mail usage RandomB should be NULL. In the Sender's
Packit 40b132
 * case RandomA is generate, outherwize it is passed.
Packit 40b132
 */
Packit 40b132
static unsigned char *rb_email = NULL;
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey, 
Packit 40b132
   PRBool isSender, SECItem *randomA, SECItem *randomB, 
Packit 40b132
    CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
Packit 40b132
			CK_ATTRIBUTE_TYPE operation, int keySize,void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo *slot = privKey->pkcs11Slot;
Packit 40b132
    CK_MECHANISM mechanism;
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    CK_RV crv;
Packit 40b132
Packit 40b132
Packit 40b132
    if (rb_email == NULL) {
Packit 40b132
	rb_email = PORT_ZAlloc(128);
Packit 40b132
	if (rb_email == NULL) {
Packit 40b132
	    return NULL;
Packit 40b132
	}
Packit 40b132
	rb_email[127] = 1;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* get our key Structure */
Packit 40b132
    symKey = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, wincx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->origin = PK11_OriginDerive;
Packit 40b132
Packit 40b132
    switch (privKey->keyType) {
Packit 40b132
    case rsaKey:
Packit 40b132
    case nullKey:
Packit 40b132
	PORT_SetError(SEC_ERROR_BAD_KEY);
Packit 40b132
	break;
Packit 40b132
    case dsaKey:
Packit 40b132
    case keaKey:
Packit 40b132
    case fortezzaKey:
Packit 40b132
	{
Packit 40b132
	    CK_KEA_DERIVE_PARAMS param;
Packit 40b132
	    param.isSender = (CK_BBOOL) isSender;
Packit 40b132
	    param.ulRandomLen = randomA->len;
Packit 40b132
	    param.pRandomA = randomA->data;
Packit 40b132
	    param.pRandomB = rb_email;
Packit 40b132
	    if (randomB)
Packit 40b132
		 param.pRandomB = randomB->data;
Packit 40b132
	    if (pubKey->keyType == fortezzaKey) {
Packit 40b132
		param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
Packit 40b132
		param.pPublicData = pubKey->u.fortezza.KEAKey.data;
Packit 40b132
	    } else {
Packit 40b132
		/* assert type == keaKey */
Packit 40b132
		/* XXX change to match key key types */
Packit 40b132
		param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
Packit 40b132
		param.pPublicData = pubKey->u.fortezza.KEAKey.data;
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    mechanism.mechanism = derive;
Packit 40b132
	    mechanism.pParameter = ¶m;
Packit 40b132
	    mechanism.ulParameterLen = sizeof(param);
Packit 40b132
Packit 40b132
	    /* get a new symKey structure */
Packit 40b132
	    pk11_EnterKeyMonitor(symKey);
Packit 40b132
	    crv=PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
Packit 40b132
			privKey->pkcs11ID, NULL, 0, &symKey->objectID);
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
	    if (crv == CKR_OK) return symKey;
Packit 40b132
	    PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	}
Packit 40b132
	break;
Packit 40b132
    case dhKey:
Packit 40b132
	{
Packit 40b132
	    CK_BBOOL cktrue = CK_TRUE;
Packit 40b132
	    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
Packit 40b132
	    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
Packit 40b132
	    CK_ULONG key_size = 0;
Packit 40b132
	    CK_ATTRIBUTE keyTemplate[4];
Packit 40b132
	    int templateCount;
Packit 40b132
	    CK_ATTRIBUTE *attrs = keyTemplate;
Packit 40b132
Packit 40b132
	    if (pubKey->keyType != dhKey) {
Packit 40b132
		PORT_SetError(SEC_ERROR_BAD_KEY);
Packit 40b132
		break;
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
Packit 40b132
	    attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
Packit 40b132
	    attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size)); 
Packit 40b132
	    attrs++;
Packit 40b132
	    templateCount =  attrs - keyTemplate;
Packit 40b132
	    PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
	    keyType = PK11_GetKeyType(target,keySize);
Packit 40b132
	    key_size = keySize;
Packit 40b132
	    symKey->size = keySize;
Packit 40b132
	    if (key_size == 0) templateCount--;
Packit 40b132
Packit 40b132
	    mechanism.mechanism = derive;
Packit 40b132
Packit 40b132
	    /* we can undefine these when we define diffie-helman keys */
Packit 40b132
Packit 40b132
	    mechanism.pParameter = pubKey->u.dh.publicValue.data; 
Packit 40b132
	    mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
Packit 40b132
		
Packit 40b132
	    pk11_EnterKeyMonitor(symKey);
Packit 40b132
	    crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
Packit 40b132
	     privKey->pkcs11ID, keyTemplate, templateCount, &symKey->objectID);
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
	    if (crv == CKR_OK) return symKey;
Packit 40b132
	    PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	}
Packit 40b132
	break;
Packit 40b132
    case ecKey:
Packit 40b132
        {
Packit 40b132
	    CK_BBOOL cktrue = CK_TRUE;
Packit 40b132
	    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
Packit 40b132
	    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
Packit 40b132
	    CK_ULONG key_size = 0;
Packit 40b132
	    CK_ATTRIBUTE keyTemplate[4];
Packit 40b132
	    int templateCount;
Packit 40b132
	    CK_ATTRIBUTE *attrs = keyTemplate;
Packit 40b132
	    CK_ECDH1_DERIVE_PARAMS *mechParams = NULL;
Packit 40b132
Packit 40b132
	    if (pubKey->keyType != ecKey) {
Packit 40b132
		PORT_SetError(SEC_ERROR_BAD_KEY);
Packit 40b132
		break;
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
Packit 40b132
	    attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
Packit 40b132
	    attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
Packit 40b132
	    PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size)); 
Packit 40b132
	    attrs++;
Packit 40b132
	    templateCount =  attrs - keyTemplate;
Packit 40b132
	    PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
	    keyType = PK11_GetKeyType(target,keySize);
Packit 40b132
	    key_size = keySize;
Packit 40b132
	    if (key_size == 0) {
Packit 40b132
		if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
Packit 40b132
		    templateCount --;
Packit 40b132
		} else {
Packit 40b132
		    /* sigh, some tokens can't figure this out and require
Packit 40b132
		     * CKA_VALUE_LEN to be set */
Packit 40b132
		    key_size = SHA1_LENGTH;
Packit 40b132
		}
Packit 40b132
	    }
Packit 40b132
	    symKey->size = key_size;
Packit 40b132
Packit 40b132
	    mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS); 
Packit 40b132
	    mechParams->kdf = CKD_SHA1_KDF;
Packit 40b132
	    mechParams->ulSharedDataLen = 0;
Packit 40b132
	    mechParams->pSharedData = NULL;
Packit 40b132
	    mechParams->ulPublicDataLen =  pubKey->u.ec.publicValue.len;
Packit 40b132
	    mechParams->pPublicData =  pubKey->u.ec.publicValue.data;
Packit 40b132
Packit 40b132
	    mechanism.mechanism = derive;
Packit 40b132
	    mechanism.pParameter = mechParams;
Packit 40b132
	    mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
Packit 40b132
Packit 40b132
	    pk11_EnterKeyMonitor(symKey);
Packit 40b132
	    crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, 
Packit 40b132
		&mechanism, privKey->pkcs11ID, keyTemplate, 
Packit 40b132
		templateCount, &symKey->objectID);
Packit 40b132
	    pk11_ExitKeyMonitor(symKey);
Packit 40b132
Packit 40b132
	    /* old PKCS #11 spec was ambiguous on what needed to be passed,
Packit 40b132
	     * try this again with and encoded public key */
Packit 40b132
	    if (crv != CKR_OK) {
Packit 40b132
		SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL,
Packit 40b132
			&pubKey->u.ec.publicValue,
Packit 40b132
			SEC_ASN1_GET(SEC_OctetStringTemplate));
Packit 40b132
		if (pubValue == NULL) {
Packit 40b132
	    	    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
Packit 40b132
		    break;
Packit 40b132
		}
Packit 40b132
		mechParams->ulPublicDataLen =  pubValue->len;
Packit 40b132
		mechParams->pPublicData =  pubValue->data;
Packit 40b132
Packit 40b132
		pk11_EnterKeyMonitor(symKey);
Packit 40b132
		crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, 
Packit 40b132
		    &mechanism, privKey->pkcs11ID, keyTemplate, 
Packit 40b132
		    templateCount, &symKey->objectID);
Packit 40b132
		pk11_ExitKeyMonitor(symKey);
Packit 40b132
Packit 40b132
		SECITEM_FreeItem(pubValue,PR_TRUE);
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
Packit 40b132
Packit 40b132
	    if (crv == CKR_OK) return symKey;
Packit 40b132
	    PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	}
Packit 40b132
   }
Packit 40b132
Packit 40b132
   PK11_FreeSymKey(symKey);
Packit 40b132
   return NULL;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* Returns the size of the public key, or 0 if there
Packit 40b132
 * is an error. */
Packit 40b132
static CK_ULONG
Packit 40b132
pk11_ECPubKeySize(SECItem *publicValue)
Packit 40b132
{
Packit 40b132
    if (publicValue->data[0] == 0x04) {
Packit 40b132
	/* key encoded in uncompressed form */
Packit 40b132
	return((publicValue->len - 1)/2);
Packit 40b132
    } else if ( (publicValue->data[0] == 0x02) ||
Packit 40b132
		(publicValue->data[0] == 0x03)) {
Packit 40b132
	/* key encoded in compressed form */
Packit 40b132
	return(publicValue->len - 1);
Packit 40b132
    }
Packit 40b132
    /* key encoding not recognized */
Packit 40b132
    return(0);
Packit 40b132
}
Packit 40b132
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_PubDeriveECKeyWithKDF(
Packit 40b132
		    SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
Packit 40b132
		    PRBool isSender, SECItem *randomA, SECItem *randomB,
Packit 40b132
		    CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
Packit 40b132
		    CK_ATTRIBUTE_TYPE operation, int keySize,
Packit 40b132
		    CK_ULONG kdf, SECItem *sharedData, void *wincx)
Packit 40b132
{
Packit 40b132
    PK11SlotInfo           *slot            = privKey->pkcs11Slot;
Packit 40b132
    PK11SymKey             *symKey;
Packit 40b132
    PK11SymKey             *SharedSecret;
Packit 40b132
    CK_MECHANISM            mechanism;
Packit 40b132
    CK_RV                   crv;
Packit 40b132
    CK_BBOOL                cktrue          = CK_TRUE;
Packit 40b132
    CK_OBJECT_CLASS         keyClass        = CKO_SECRET_KEY;
Packit 40b132
    CK_KEY_TYPE             keyType         = CKK_GENERIC_SECRET;
Packit 40b132
    CK_ULONG                key_size        = 0;
Packit 40b132
    CK_ATTRIBUTE            keyTemplate[4];
Packit 40b132
    int                     templateCount;
Packit 40b132
    CK_ATTRIBUTE           *attrs           = keyTemplate;
Packit 40b132
    CK_ECDH1_DERIVE_PARAMS *mechParams      = NULL;
Packit 40b132
Packit 40b132
    if (pubKey->keyType != ecKey) {
Packit 40b132
	PORT_SetError(SEC_ERROR_BAD_KEY);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    if ((kdf != CKD_NULL) && (kdf != CKD_SHA1_KDF) &&
Packit 40b132
	(kdf != CKD_SHA224_KDF) && (kdf != CKD_SHA256_KDF) &&
Packit 40b132
	(kdf != CKD_SHA384_KDF) && (kdf != CKD_SHA512_KDF)) {
Packit 40b132
	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* get our key Structure */
Packit 40b132
    symKey = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, wincx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->origin = PK11_OriginDerive;
Packit 40b132
Packit 40b132
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));     attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));    attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, operation, &cktrue, 1);                      attrs++;
Packit 40b132
    PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size)); attrs++;
Packit 40b132
    templateCount =  attrs - keyTemplate;
Packit 40b132
    PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
    keyType = PK11_GetKeyType(target,keySize);
Packit 40b132
    key_size = keySize;
Packit 40b132
    if (key_size == 0) {
Packit 40b132
	if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
Packit 40b132
	    templateCount --;
Packit 40b132
	} else {
Packit 40b132
	    /* sigh, some tokens can't figure this out and require
Packit 40b132
	     * CKA_VALUE_LEN to be set */
Packit 40b132
	    switch (kdf) {
Packit 40b132
	    case CKD_NULL:
Packit 40b132
		key_size = pk11_ECPubKeySize(&pubKey->u.ec.publicValue);
Packit 40b132
		if (key_size == 0) {
Packit 40b132
		    PK11_FreeSymKey(symKey);
Packit 40b132
		    return NULL;
Packit 40b132
		}
Packit 40b132
		break;
Packit 40b132
	    case CKD_SHA1_KDF:
Packit 40b132
		key_size = SHA1_LENGTH;
Packit 40b132
		break;
Packit 40b132
	    case CKD_SHA224_KDF:
Packit 40b132
		key_size = SHA224_LENGTH;
Packit 40b132
		break;
Packit 40b132
	    case CKD_SHA256_KDF:
Packit 40b132
		key_size = SHA256_LENGTH;
Packit 40b132
		break;
Packit 40b132
	    case CKD_SHA384_KDF:
Packit 40b132
		key_size = SHA384_LENGTH;
Packit 40b132
		break;
Packit 40b132
	    case CKD_SHA512_KDF:
Packit 40b132
		key_size = SHA512_LENGTH;
Packit 40b132
		break;
Packit 40b132
	    default:
Packit 40b132
		PORT_Assert(!"Invalid CKD");
Packit 40b132
		PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
Packit 40b132
		return NULL;
Packit 40b132
	    }
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
    symKey->size = key_size;
Packit 40b132
Packit 40b132
    mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS);
Packit 40b132
    if (!mechParams) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    mechParams->kdf = kdf;
Packit 40b132
    if (sharedData == NULL) {
Packit 40b132
	mechParams->ulSharedDataLen = 0;
Packit 40b132
	mechParams->pSharedData     = NULL;
Packit 40b132
    } else {
Packit 40b132
	mechParams->ulSharedDataLen = sharedData->len;
Packit 40b132
	mechParams->pSharedData     = sharedData->data;
Packit 40b132
    }
Packit 40b132
    mechParams->ulPublicDataLen =  pubKey->u.ec.publicValue.len;
Packit 40b132
    mechParams->pPublicData =  pubKey->u.ec.publicValue.data;
Packit 40b132
Packit 40b132
    mechanism.mechanism      = derive;
Packit 40b132
    mechanism.pParameter     = mechParams;
Packit 40b132
    mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
Packit 40b132
Packit 40b132
    pk11_EnterKeyMonitor(symKey);
Packit 40b132
    crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism, 
Packit 40b132
    	privKey->pkcs11ID, keyTemplate, templateCount, &symKey->objectID);
Packit 40b132
    pk11_ExitKeyMonitor(symKey);
Packit 40b132
Packit 40b132
    /* old PKCS #11 spec was ambiguous on what needed to be passed,
Packit 40b132
     * try this again with an encoded public key */
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL,
Packit 40b132
		&pubKey->u.ec.publicValue,
Packit 40b132
		SEC_ASN1_GET(SEC_OctetStringTemplate));
Packit 40b132
	if (pubValue == NULL) {
Packit 40b132
	    goto loser;
Packit 40b132
	}
Packit 40b132
	mechParams->ulPublicDataLen =  pubValue->len;
Packit 40b132
	mechParams->pPublicData =  pubValue->data;
Packit 40b132
Packit 40b132
	pk11_EnterKeyMonitor(symKey);
Packit 40b132
	crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, 
Packit 40b132
	    &mechanism, privKey->pkcs11ID, keyTemplate, 
Packit 40b132
	    templateCount, &symKey->objectID);
Packit 40b132
	pk11_ExitKeyMonitor(symKey);
Packit 40b132
Packit 40b132
	if ((crv != CKR_OK) && (kdf != CKD_NULL)) {
Packit 40b132
	    /* Some PKCS #11 libraries cannot perform the key derivation
Packit 40b132
	     * function. So, try calling C_DeriveKey with CKD_NULL and then
Packit 40b132
	     * performing the KDF separately.
Packit 40b132
	     */
Packit 40b132
	    CK_ULONG derivedKeySize = key_size;
Packit 40b132
Packit 40b132
	    keyType = CKK_GENERIC_SECRET;
Packit 40b132
	    key_size = pk11_ECPubKeySize(&pubKey->u.ec.publicValue);
Packit 40b132
	    if (key_size == 0) {
Packit 40b132
		SECITEM_FreeItem(pubValue,PR_TRUE);
Packit 40b132
		goto loser;
Packit 40b132
	    }
Packit 40b132
	    SharedSecret = symKey;
Packit 40b132
	    SharedSecret->size = key_size;
Packit 40b132
Packit 40b132
	    mechParams->kdf             = CKD_NULL;
Packit 40b132
	    mechParams->ulSharedDataLen = 0;
Packit 40b132
	    mechParams->pSharedData     = NULL;
Packit 40b132
	    mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
Packit 40b132
	    mechParams->pPublicData     = pubKey->u.ec.publicValue.data;
Packit 40b132
Packit 40b132
	    pk11_EnterKeyMonitor(SharedSecret);
Packit 40b132
	    crv = PK11_GETTAB(slot)->C_DeriveKey(SharedSecret->session,
Packit 40b132
			    &mechanism, privKey->pkcs11ID, keyTemplate,
Packit 40b132
			    templateCount, &SharedSecret->objectID);
Packit 40b132
	    pk11_ExitKeyMonitor(SharedSecret);
Packit 40b132
Packit 40b132
	    if (crv != CKR_OK) {
Packit 40b132
		/* old PKCS #11 spec was ambiguous on what needed to be passed,
Packit 40b132
		 * try this one final time with an encoded public key */
Packit 40b132
		mechParams->ulPublicDataLen =  pubValue->len;
Packit 40b132
		mechParams->pPublicData     =  pubValue->data;
Packit 40b132
Packit 40b132
		pk11_EnterKeyMonitor(SharedSecret);
Packit 40b132
		crv = PK11_GETTAB(slot)->C_DeriveKey(SharedSecret->session,
Packit 40b132
				&mechanism, privKey->pkcs11ID, keyTemplate,
Packit 40b132
				templateCount, &SharedSecret->objectID);
Packit 40b132
		pk11_ExitKeyMonitor(SharedSecret);
Packit 40b132
	    }
Packit 40b132
Packit 40b132
	    /* Perform KDF. */
Packit 40b132
	    if (crv == CKR_OK) {
Packit 40b132
		    symKey = pk11_ANSIX963Derive(SharedSecret, kdf,
Packit 40b132
					sharedData, target, operation,
Packit 40b132
					derivedKeySize);
Packit 40b132
		    PK11_FreeSymKey(SharedSecret);
Packit 40b132
		    if (symKey == NULL) {
Packit 40b132
			SECITEM_FreeItem(pubValue,PR_TRUE);
Packit 40b132
			PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
Packit 40b132
			return NULL;
Packit 40b132
		    }
Packit 40b132
	    }
Packit 40b132
	}
Packit 40b132
	SECITEM_FreeItem(pubValue,PR_TRUE);
Packit 40b132
    }
Packit 40b132
Packit 40b132
loser:
Packit 40b132
    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
Packit 40b132
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	symKey = NULL;
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
    }
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_PubDeriveWithKDF(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey, 
Packit 40b132
		      PRBool isSender, SECItem *randomA, SECItem *randomB, 
Packit 40b132
		      CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
Packit 40b132
		      CK_ATTRIBUTE_TYPE operation, int keySize,
Packit 40b132
		      CK_ULONG kdf, SECItem *sharedData, void *wincx)
Packit 40b132
{
Packit 40b132
Packit 40b132
    switch (privKey->keyType) {
Packit 40b132
    case rsaKey:
Packit 40b132
    case nullKey:
Packit 40b132
    case dsaKey:
Packit 40b132
    case keaKey:
Packit 40b132
    case fortezzaKey:
Packit 40b132
    case dhKey:
Packit 40b132
	return PK11_PubDerive(privKey, pubKey, isSender, randomA, randomB,
Packit 40b132
		derive, target, operation, keySize, wincx);
Packit 40b132
    case ecKey:
Packit 40b132
	return pk11_PubDeriveECKeyWithKDF( privKey, pubKey, isSender, 
Packit 40b132
		randomA, randomB, derive, target, operation, keySize, 
Packit 40b132
		kdf, sharedData, wincx);
Packit 40b132
    default:
Packit 40b132
        PORT_SetError(SEC_ERROR_BAD_KEY);
Packit 40b132
        break;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    return NULL;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * this little function uses the Decrypt function to unwrap a key, just in
Packit 40b132
 * case we are having problem with unwrap. NOTE: The key size may
Packit 40b132
 * not be preserved properly for some algorithms!
Packit 40b132
 */
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
Packit 40b132
                CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target, 
Packit 40b132
		CK_ATTRIBUTE *keyTemplate, unsigned int templateCount, 
Packit 40b132
		int key_size, void * wincx, CK_RV *crvp, PRBool isPerm)
Packit 40b132
{
Packit 40b132
    CK_ULONG len;
Packit 40b132
    SECItem outKey;
Packit 40b132
    PK11SymKey *symKey;
Packit 40b132
    CK_RV crv;
Packit 40b132
    PRBool owner = PR_TRUE;
Packit 40b132
    CK_SESSION_HANDLE session;
Packit 40b132
Packit 40b132
    /* remove any VALUE_LEN parameters */
Packit 40b132
    if (keyTemplate[templateCount-1].type == CKA_VALUE_LEN) {
Packit 40b132
        templateCount--;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* keys are almost always aligned, but if we get this far,
Packit 40b132
     * we've gone above and beyond anyway... */
Packit 40b132
    outKey.data = (unsigned char*)PORT_Alloc(inKey->len);
Packit 40b132
    if (outKey.data == NULL) {
Packit 40b132
	PORT_SetError( SEC_ERROR_NO_MEMORY );
Packit 40b132
	if (crvp) *crvp = CKR_HOST_MEMORY;
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    len = inKey->len;
Packit 40b132
Packit 40b132
    /* use NULL IV's for wrapping */
Packit 40b132
    session = pk11_GetNewSession(slot,&owner);
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
Packit 40b132
    crv = PK11_GETTAB(slot)->C_DecryptInit(session,mech,wrappingKey);
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
	pk11_CloseSession(slot,session,owner);
Packit 40b132
	PORT_Free(outKey.data);
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	if (crvp) *crvp =crv;
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
    crv = PK11_GETTAB(slot)->C_Decrypt(session,inKey->data,inKey->len,
Packit 40b132
							   outKey.data, &len;;
Packit 40b132
    if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
Packit 40b132
    pk11_CloseSession(slot,session,owner);
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PORT_Free(outKey.data);
Packit 40b132
	PORT_SetError( PK11_MapError(crv) );
Packit 40b132
	if (crvp) *crvp =crv;
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    outKey.len = (key_size == 0) ? len : key_size;
Packit 40b132
    outKey.type = siBuffer;
Packit 40b132
Packit 40b132
    if (PK11_DoesMechanism(slot,target)) {
Packit 40b132
	symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap, 
Packit 40b132
	                                    isPerm, keyTemplate, 
Packit 40b132
					    templateCount, &outKey, wincx);
Packit 40b132
    } else {
Packit 40b132
	slot = PK11_GetBestSlot(target,wincx);
Packit 40b132
	if (slot == NULL) {
Packit 40b132
	    PORT_SetError( SEC_ERROR_NO_MODULE );
Packit 40b132
	    PORT_Free(outKey.data);
Packit 40b132
	    if (crvp) *crvp = CKR_DEVICE_ERROR; 
Packit 40b132
	    return NULL;
Packit 40b132
	}
Packit 40b132
	symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap, 
Packit 40b132
	                                    isPerm, keyTemplate,
Packit 40b132
					    templateCount, &outKey, wincx);
Packit 40b132
	PK11_FreeSlot(slot);
Packit 40b132
    }
Packit 40b132
    PORT_Free(outKey.data);
Packit 40b132
Packit 40b132
    if (crvp) *crvp = symKey? CKR_OK : CKR_DEVICE_ERROR; 
Packit 40b132
    return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * The wrap/unwrap function is pretty much the same for private and
Packit 40b132
 * public keys. It's just getting the Object ID and slot right. This is
Packit 40b132
 * the combined unwrap function.
Packit 40b132
 */
Packit 40b132
static PK11SymKey *
Packit 40b132
pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
Packit 40b132
    CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey, 
Packit 40b132
    CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize, 
Packit 40b132
    void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs, PRBool isPerm)
Packit 40b132
{
Packit 40b132
    PK11SymKey *    symKey;
Packit 40b132
    SECItem *       param_free	= NULL;
Packit 40b132
    CK_BBOOL        cktrue	= CK_TRUE; 
Packit 40b132
    CK_OBJECT_CLASS keyClass	= CKO_SECRET_KEY;
Packit 40b132
    CK_KEY_TYPE     keyType	= CKK_GENERIC_SECRET;
Packit 40b132
    CK_ULONG        valueLen	= 0;
Packit 40b132
    CK_MECHANISM    mechanism;
Packit 40b132
    CK_SESSION_HANDLE rwsession;
Packit 40b132
    CK_RV           crv;
Packit 40b132
    CK_MECHANISM_INFO mechanism_info;
Packit 40b132
#define MAX_ADD_ATTRS 4
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS + MAX_ADD_ATTRS];
Packit 40b132
#undef MAX_ADD_ATTRS
Packit 40b132
    CK_ATTRIBUTE *  attrs	= keyTemplate;
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
Packit 40b132
    if (numAttrs > MAX_TEMPL_ATTRS) {
Packit 40b132
    	PORT_SetError(SEC_ERROR_INVALID_ARGS);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* first copy caller attributes in. */
Packit 40b132
    for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
Packit 40b132
    	*attrs++ = *userAttr++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* We only add the following attributes to the template if the caller
Packit 40b132
    ** didn't already supply them.
Packit 40b132
    */
Packit 40b132
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
Packit 40b132
	PK11_SETATTRS(attrs, CKA_CLASS,     &keyClass, sizeof keyClass); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
Packit 40b132
	keyType = PK11_GetKeyType(target, keySize);
Packit 40b132
	PK11_SETATTRS(attrs, CKA_KEY_TYPE,  &keyType,  sizeof keyType ); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
    if ((operation != CKA_FLAGS_ONLY) &&
Packit 40b132
	  !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
Packit 40b132
	PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /*
Packit 40b132
     * must be last in case we need to use this template to import the key
Packit 40b132
     */
Packit 40b132
    if (keySize > 0 &&
Packit 40b132
    	  !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
Packit 40b132
	valueLen = (CK_ULONG)keySize;
Packit 40b132
	PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen); 
Packit 40b132
	attrs++;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    templateCount = attrs - keyTemplate;
Packit 40b132
    PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
Packit 40b132
Packit 40b132
Packit 40b132
    /* find out if we can do wrap directly. Because the RSA case if *very*
Packit 40b132
     * common, cache the results for it. */
Packit 40b132
    if ((wrapType == CKM_RSA_PKCS) && (slot->hasRSAInfo)) {
Packit 40b132
	mechanism_info.flags = slot->RSAInfoFlags;
Packit 40b132
    } else {
Packit 40b132
	if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
Packit 40b132
	crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,wrapType,
Packit 40b132
				 &mechanism_info);
Packit 40b132
    	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
Packit 40b132
    	if (crv != CKR_OK) {
Packit 40b132
	     mechanism_info.flags = 0;
Packit 40b132
    	}
Packit 40b132
        if (wrapType == CKM_RSA_PKCS) {
Packit 40b132
	    slot->RSAInfoFlags = mechanism_info.flags;
Packit 40b132
	    slot->hasRSAInfo = PR_TRUE;
Packit 40b132
	}
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* initialize the mechanism structure */
Packit 40b132
    mechanism.mechanism = wrapType;
Packit 40b132
    /* use NULL IV's for wrapping */
Packit 40b132
    if (param == NULL) 
Packit 40b132
	param = param_free = PK11_ParamFromIV(wrapType,NULL);
Packit 40b132
    if (param) {
Packit 40b132
	mechanism.pParameter = param->data;
Packit 40b132
	mechanism.ulParameterLen = param->len;
Packit 40b132
    } else {
Packit 40b132
	mechanism.pParameter = NULL;
Packit 40b132
	mechanism.ulParameterLen = 0;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    if ((mechanism_info.flags & CKF_DECRYPT)  
Packit 40b132
				&& !PK11_DoesMechanism(slot,target)) {
Packit 40b132
	symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey, 
Packit 40b132
	                         target, keyTemplate, templateCount, keySize, 
Packit 40b132
				 wincx, &crv, isPerm);
Packit 40b132
	if (symKey) {
Packit 40b132
	    if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
Packit 40b132
	    return symKey;
Packit 40b132
	}
Packit 40b132
	/*
Packit 40b132
	 * if the RSA OP simply failed, don't try to unwrap again 
Packit 40b132
	 * with this module.
Packit 40b132
	 */
Packit 40b132
	if (crv == CKR_DEVICE_ERROR){
Packit 40b132
	    if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
Packit 40b132
	    return NULL;
Packit 40b132
	}
Packit 40b132
	/* fall through, maybe they incorrectly set CKF_DECRYPT */
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* get our key Structure */
Packit 40b132
    symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE, wincx);
Packit 40b132
    if (symKey == NULL) {
Packit 40b132
	if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
Packit 40b132
	return NULL;
Packit 40b132
    }
Packit 40b132
Packit 40b132
    symKey->size = keySize;
Packit 40b132
    symKey->origin = PK11_OriginUnwrap;
Packit 40b132
Packit 40b132
    if (isPerm) {
Packit 40b132
	rwsession = PK11_GetRWSession(slot);
Packit 40b132
    } else {
Packit 40b132
        pk11_EnterKeyMonitor(symKey);
Packit 40b132
	rwsession = symKey->session;
Packit 40b132
    }
Packit 40b132
    PORT_Assert(rwsession != CK_INVALID_SESSION);
Packit 40b132
    if (rwsession == CK_INVALID_SESSION) 
Packit 40b132
    	crv = CKR_SESSION_HANDLE_INVALID;
Packit 40b132
    else
Packit 40b132
	crv = PK11_GETTAB(slot)->C_UnwrapKey(rwsession,&mechanism,wrappingKey,
Packit 40b132
		wrappedKey->data, wrappedKey->len, keyTemplate, templateCount, 
Packit 40b132
							  &symKey->objectID);
Packit 40b132
    if (isPerm) {
Packit 40b132
	if (rwsession != CK_INVALID_SESSION)
Packit 40b132
	    PK11_RestoreROSession(slot, rwsession);
Packit 40b132
    } else {
Packit 40b132
        pk11_ExitKeyMonitor(symKey);
Packit 40b132
    }
Packit 40b132
    if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
Packit 40b132
    if (crv != CKR_OK) {
Packit 40b132
	PK11_FreeSymKey(symKey);
Packit 40b132
	symKey = NULL;
Packit 40b132
	if (crv != CKR_DEVICE_ERROR) {
Packit 40b132
	    /* try hand Unwrapping */
Packit 40b132
	    symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey, 
Packit 40b132
				     target, keyTemplate, templateCount,
Packit 40b132
				     keySize, wincx, NULL, isPerm);
Packit 40b132
	}
Packit 40b132
   }
Packit 40b132
Packit 40b132
   return symKey;
Packit 40b132
}
Packit 40b132
Packit 40b132
/* use a symetric key to unwrap another symetric key */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_UnwrapSymKey( PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
Packit 40b132
                   SECItem *param, SECItem *wrappedKey, 
Packit 40b132
		   CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
		   int keySize)
Packit 40b132
{
Packit 40b132
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
Packit 40b132
		    wrapType, param, wrappedKey, target, operation, keySize, 
Packit 40b132
		    wrappingKey->cx, NULL, 0, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
/* use a symetric key to unwrap another symetric key */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
Packit 40b132
                   SECItem *param, SECItem *wrappedKey, 
Packit 40b132
		   CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
		   int keySize, CK_FLAGS flags)
Packit 40b132
{
Packit 40b132
    CK_BBOOL        ckTrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
Packit 40b132
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
Packit 40b132
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
Packit 40b132
		    wrapType, param, wrappedKey, target, operation, keySize, 
Packit 40b132
		    wrappingKey->cx, keyTemplate, templateCount, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_UnwrapSymKeyWithFlagsPerm(PK11SymKey *wrappingKey, 
Packit 40b132
		   CK_MECHANISM_TYPE wrapType,
Packit 40b132
                   SECItem *param, SECItem *wrappedKey, 
Packit 40b132
		   CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 
Packit 40b132
		   int keySize, CK_FLAGS flags, PRBool isPerm)
Packit 40b132
{
Packit 40b132
    CK_BBOOL        cktrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    CK_ATTRIBUTE    *attrs;
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
Packit 40b132
    attrs = keyTemplate;
Packit 40b132
    if (isPerm) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_TOKEN,  &cktrue, sizeof(CK_BBOOL)); attrs++;
Packit 40b132
    }
Packit 40b132
    templateCount = attrs-keyTemplate;
Packit 40b132
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
Packit 40b132
Packit 40b132
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
Packit 40b132
		    wrapType, param, wrappedKey, target, operation, keySize, 
Packit 40b132
		    wrappingKey->cx, keyTemplate, templateCount, isPerm);
Packit 40b132
}
Packit 40b132
Packit 40b132
Packit 40b132
/* unwrap a symetric key with a private key. */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
Packit 40b132
	  CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
Packit 40b132
{
Packit 40b132
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
Packit 40b132
    PK11SlotInfo    *slot = wrappingKey->pkcs11Slot;
Packit 40b132
Packit 40b132
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey,CKA_PRIVATE)) {
Packit 40b132
	PK11_HandlePasswordCheck(slot,wrappingKey->wincx);
Packit 40b132
    }
Packit 40b132
    
Packit 40b132
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
Packit 40b132
	wrapType, NULL, wrappedKey, target, operation, keySize, 
Packit 40b132
	wrappingKey->wincx, NULL, 0, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
/* unwrap a symetric key with a private key. */
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_PubUnwrapSymKeyWithFlags(SECKEYPrivateKey *wrappingKey, 
Packit 40b132
	  SECItem *wrappedKey, CK_MECHANISM_TYPE target, 
Packit 40b132
	  CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags)
Packit 40b132
{
Packit 40b132
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
Packit 40b132
    CK_BBOOL        ckTrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
    PK11SlotInfo    *slot = wrappingKey->pkcs11Slot;
Packit 40b132
Packit 40b132
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
Packit 40b132
Packit 40b132
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey,CKA_PRIVATE)) {
Packit 40b132
	PK11_HandlePasswordCheck(slot,wrappingKey->wincx);
Packit 40b132
    }
Packit 40b132
    
Packit 40b132
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
Packit 40b132
	wrapType, NULL, wrappedKey, target, operation, keySize, 
Packit 40b132
	wrappingKey->wincx, keyTemplate, templateCount, PR_FALSE);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey *
Packit 40b132
PK11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey, 
Packit 40b132
	  SECItem *wrappedKey, CK_MECHANISM_TYPE target, 
Packit 40b132
	  CK_ATTRIBUTE_TYPE operation, int keySize,
Packit 40b132
	  CK_FLAGS flags, PRBool isPerm)
Packit 40b132
{
Packit 40b132
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
Packit 40b132
    CK_BBOOL        cktrue	= CK_TRUE; 
Packit 40b132
    CK_ATTRIBUTE    keyTemplate[MAX_TEMPL_ATTRS];
Packit 40b132
    CK_ATTRIBUTE    *attrs;
Packit 40b132
    unsigned int    templateCount;
Packit 40b132
    PK11SlotInfo    *slot = wrappingKey->pkcs11Slot;
Packit 40b132
Packit 40b132
    attrs = keyTemplate;
Packit 40b132
    if (isPerm) {
Packit 40b132
        PK11_SETATTRS(attrs, CKA_TOKEN,  &cktrue, sizeof(CK_BBOOL)); attrs++;
Packit 40b132
    }
Packit 40b132
    templateCount = attrs-keyTemplate;
Packit 40b132
Packit 40b132
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
Packit 40b132
Packit 40b132
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey,CKA_PRIVATE)) {
Packit 40b132
	PK11_HandlePasswordCheck(slot,wrappingKey->wincx);
Packit 40b132
    }
Packit 40b132
    
Packit 40b132
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
Packit 40b132
	wrapType, NULL, wrappedKey, target, operation, keySize, 
Packit 40b132
	wrappingKey->wincx, keyTemplate, templateCount, isPerm);
Packit 40b132
}
Packit 40b132
Packit 40b132
PK11SymKey*
Packit 40b132
PK11_CopySymKeyForSigning(PK11SymKey *originalKey, CK_MECHANISM_TYPE mech)
Packit 40b132
{
Packit 40b132
    CK_RV crv;
Packit 40b132
    CK_ATTRIBUTE setTemplate;
Packit 40b132
    CK_BBOOL ckTrue = CK_TRUE; 
Packit 40b132
    PK11SlotInfo *slot = originalKey->slot;
Packit 40b132
Packit 40b132
    /* first just try to set this key up for signing */
Packit 40b132
    PK11_SETATTRS(&setTemplate, CKA_SIGN, &ckTrue, sizeof(ckTrue));
Packit 40b132
    pk11_EnterKeyMonitor(originalKey);
Packit 40b132
    crv = PK11_GETTAB(slot)-> C_SetAttributeValue(originalKey->session, 
Packit 40b132
				originalKey->objectID, &setTemplate, 1);
Packit 40b132
    pk11_ExitKeyMonitor(originalKey);
Packit 40b132
    if (crv == CKR_OK) {
Packit 40b132
	return PK11_ReferenceSymKey(originalKey);
Packit 40b132
    }
Packit 40b132
Packit 40b132
    /* nope, doesn't like it, use the pk11 copy object command */
Packit 40b132
    return pk11_CopyToSlot(slot, mech, CKA_SIGN, originalKey);
Packit 40b132
}
Packit 40b132
    
Packit 40b132
void   
Packit 40b132
PK11_SetFortezzaHack(PK11SymKey *symKey) { 
Packit 40b132
   symKey->origin = PK11_OriginFortezzaHack;
Packit 40b132
}
Packit 40b132
Packit 40b132
/*
Packit 40b132
 * This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
Packit 40b132
 * working. This function simply gets a valid IV for the keys.
Packit 40b132
 */
Packit 40b132
SECStatus
Packit 40b132
PK11_GenerateFortezzaIV(PK11SymKey *symKey,unsigned char *iv,int len)
Packit 40b132
{
Packit 40b132
    CK_MECHANISM mech_info;
Packit 40b132
    CK_ULONG count = 0;
Packit 40b132
    CK_RV crv;
Packit 40b132
    SECStatus rv = SECFailure;
Packit 40b132
Packit 40b132
    mech_info.mechanism = CKM_SKIPJACK_CBC64;
Packit 40b132
    mech_info.pParameter = iv;
Packit 40b132
    mech_info.ulParameterLen = len;
Packit 40b132
Packit 40b132
    /* generate the IV for fortezza */
Packit 40b132
    PK11_EnterSlotMonitor(symKey->slot);
Packit 40b132
    crv=PK11_GETTAB(symKey->slot)->C_EncryptInit(symKey->slot->session,
Packit 40b132
				&mech_info, symKey->objectID);
Packit 40b132
    if (crv == CKR_OK) {
Packit 40b132
	PK11_GETTAB(symKey->slot)->C_EncryptFinal(symKey->slot->session, 
Packit 40b132
								NULL, &count);
Packit 40b132
	rv = SECSuccess;
Packit 40b132
    }
Packit 40b132
    PK11_ExitSlotMonitor(symKey->slot);
Packit 40b132
    return rv;
Packit 40b132
}
Packit 40b132
Packit 40b132
CK_OBJECT_HANDLE
Packit 40b132
PK11_GetSymKeyHandle(PK11SymKey *symKey)
Packit 40b132
{
Packit 40b132
    return symKey->objectID;
Packit 40b132
}
Packit 40b132