Coverage Report

Created: 2024-11-21 07:03

/src/nss-nspr/nss/lib/pk11wrap/pk11skey.c
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
/*
5
 * This file implements the Symkey wrapper and the PKCS context
6
 * Interfaces.
7
 */
8
9
#include <stddef.h>
10
#include <limits.h>
11
12
#include "seccomon.h"
13
#include "secmod.h"
14
#include "nssilock.h"
15
#include "secmodi.h"
16
#include "secmodti.h"
17
#include "pkcs11.h"
18
#include "pk11func.h"
19
#include "secitem.h"
20
#include "secoid.h"
21
#include "secerr.h"
22
#include "hasht.h"
23
24
static ECPointEncoding pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey);
25
26
static void
27
pk11_EnterKeyMonitor(PK11SymKey *symKey)
28
434
{
29
434
    if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
30
0
        PK11_EnterSlotMonitor(symKey->slot);
31
434
}
32
33
static void
34
pk11_ExitKeyMonitor(PK11SymKey *symKey)
35
434
{
36
434
    if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
37
0
        PK11_ExitSlotMonitor(symKey->slot);
38
434
}
39
40
/*
41
 * pk11_getKeyFromList returns a symKey that has a session (if needSession
42
 * was specified), or explicitly does not have a session (if needSession
43
 * was not specified).
44
 */
45
static PK11SymKey *
46
pk11_getKeyFromList(PK11SlotInfo *slot, PRBool needSession)
47
335
{
48
335
    PK11SymKey *symKey = NULL;
49
50
335
    PZ_Lock(slot->freeListLock);
51
    /* own session list are symkeys with sessions that the symkey owns.
52
     * 'most' symkeys will own their own session. */
53
335
    if (needSession) {
54
335
        if (slot->freeSymKeysWithSessionHead) {
55
333
            symKey = slot->freeSymKeysWithSessionHead;
56
333
            slot->freeSymKeysWithSessionHead = symKey->next;
57
333
            slot->keyCount--;
58
333
        }
59
335
    }
60
    /* if we don't need a symkey with its own session, or we couldn't find
61
     * one on the owner list, get one from the non-owner free list. */
62
335
    if (!symKey) {
63
2
        if (slot->freeSymKeysHead) {
64
0
            symKey = slot->freeSymKeysHead;
65
0
            slot->freeSymKeysHead = symKey->next;
66
0
            slot->keyCount--;
67
0
        }
68
2
    }
69
335
    PZ_Unlock(slot->freeListLock);
70
335
    if (symKey) {
71
333
        symKey->next = NULL;
72
333
        if (!needSession) {
73
0
            return symKey;
74
0
        }
75
        /* if we are getting an owner key, make sure we have a valid session.
76
         * session could be invalid if the token has been removed or because
77
         * we got it from the non-owner free list */
78
333
        if ((symKey->series != slot->series) ||
79
333
            (symKey->session == CK_INVALID_HANDLE)) {
80
0
            symKey->session = pk11_GetNewSession(slot, &symKey->sessionOwner);
81
0
        }
82
333
        PORT_Assert(symKey->session != CK_INVALID_HANDLE);
83
333
        if (symKey->session != CK_INVALID_HANDLE)
84
333
            return symKey;
85
0
        PK11_FreeSymKey(symKey);
86
        /* if we are here, we need a session, but couldn't get one, it's
87
         * unlikely we pk11_GetNewSession will succeed if we call it a second
88
         * time. */
89
0
        return NULL;
90
333
    }
91
92
2
    symKey = PORT_New(PK11SymKey);
93
2
    if (symKey == NULL) {
94
0
        return NULL;
95
0
    }
96
97
2
    symKey->next = NULL;
98
2
    if (needSession) {
99
2
        symKey->session = pk11_GetNewSession(slot, &symKey->sessionOwner);
100
2
        PORT_Assert(symKey->session != CK_INVALID_HANDLE);
101
2
        if (symKey->session == CK_INVALID_HANDLE) {
102
0
            PK11_FreeSymKey(symKey);
103
0
            symKey = NULL;
104
0
        }
105
2
    } else {
106
0
        symKey->session = CK_INVALID_HANDLE;
107
0
    }
108
2
    return symKey;
109
2
}
110
111
/* Caller MUST hold slot->freeListLock (or ref count == 0?) !! */
112
void
113
PK11_CleanKeyList(PK11SlotInfo *slot)
114
0
{
115
0
    PK11SymKey *symKey = NULL;
116
117
0
    while (slot->freeSymKeysWithSessionHead) {
118
0
        symKey = slot->freeSymKeysWithSessionHead;
119
0
        slot->freeSymKeysWithSessionHead = symKey->next;
120
0
        pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
121
0
        PORT_Free(symKey);
122
0
    }
123
0
    while (slot->freeSymKeysHead) {
124
0
        symKey = slot->freeSymKeysHead;
125
0
        slot->freeSymKeysHead = symKey->next;
126
0
        pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
127
0
        PORT_Free(symKey);
128
0
    }
129
0
    return;
130
0
}
131
132
/*
133
 * create a symetric key:
134
 *      Slot is the slot to create the key in.
135
 *      type is the mechanism type
136
 *      owner is does this symKey structure own it's object handle (rare
137
 *        that this is false).
138
 *      needSession means the returned symKey will return with a valid session
139
 *        allocated already.
140
 */
141
static PK11SymKey *
142
pk11_CreateSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
143
                  PRBool owner, PRBool needSession, void *wincx)
144
335
{
145
146
335
    PK11SymKey *symKey = pk11_getKeyFromList(slot, needSession);
147
148
335
    if (symKey == NULL) {
149
0
        return NULL;
150
0
    }
151
    /* if needSession was specified, make sure we have a valid session.
152
     * callers which specify needSession as false should do their own
153
     * check of the session before returning the symKey */
154
335
    if (needSession && symKey->session == CK_INVALID_HANDLE) {
155
0
        PK11_FreeSymKey(symKey);
156
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
157
0
        return NULL;
158
0
    }
159
160
335
    symKey->type = type;
161
335
    symKey->data.type = siBuffer;
162
335
    symKey->data.data = NULL;
163
335
    symKey->data.len = 0;
164
335
    symKey->owner = owner;
165
335
    symKey->objectID = CK_INVALID_HANDLE;
166
335
    symKey->slot = slot;
167
335
    symKey->series = slot->series;
168
335
    symKey->cx = wincx;
169
335
    symKey->size = 0;
170
335
    symKey->refCount = 1;
171
335
    symKey->origin = PK11_OriginNULL;
172
335
    symKey->parent = NULL;
173
335
    symKey->freeFunc = NULL;
174
335
    symKey->userData = NULL;
175
335
    PK11_ReferenceSlot(slot);
176
335
    return symKey;
177
335
}
178
179
/*
180
 * destroy a symetric key
181
 */
182
void
183
PK11_FreeSymKey(PK11SymKey *symKey)
184
563
{
185
563
    PK11SlotInfo *slot;
186
563
    PRBool freeit = PR_TRUE;
187
188
563
    if (!symKey) {
189
0
        return;
190
0
    }
191
192
563
    if (PR_ATOMIC_DECREMENT(&symKey->refCount) == 0) {
193
335
        PK11SymKey *parent = symKey->parent;
194
195
335
        symKey->parent = NULL;
196
335
        if ((symKey->owner) && symKey->objectID != CK_INVALID_HANDLE) {
197
326
            pk11_EnterKeyMonitor(symKey);
198
326
            (void)PK11_GETTAB(symKey->slot)->C_DestroyObject(symKey->session, symKey->objectID);
199
326
            pk11_ExitKeyMonitor(symKey);
200
326
        }
201
335
        if (symKey->data.data) {
202
261
            PORT_Memset(symKey->data.data, 0, symKey->data.len);
203
261
            PORT_Free(symKey->data.data);
204
261
        }
205
        /* free any existing data */
206
335
        if (symKey->userData && symKey->freeFunc) {
207
0
            (*symKey->freeFunc)(symKey->userData);
208
0
        }
209
335
        slot = symKey->slot;
210
335
        PZ_Lock(slot->freeListLock);
211
335
        if (slot->keyCount < slot->maxKeyCount) {
212
            /*
213
             * freeSymkeysWithSessionHead contain a list of reusable
214
             *  SymKey structures with valid sessions.
215
             *    sessionOwner must be true.
216
             *    session must be valid.
217
             * freeSymKeysHead contain a list of SymKey structures without
218
             *  valid session.
219
             *    session must be CK_INVALID_HANDLE.
220
             *    though sessionOwner is false, callers should not depend on
221
             *    this fact.
222
             */
223
335
            if (symKey->sessionOwner) {
224
335
                PORT_Assert(symKey->session != CK_INVALID_HANDLE);
225
335
                symKey->next = slot->freeSymKeysWithSessionHead;
226
335
                slot->freeSymKeysWithSessionHead = symKey;
227
335
            } else {
228
0
                symKey->session = CK_INVALID_HANDLE;
229
0
                symKey->next = slot->freeSymKeysHead;
230
0
                slot->freeSymKeysHead = symKey;
231
0
            }
232
335
            slot->keyCount++;
233
335
            symKey->slot = NULL;
234
335
            freeit = PR_FALSE;
235
335
        }
236
335
        PZ_Unlock(slot->freeListLock);
237
335
        if (freeit) {
238
0
            pk11_CloseSession(symKey->slot, symKey->session,
239
0
                              symKey->sessionOwner);
240
0
            PORT_Free(symKey);
241
0
        }
242
335
        PK11_FreeSlot(slot);
243
244
335
        if (parent) {
245
0
            PK11_FreeSymKey(parent);
246
0
        }
247
335
    }
248
563
}
249
250
PK11SymKey *
251
PK11_ReferenceSymKey(PK11SymKey *symKey)
252
228
{
253
228
    PR_ATOMIC_INCREMENT(&symKey->refCount);
254
228
    return symKey;
255
228
}
256
257
/*
258
 * Accessors
259
 */
260
CK_MECHANISM_TYPE
261
PK11_GetMechanism(PK11SymKey *symKey)
262
0
{
263
0
    return symKey->type;
264
0
}
265
266
/*
267
 * return the slot associated with a symetric key
268
 */
269
PK11SlotInfo *
270
PK11_GetSlotFromKey(PK11SymKey *symKey)
271
0
{
272
0
    return PK11_ReferenceSlot(symKey->slot);
273
0
}
274
275
CK_KEY_TYPE
276
PK11_GetSymKeyType(PK11SymKey *symKey)
277
0
{
278
0
    return PK11_GetKeyType(symKey->type, symKey->size);
279
0
}
280
281
PK11SymKey *
282
PK11_GetNextSymKey(PK11SymKey *symKey)
283
0
{
284
0
    return symKey ? symKey->next : NULL;
285
0
}
286
287
char *
288
PK11_GetSymKeyNickname(PK11SymKey *symKey)
289
0
{
290
0
    return PK11_GetObjectNickname(symKey->slot, symKey->objectID);
291
0
}
292
293
SECStatus
294
PK11_SetSymKeyNickname(PK11SymKey *symKey, const char *nickname)
295
0
{
296
0
    return PK11_SetObjectNickname(symKey->slot, symKey->objectID, nickname);
297
0
}
298
299
void *
300
PK11_GetSymKeyUserData(PK11SymKey *symKey)
301
0
{
302
0
    return symKey->userData;
303
0
}
304
305
void
306
PK11_SetSymKeyUserData(PK11SymKey *symKey, void *userData,
307
                       PK11FreeDataFunc freeFunc)
308
0
{
309
    /* free any existing data */
310
0
    if (symKey->userData && symKey->freeFunc) {
311
0
        (*symKey->freeFunc)(symKey->userData);
312
0
    }
313
0
    symKey->userData = userData;
314
0
    symKey->freeFunc = freeFunc;
315
0
    return;
316
0
}
317
318
/*
319
 * turn key handle into an appropriate key object
320
 */
321
PK11SymKey *
322
PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent, PK11Origin origin,
323
                      CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID, PRBool owner, void *wincx)
324
0
{
325
0
    PK11SymKey *symKey;
326
0
    PRBool needSession = !(owner && parent);
327
328
0
    if (keyID == CK_INVALID_HANDLE) {
329
0
        return NULL;
330
0
    }
331
332
0
    symKey = pk11_CreateSymKey(slot, type, owner, needSession, wincx);
333
0
    if (symKey == NULL) {
334
0
        return NULL;
335
0
    }
336
337
0
    symKey->objectID = keyID;
338
0
    symKey->origin = origin;
339
340
    /* adopt the parent's session */
341
    /* This is only used by SSL. What we really want here is a session
342
     * structure with a ref count so  the session goes away only after all the
343
     * keys do. */
344
0
    if (!needSession) {
345
0
        symKey->sessionOwner = PR_FALSE;
346
0
        symKey->session = parent->session;
347
0
        symKey->parent = PK11_ReferenceSymKey(parent);
348
        /* This is the only case where pk11_CreateSymKey does not explicitly
349
         * check symKey->session. We need to assert here to make sure.
350
         * the session isn't invalid. */
351
0
        PORT_Assert(parent->session != CK_INVALID_HANDLE);
352
0
        if (parent->session == CK_INVALID_HANDLE) {
353
0
            PK11_FreeSymKey(symKey);
354
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
355
0
            return NULL;
356
0
        }
357
0
    }
358
359
0
    return symKey;
360
0
}
361
362
/*
363
 * Restore a symmetric wrapping key that was saved using PK11_SetWrapKey.
364
 *
365
 * This function is provided for ABI compatibility; see PK11_SetWrapKey below.
366
 */
367
PK11SymKey *
368
PK11_GetWrapKey(PK11SlotInfo *slot, int wrap, CK_MECHANISM_TYPE type,
369
                int series, void *wincx)
370
0
{
371
0
    PK11SymKey *symKey = NULL;
372
0
    CK_OBJECT_HANDLE keyHandle;
373
374
0
    PK11_EnterSlotMonitor(slot);
375
0
    if (slot->series != series ||
376
0
        slot->refKeys[wrap] == CK_INVALID_HANDLE) {
377
0
        PK11_ExitSlotMonitor(slot);
378
0
        return NULL;
379
0
    }
380
381
0
    if (type == CKM_INVALID_MECHANISM) {
382
0
        type = slot->wrapMechanism;
383
0
    }
384
385
0
    keyHandle = slot->refKeys[wrap];
386
0
    PK11_ExitSlotMonitor(slot);
387
0
    symKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive,
388
0
                                   slot->wrapMechanism, keyHandle, PR_FALSE, wincx);
389
0
    return symKey;
390
0
}
391
392
/*
393
 * This function sets an attribute on the current slot with a wrapping key.  The
394
 * data saved is ephemeral; it needs to be run every time the program is
395
 * invoked.
396
 *
397
 * Since NSS 3.45, this function is marginally more thread safe.  It uses the
398
 * slot lock (if present) and fails silently if a value is already set.  Use
399
 * PK11_GetWrapKey() after calling this function to get the current wrapping key
400
 * in case there was an update on another thread.
401
 *
402
 * Either way, using this function is inadvisable.  It's provided for ABI
403
 * compatibility only.
404
 */
405
void
406
PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey)
407
0
{
408
0
    PK11_EnterSlotMonitor(slot);
409
0
    if (wrap >= 0) {
410
0
        size_t uwrap = (size_t)wrap;
411
0
        if (uwrap < PR_ARRAY_SIZE(slot->refKeys) &&
412
0
            slot->refKeys[uwrap] == CK_INVALID_HANDLE) {
413
            /* save the handle and mechanism for the wrapping key */
414
            /* mark the key and session as not owned by us so they don't get
415
             * freed when the key goes way... that lets us reuse the key
416
             * later */
417
0
            slot->refKeys[uwrap] = wrapKey->objectID;
418
0
            wrapKey->owner = PR_FALSE;
419
0
            wrapKey->sessionOwner = PR_FALSE;
420
0
            slot->wrapMechanism = wrapKey->type;
421
0
        }
422
0
    }
423
0
    PK11_ExitSlotMonitor(slot);
424
0
}
425
426
/*
427
 * figure out if a key is still valid or if it is stale.
428
 */
429
PRBool
430
PK11_VerifyKeyOK(PK11SymKey *key)
431
0
{
432
0
    if (!PK11_IsPresent(key->slot)) {
433
0
        return PR_FALSE;
434
0
    }
435
0
    return (PRBool)(key->series == key->slot->series);
436
0
}
437
438
static PK11SymKey *
439
pk11_ImportSymKeyWithTempl(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
440
                           PK11Origin origin, PRBool isToken, CK_ATTRIBUTE *keyTemplate,
441
                           unsigned int templateCount, SECItem *key, void *wincx)
442
227
{
443
227
    PK11SymKey *symKey;
444
227
    SECStatus rv;
445
446
227
    symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE, wincx);
447
227
    if (symKey == NULL) {
448
0
        return NULL;
449
0
    }
450
451
227
    symKey->size = key->len;
452
453
227
    PK11_SETATTRS(&keyTemplate[templateCount], CKA_VALUE, key->data, key->len);
454
227
    templateCount++;
455
456
227
    if (SECITEM_CopyItem(NULL, &symKey->data, key) != SECSuccess) {
457
0
        PK11_FreeSymKey(symKey);
458
0
        return NULL;
459
0
    }
460
461
227
    symKey->origin = origin;
462
463
    /* import the keys */
464
227
    rv = PK11_CreateNewObject(slot, symKey->session, keyTemplate,
465
227
                              templateCount, isToken, &symKey->objectID);
466
227
    if (rv != SECSuccess) {
467
17
        PK11_FreeSymKey(symKey);
468
17
        return NULL;
469
17
    }
470
471
210
    return symKey;
472
227
}
473
474
/*
475
 * turn key bits into an appropriate key object
476
 */
477
PK11SymKey *
478
PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
479
                  PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx)
480
227
{
481
227
    PK11SymKey *symKey;
482
227
    unsigned int templateCount = 0;
483
227
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
484
227
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
485
227
    CK_BBOOL cktrue = CK_TRUE; /* sigh */
486
227
    CK_ATTRIBUTE keyTemplate[5];
487
227
    CK_ATTRIBUTE *attrs = keyTemplate;
488
489
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
490
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
491
     * it as a real attribute */
492
227
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
493
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
494
         * etc. Strip out the real attribute here */
495
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
496
0
    }
497
498
227
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
499
227
    attrs++;
500
227
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
501
227
    attrs++;
502
227
    PK11_SETATTRS(attrs, operation, &cktrue, 1);
503
227
    attrs++;
504
227
    templateCount = attrs - keyTemplate;
505
227
    PR_ASSERT(templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
506
507
227
    keyType = PK11_GetKeyType(type, key->len);
508
227
    symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, PR_FALSE,
509
227
                                        keyTemplate, templateCount, key, wincx);
510
227
    return symKey;
511
227
}
512
/* Import a PKCS #11 data object and return it as a key. This key is
513
 * only useful in a limited number of mechanisms, such as HKDF. */
514
PK11SymKey *
515
PK11_ImportDataKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, PK11Origin origin,
516
                   CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx)
517
0
{
518
0
    CK_OBJECT_CLASS ckoData = CKO_DATA;
519
0
    CK_ATTRIBUTE template[2] = { { CKA_CLASS, (CK_BYTE_PTR)&ckoData, sizeof(ckoData) },
520
0
                                 { CKA_VALUE, (CK_BYTE_PTR)key->data, key->len } };
521
0
    CK_OBJECT_HANDLE handle;
522
0
    PK11GenericObject *genObject;
523
524
0
    genObject = PK11_CreateGenericObject(slot, template, PR_ARRAY_SIZE(template), PR_FALSE);
525
0
    if (genObject == NULL) {
526
0
        return NULL;
527
0
    }
528
0
    handle = PK11_GetObjectHandle(PK11_TypeGeneric, genObject, NULL);
529
    /* A note about ownership of the PKCS #11 handle:
530
     * PK11_CreateGenericObject() will not destroy the object it creates
531
     * on Free, For that you want PK11_CreateManagedGenericObject().
532
     * Below we import the handle into the symKey structure. We pass
533
     * PR_TRUE as the owner so that the symKey will destroy the object
534
     * once it's freed. This is why it's safe to destroy genObject now. */
535
0
    PK11_DestroyGenericObject(genObject);
536
0
    if (handle == CK_INVALID_HANDLE) {
537
0
        return NULL;
538
0
    }
539
0
    return PK11_SymKeyFromHandle(slot, NULL, origin, type, handle, PR_TRUE, wincx);
540
0
}
541
542
/* turn key bits into an appropriate key object */
543
PK11SymKey *
544
PK11_ImportSymKeyWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
545
                           PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
546
                           CK_FLAGS flags, PRBool isPerm, void *wincx)
547
0
{
548
0
    PK11SymKey *symKey;
549
0
    unsigned int templateCount = 0;
550
0
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
551
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
552
0
    CK_BBOOL cktrue = CK_TRUE; /* sigh */
553
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
554
0
    CK_ATTRIBUTE *attrs = keyTemplate;
555
556
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
557
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
558
     * it as a real attribute */
559
0
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
560
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
561
         * etc. Strip out the real attribute here */
562
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
563
0
    }
564
565
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
566
0
    attrs++;
567
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
568
0
    attrs++;
569
0
    if (isPerm) {
570
0
        PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue));
571
0
        attrs++;
572
        /* sigh some tokens think CKA_PRIVATE = false is a reasonable
573
         * default for secret keys */
574
0
        PK11_SETATTRS(attrs, CKA_PRIVATE, &cktrue, sizeof(cktrue));
575
0
        attrs++;
576
0
    }
577
0
    attrs += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
578
0
    if ((operation != CKA_FLAGS_ONLY) &&
579
0
        !pk11_FindAttrInTemplate(keyTemplate, attrs - keyTemplate, operation)) {
580
0
        PK11_SETATTRS(attrs, operation, &cktrue, sizeof(cktrue));
581
0
        attrs++;
582
0
    }
583
0
    templateCount = attrs - keyTemplate;
584
0
    PR_ASSERT(templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
585
586
0
    keyType = PK11_GetKeyType(type, key->len);
587
0
    symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, isPerm,
588
0
                                        keyTemplate, templateCount, key, wincx);
589
0
    if (symKey && isPerm) {
590
0
        symKey->owner = PR_FALSE;
591
0
    }
592
0
    return symKey;
593
0
}
594
595
PK11SymKey *
596
PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *keyID,
597
                  void *wincx)
598
0
{
599
0
    CK_ATTRIBUTE findTemp[4];
600
0
    CK_ATTRIBUTE *attrs;
601
0
    CK_BBOOL ckTrue = CK_TRUE;
602
0
    CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
603
0
    size_t tsize = 0;
604
0
    CK_OBJECT_HANDLE key_id;
605
606
0
    attrs = findTemp;
607
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass));
608
0
    attrs++;
609
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue));
610
0
    attrs++;
611
0
    if (keyID) {
612
0
        PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len);
613
0
        attrs++;
614
0
    }
615
0
    tsize = attrs - findTemp;
616
0
    PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE));
617
618
0
    key_id = pk11_FindObjectByTemplate(slot, findTemp, tsize);
619
0
    if (key_id == CK_INVALID_HANDLE) {
620
0
        return NULL;
621
0
    }
622
0
    return PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive, type, key_id,
623
0
                                 PR_FALSE, wincx);
624
0
}
625
626
PK11SymKey *
627
PK11_ListFixedKeysInSlot(PK11SlotInfo *slot, char *nickname, void *wincx)
628
0
{
629
0
    CK_ATTRIBUTE findTemp[4];
630
0
    CK_ATTRIBUTE *attrs;
631
0
    CK_BBOOL ckTrue = CK_TRUE;
632
0
    CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
633
0
    int tsize = 0;
634
0
    int objCount = 0;
635
0
    CK_OBJECT_HANDLE *key_ids;
636
0
    PK11SymKey *nextKey = NULL;
637
0
    PK11SymKey *topKey = NULL;
638
0
    int i, len;
639
640
0
    attrs = findTemp;
641
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass));
642
0
    attrs++;
643
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue));
644
0
    attrs++;
645
0
    if (nickname) {
646
0
        len = PORT_Strlen(nickname);
647
0
        PK11_SETATTRS(attrs, CKA_LABEL, nickname, len);
648
0
        attrs++;
649
0
    }
650
0
    tsize = attrs - findTemp;
651
0
    PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE));
652
653
0
    key_ids = pk11_FindObjectsByTemplate(slot, findTemp, tsize, &objCount);
654
0
    if (key_ids == NULL) {
655
0
        return NULL;
656
0
    }
657
658
0
    for (i = 0; i < objCount; i++) {
659
0
        SECItem typeData;
660
0
        CK_KEY_TYPE type = CKK_GENERIC_SECRET;
661
0
        SECStatus rv = PK11_ReadAttribute(slot, key_ids[i],
662
0
                                          CKA_KEY_TYPE, NULL, &typeData);
663
0
        if (rv == SECSuccess) {
664
0
            if (typeData.len == sizeof(CK_KEY_TYPE)) {
665
0
                type = *(CK_KEY_TYPE *)typeData.data;
666
0
            }
667
0
            PORT_Free(typeData.data);
668
0
        }
669
0
        nextKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive,
670
0
                                        PK11_GetKeyMechanism(type), key_ids[i], PR_FALSE, wincx);
671
0
        if (nextKey) {
672
0
            nextKey->next = topKey;
673
0
            topKey = nextKey;
674
0
        }
675
0
    }
676
0
    PORT_Free(key_ids);
677
0
    return topKey;
678
0
}
679
680
void *
681
PK11_GetWindow(PK11SymKey *key)
682
0
{
683
0
    return key->cx;
684
0
}
685
686
/*
687
 * extract a symmetric key value. NOTE: if the key is sensitive, we will
688
 * not be able to do this operation. This function is used to move
689
 * keys from one token to another */
690
SECStatus
691
PK11_ExtractKeyValue(PK11SymKey *symKey)
692
56
{
693
56
    SECStatus rv;
694
695
56
    if (symKey == NULL) {
696
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
697
0
        return SECFailure;
698
0
    }
699
700
56
    if (symKey->data.data != NULL) {
701
0
        if (symKey->size == 0) {
702
0
            symKey->size = symKey->data.len;
703
0
        }
704
0
        return SECSuccess;
705
0
    }
706
707
56
    if (symKey->slot == NULL) {
708
0
        PORT_SetError(SEC_ERROR_INVALID_KEY);
709
0
        return SECFailure;
710
0
    }
711
712
56
    rv = PK11_ReadAttribute(symKey->slot, symKey->objectID, CKA_VALUE, NULL,
713
56
                            &symKey->data);
714
56
    if (rv == SECSuccess) {
715
56
        symKey->size = symKey->data.len;
716
56
    }
717
56
    return rv;
718
56
}
719
720
SECStatus
721
PK11_DeleteTokenSymKey(PK11SymKey *symKey)
722
0
{
723
0
    if (!PK11_IsPermObject(symKey->slot, symKey->objectID)) {
724
0
        return SECFailure;
725
0
    }
726
0
    PK11_DestroyTokenObject(symKey->slot, symKey->objectID);
727
0
    symKey->objectID = CK_INVALID_HANDLE;
728
0
    return SECSuccess;
729
0
}
730
731
SECItem *
732
PK11_GetKeyData(PK11SymKey *symKey)
733
56
{
734
56
    return &symKey->data;
735
56
}
736
737
/* This symbol is exported for backward compatibility. */
738
SECItem *
739
__PK11_GetKeyData(PK11SymKey *symKey)
740
0
{
741
0
    return PK11_GetKeyData(symKey);
742
0
}
743
744
/*
745
 * PKCS #11 key Types with predefined length
746
 */
747
unsigned int
748
pk11_GetPredefinedKeyLength(CK_KEY_TYPE keyType)
749
0
{
750
0
    int length = 0;
751
0
    switch (keyType) {
752
0
        case CKK_DES:
753
0
            length = 8;
754
0
            break;
755
0
        case CKK_DES2:
756
0
            length = 16;
757
0
            break;
758
0
        case CKK_DES3:
759
0
            length = 24;
760
0
            break;
761
0
        case CKK_SKIPJACK:
762
0
            length = 10;
763
0
            break;
764
0
        case CKK_BATON:
765
0
            length = 20;
766
0
            break;
767
0
        case CKK_JUNIPER:
768
0
            length = 20;
769
0
            break;
770
0
        default:
771
0
            break;
772
0
    }
773
0
    return length;
774
0
}
775
776
/* return the keylength if possible.  '0' if not */
777
unsigned int
778
PK11_GetKeyLength(PK11SymKey *key)
779
0
{
780
0
    CK_KEY_TYPE keyType;
781
782
0
    if (key->size != 0)
783
0
        return key->size;
784
785
    /* First try to figure out the key length from its type */
786
0
    keyType = PK11_ReadULongAttribute(key->slot, key->objectID, CKA_KEY_TYPE);
787
0
    key->size = pk11_GetPredefinedKeyLength(keyType);
788
0
    if ((keyType == CKK_GENERIC_SECRET) &&
789
0
        (key->type == CKM_SSL3_PRE_MASTER_KEY_GEN)) {
790
0
        key->size = 48;
791
0
    }
792
793
0
    if (key->size != 0)
794
0
        return key->size;
795
796
0
    if (key->data.data == NULL) {
797
0
        PK11_ExtractKeyValue(key);
798
0
    }
799
    /* key is probably secret. Look up its length */
800
    /*  this is new PKCS #11 version 2.0 functionality. */
801
0
    if (key->size == 0) {
802
0
        CK_ULONG keyLength;
803
804
0
        keyLength = PK11_ReadULongAttribute(key->slot, key->objectID, CKA_VALUE_LEN);
805
0
        if (keyLength != CK_UNAVAILABLE_INFORMATION) {
806
0
            key->size = (unsigned int)keyLength;
807
0
        }
808
0
    }
809
810
0
    return key->size;
811
0
}
812
813
/* return the strength of a key. This is different from length in that
814
 * 1) it returns the size in bits, and 2) it returns only the secret portions
815
 * of the key minus any checksums or parity.
816
 */
817
unsigned int
818
PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid)
819
0
{
820
0
    int size = 0;
821
0
    CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; /* RC2 only */
822
0
    SECItem *param = NULL;                               /* RC2 only */
823
0
    CK_RC2_CBC_PARAMS *rc2_params = NULL;                /* RC2 ONLY */
824
0
    unsigned int effectiveBits = 0;                      /* RC2 ONLY */
825
826
0
    switch (PK11_GetKeyType(key->type, 0)) {
827
0
        case CKK_CDMF:
828
0
            return 40;
829
0
        case CKK_DES:
830
0
            return 56;
831
0
        case CKK_DES3:
832
0
        case CKK_DES2:
833
0
            size = PK11_GetKeyLength(key);
834
0
            if (size == 16) {
835
                /* double des */
836
0
                return 112; /* 16*7 */
837
0
            }
838
0
            return 168;
839
        /*
840
         * RC2 has is different than other ciphers in that it allows the user
841
         * to deprecating keysize while still requiring all the bits for the
842
         * original key. The info
843
         * on what the effective key strength is in the parameter for the key.
844
         * In S/MIME this parameter is stored in the DER encoded algid. In Our
845
         * other uses of RC2, effectiveBits == keyBits, so this code functions
846
         * correctly without an algid.
847
         */
848
0
        case CKK_RC2:
849
            /* if no algid was provided, fall through to default */
850
0
            if (!algid) {
851
0
                break;
852
0
            }
853
            /* verify that the algid is for RC2 */
854
0
            mechanism = PK11_AlgtagToMechanism(SECOID_GetAlgorithmTag(algid));
855
0
            if ((mechanism != CKM_RC2_CBC) && (mechanism != CKM_RC2_ECB)) {
856
0
                break;
857
0
            }
858
859
            /* now get effective bits from the algorithm ID. */
860
0
            param = PK11_ParamFromAlgid(algid);
861
            /* if we couldn't get memory just use key length */
862
0
            if (param == NULL) {
863
0
                break;
864
0
            }
865
866
0
            rc2_params = (CK_RC2_CBC_PARAMS *)param->data;
867
            /* paranoia... shouldn't happen */
868
0
            PORT_Assert(param->data != NULL);
869
0
            if (param->data == NULL) {
870
0
                SECITEM_FreeItem(param, PR_TRUE);
871
0
                break;
872
0
            }
873
0
            effectiveBits = (unsigned int)rc2_params->ulEffectiveBits;
874
0
            SECITEM_FreeItem(param, PR_TRUE);
875
0
            param = NULL;
876
0
            rc2_params = NULL; /* paranoia */
877
878
            /* we have effective bits, is and allocated memory is free, now
879
             * we need to return the smaller of effective bits and keysize */
880
0
            size = PK11_GetKeyLength(key);
881
0
            if ((unsigned int)size * 8 > effectiveBits) {
882
0
                return effectiveBits;
883
0
            }
884
885
0
            return size * 8; /* the actual key is smaller, the strength can't be
886
                              * greater than the actual key size */
887
888
0
        default:
889
0
            break;
890
0
    }
891
0
    return PK11_GetKeyLength(key) * 8;
892
0
}
893
894
/*
895
 * The next three utilities are to deal with the fact that a given operation
896
 * may be a multi-slot affair. This creates a new key object that is copied
897
 * into the new slot.
898
 */
899
PK11SymKey *
900
pk11_CopyToSlotPerm(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
901
                    CK_ATTRIBUTE_TYPE operation, CK_FLAGS flags,
902
                    PRBool isPerm, PK11SymKey *symKey)
903
0
{
904
0
    SECStatus rv;
905
0
    PK11SymKey *newKey = NULL;
906
907
    /* Extract the raw key data if possible */
908
0
    if (symKey->data.data == NULL) {
909
0
        rv = PK11_ExtractKeyValue(symKey);
910
        /* KEY is sensitive, we're try key exchanging it. */
911
0
        if (rv != SECSuccess) {
912
0
            return pk11_KeyExchange(slot, type, operation,
913
0
                                    flags, isPerm, symKey);
914
0
        }
915
0
    }
916
917
0
    newKey = PK11_ImportSymKeyWithFlags(slot, type, symKey->origin,
918
0
                                        operation, &symKey->data, flags, isPerm, symKey->cx);
919
0
    if (newKey == NULL) {
920
0
        newKey = pk11_KeyExchange(slot, type, operation, flags, isPerm, symKey);
921
0
    }
922
0
    return newKey;
923
0
}
924
925
PK11SymKey *
926
pk11_CopyToSlot(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
927
                CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey)
928
0
{
929
0
    return pk11_CopyToSlotPerm(slot, type, operation, 0, PR_FALSE, symKey);
930
0
}
931
932
/*
933
 * Make sure the slot we are in is the correct slot for the operation
934
 * by verifying that it supports all of the specified mechanism types.
935
 */
936
PK11SymKey *
937
pk11_ForceSlotMultiple(PK11SymKey *symKey, CK_MECHANISM_TYPE *type,
938
                       int mechCount, CK_ATTRIBUTE_TYPE operation)
939
114
{
940
114
    PK11SlotInfo *slot = symKey->slot;
941
114
    PK11SymKey *newKey = NULL;
942
114
    PRBool needToCopy = PR_FALSE;
943
114
    int i;
944
945
114
    if (slot == NULL) {
946
0
        needToCopy = PR_TRUE;
947
114
    } else {
948
114
        i = 0;
949
228
        while ((i < mechCount) && (needToCopy == PR_FALSE)) {
950
114
            if (!PK11_DoesMechanism(slot, type[i])) {
951
32
                needToCopy = PR_TRUE;
952
32
            }
953
114
            i++;
954
114
        }
955
114
    }
956
957
114
    if (needToCopy == PR_TRUE) {
958
32
        slot = PK11_GetBestSlotMultiple(type, mechCount, symKey->cx);
959
32
        if (slot == NULL) {
960
32
            PORT_SetError(SEC_ERROR_NO_MODULE);
961
32
            return NULL;
962
32
        }
963
0
        newKey = pk11_CopyToSlot(slot, type[0], operation, symKey);
964
0
        PK11_FreeSlot(slot);
965
0
    }
966
82
    return newKey;
967
114
}
968
969
/*
970
 * Make sure the slot we are in is the correct slot for the operation
971
 */
972
PK11SymKey *
973
pk11_ForceSlot(PK11SymKey *symKey, CK_MECHANISM_TYPE type,
974
               CK_ATTRIBUTE_TYPE operation)
975
114
{
976
114
    return pk11_ForceSlotMultiple(symKey, &type, 1, operation);
977
114
}
978
979
PK11SymKey *
980
PK11_MoveSymKey(PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation,
981
                CK_FLAGS flags, PRBool perm, PK11SymKey *symKey)
982
0
{
983
0
    if (symKey->slot == slot) {
984
0
        if (perm) {
985
0
            return PK11_ConvertSessionSymKeyToTokenSymKey(symKey, symKey->cx);
986
0
        } else {
987
0
            return PK11_ReferenceSymKey(symKey);
988
0
        }
989
0
    }
990
991
0
    return pk11_CopyToSlotPerm(slot, symKey->type,
992
0
                               operation, flags, perm, symKey);
993
0
}
994
995
/*
996
 * Use the token to generate a key.
997
 *
998
 * keySize must be 'zero' for fixed key length algorithms. A nonzero
999
 *  keySize causes the CKA_VALUE_LEN attribute to be added to the template
1000
 *  for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN
1001
 *  attribute for keys with fixed length. The exception is DES2. If you
1002
 *  select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
1003
 *  parameter and use the key size to determine which underlying DES keygen
1004
 *  function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
1005
 *
1006
 * keyType must be -1 for most algorithms. Some PBE algorthims cannot
1007
 *  determine the correct key type from the mechanism or the parameters,
1008
 *  so key type must be specified. Other PKCS #11 mechanisms may do so in
1009
 *  the future. Currently there is no need to export this publically.
1010
 *  Keep it private until there is a need in case we need to expand the
1011
 *  keygen parameters again...
1012
 *
1013
 * CK_FLAGS flags: key operation flags
1014
 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
1015
 */
1016
PK11SymKey *
1017
pk11_TokenKeyGenWithFlagsAndKeyType(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1018
                                    SECItem *param, CK_KEY_TYPE keyType, int keySize, SECItem *keyid,
1019
                                    CK_FLAGS opFlags, PK11AttrFlags attrFlags, void *wincx)
1020
56
{
1021
56
    PK11SymKey *symKey;
1022
56
    CK_ATTRIBUTE genTemplate[MAX_TEMPL_ATTRS];
1023
56
    CK_ATTRIBUTE *attrs = genTemplate;
1024
56
    int count = sizeof(genTemplate) / sizeof(genTemplate[0]);
1025
56
    CK_MECHANISM_TYPE keyGenType;
1026
56
    CK_BBOOL cktrue = CK_TRUE;
1027
56
    CK_BBOOL ckfalse = CK_FALSE;
1028
56
    CK_ULONG ck_key_size; /* only used for variable-length keys */
1029
1030
56
    if (pk11_BadAttrFlags(attrFlags)) {
1031
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1032
0
        return NULL;
1033
0
    }
1034
1035
56
    if ((keySize != 0) && (type != CKM_DES3_CBC) &&
1036
56
        (type != CKM_DES3_CBC_PAD) && (type != CKM_DES3_ECB)) {
1037
56
        ck_key_size = keySize; /* Convert to PK11 type */
1038
1039
56
        PK11_SETATTRS(attrs, CKA_VALUE_LEN, &ck_key_size, sizeof(ck_key_size));
1040
56
        attrs++;
1041
56
    }
1042
1043
56
    if (keyType != -1) {
1044
56
        PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(CK_KEY_TYPE));
1045
56
        attrs++;
1046
56
    }
1047
1048
    /* Include key id value if provided */
1049
56
    if (keyid) {
1050
0
        PK11_SETATTRS(attrs, CKA_ID, keyid->data, keyid->len);
1051
0
        attrs++;
1052
0
    }
1053
1054
56
    attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
1055
56
    attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
1056
1057
56
    count = attrs - genTemplate;
1058
56
    PR_ASSERT(count <= sizeof(genTemplate) / sizeof(CK_ATTRIBUTE));
1059
1060
56
    keyGenType = PK11_GetKeyGenWithSize(type, keySize);
1061
56
    if (keyGenType == CKM_FAKE_RANDOM) {
1062
0
        PORT_SetError(SEC_ERROR_NO_MODULE);
1063
0
        return NULL;
1064
0
    }
1065
56
    symKey = PK11_KeyGenWithTemplate(slot, type, keyGenType,
1066
56
                                     param, genTemplate, count, wincx);
1067
56
    if (symKey != NULL) {
1068
56
        symKey->size = keySize;
1069
56
    }
1070
56
    return symKey;
1071
56
}
1072
1073
/*
1074
 * Use the token to generate a key.  - Public
1075
 *
1076
 * keySize must be 'zero' for fixed key length algorithms. A nonzero
1077
 *  keySize causes the CKA_VALUE_LEN attribute to be added to the template
1078
 *  for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN
1079
 *  attribute for keys with fixed length. The exception is DES2. If you
1080
 *  select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
1081
 *  parameter and use the key size to determine which underlying DES keygen
1082
 *  function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
1083
 *
1084
 * CK_FLAGS flags: key operation flags
1085
 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
1086
 */
1087
PK11SymKey *
1088
PK11_TokenKeyGenWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1089
                          SECItem *param, int keySize, SECItem *keyid, CK_FLAGS opFlags,
1090
                          PK11AttrFlags attrFlags, void *wincx)
1091
0
{
1092
0
    return pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param, -1, keySize,
1093
0
                                               keyid, opFlags, attrFlags, wincx);
1094
0
}
1095
1096
/*
1097
 * Use the token to generate a key. keySize must be 'zero' for fixed key
1098
 * length algorithms. A nonzero keySize causes the CKA_VALUE_LEN attribute
1099
 * to be added to the template for the key. PKCS #11 modules fail if you
1100
 * specify the CKA_VALUE_LEN attribute for keys with fixed length.
1101
 * NOTE: this means to generate a DES2 key from this interface you must
1102
 * specify CKM_DES2_KEY_GEN as the mechanism directly; specifying
1103
 * CKM_DES3_CBC as the mechanism and 16 as keySize currently doesn't work.
1104
 */
1105
PK11SymKey *
1106
PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
1107
                 int keySize, SECItem *keyid, PRBool isToken, void *wincx)
1108
0
{
1109
0
    PK11SymKey *symKey;
1110
0
    PRBool weird = PR_FALSE; /* hack for fortezza */
1111
0
    CK_FLAGS opFlags = CKF_SIGN;
1112
0
    PK11AttrFlags attrFlags = 0;
1113
1114
0
    if ((keySize == -1) && (type == CKM_SKIPJACK_CBC64)) {
1115
0
        weird = PR_TRUE;
1116
0
        keySize = 0;
1117
0
    }
1118
1119
0
    opFlags |= weird ? CKF_DECRYPT : CKF_ENCRYPT;
1120
1121
0
    if (isToken) {
1122
0
        attrFlags |= (PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE);
1123
0
    }
1124
1125
0
    symKey = pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param,
1126
0
                                                 -1, keySize, keyid, opFlags, attrFlags, wincx);
1127
0
    if (symKey && weird) {
1128
0
        PK11_SetFortezzaHack(symKey);
1129
0
    }
1130
1131
0
    return symKey;
1132
0
}
1133
1134
PK11SymKey *
1135
PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
1136
            int keySize, void *wincx)
1137
0
{
1138
0
    return PK11_TokenKeyGen(slot, type, param, keySize, 0, PR_FALSE, wincx);
1139
0
}
1140
1141
PK11SymKey *
1142
PK11_KeyGenWithTemplate(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1143
                        CK_MECHANISM_TYPE keyGenType,
1144
                        SECItem *param, CK_ATTRIBUTE *attrs,
1145
                        unsigned int attrsCount, void *wincx)
1146
56
{
1147
56
    PK11SymKey *symKey;
1148
56
    CK_SESSION_HANDLE session;
1149
56
    CK_MECHANISM mechanism;
1150
56
    CK_RV crv;
1151
56
    PRBool isToken = CK_FALSE;
1152
56
    CK_ULONG keySize = 0;
1153
56
    unsigned i;
1154
1155
    /* Extract the template's CKA_VALUE_LEN into keySize and CKA_TOKEN into
1156
       isToken. */
1157
448
    for (i = 0; i < attrsCount; ++i) {
1158
392
        switch (attrs[i].type) {
1159
56
            case CKA_VALUE_LEN:
1160
56
                if (attrs[i].pValue == NULL ||
1161
56
                    attrs[i].ulValueLen != sizeof(CK_ULONG)) {
1162
0
                    PORT_SetError(PK11_MapError(CKR_TEMPLATE_INCONSISTENT));
1163
0
                    return NULL;
1164
0
                }
1165
56
                keySize = *(CK_ULONG *)attrs[i].pValue;
1166
56
                break;
1167
0
            case CKA_TOKEN:
1168
0
                if (attrs[i].pValue == NULL ||
1169
0
                    attrs[i].ulValueLen != sizeof(CK_BBOOL)) {
1170
0
                    PORT_SetError(PK11_MapError(CKR_TEMPLATE_INCONSISTENT));
1171
0
                    return NULL;
1172
0
                }
1173
0
                isToken = (*(CK_BBOOL *)attrs[i].pValue) ? PR_TRUE : PR_FALSE;
1174
0
                break;
1175
392
        }
1176
392
    }
1177
1178
    /* find a slot to generate the key into */
1179
    /* Only do slot management if this is not a token key */
1180
56
    if (!isToken && (slot == NULL || !PK11_DoesMechanism(slot, type))) {
1181
0
        PK11SlotInfo *bestSlot = PK11_GetBestSlot(type, wincx);
1182
0
        if (bestSlot == NULL) {
1183
0
            PORT_SetError(SEC_ERROR_NO_MODULE);
1184
0
            return NULL;
1185
0
        }
1186
0
        symKey = pk11_CreateSymKey(bestSlot, type, !isToken, PR_TRUE, wincx);
1187
0
        PK11_FreeSlot(bestSlot);
1188
56
    } else {
1189
56
        symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE, wincx);
1190
56
    }
1191
56
    if (symKey == NULL)
1192
0
        return NULL;
1193
1194
56
    symKey->size = keySize;
1195
56
    symKey->origin = PK11_OriginGenerated;
1196
1197
    /* Set the parameters for the key gen if provided */
1198
56
    mechanism.mechanism = keyGenType;
1199
56
    mechanism.pParameter = NULL;
1200
56
    mechanism.ulParameterLen = 0;
1201
56
    if (param) {
1202
56
        mechanism.pParameter = param->data;
1203
56
        mechanism.ulParameterLen = param->len;
1204
56
    }
1205
1206
    /* Get session and perform locking */
1207
56
    if (isToken) {
1208
0
        PK11_Authenticate(symKey->slot, PR_TRUE, wincx);
1209
        /* Should always be original slot */
1210
0
        session = PK11_GetRWSession(symKey->slot);
1211
0
        symKey->owner = PR_FALSE;
1212
56
    } else {
1213
56
        session = symKey->session;
1214
56
        if (session != CK_INVALID_HANDLE)
1215
56
            pk11_EnterKeyMonitor(symKey);
1216
56
    }
1217
56
    if (session == CK_INVALID_HANDLE) {
1218
0
        PK11_FreeSymKey(symKey);
1219
0
        PORT_SetError(SEC_ERROR_BAD_DATA);
1220
0
        return NULL;
1221
0
    }
1222
1223
56
    crv = PK11_GETTAB(symKey->slot)->C_GenerateKey(session, &mechanism, attrs, attrsCount, &symKey->objectID);
1224
1225
    /* Release lock and session */
1226
56
    if (isToken) {
1227
0
        PK11_RestoreROSession(symKey->slot, session);
1228
56
    } else {
1229
56
        pk11_ExitKeyMonitor(symKey);
1230
56
    }
1231
1232
56
    if (crv != CKR_OK) {
1233
0
        PK11_FreeSymKey(symKey);
1234
0
        PORT_SetError(PK11_MapError(crv));
1235
0
        return NULL;
1236
0
    }
1237
1238
56
    return symKey;
1239
56
}
1240
1241
/* --- */
1242
PK11SymKey *
1243
PK11_GenDES3TokenKey(PK11SlotInfo *slot, SECItem *keyid, void *cx)
1244
0
{
1245
0
    return PK11_TokenKeyGen(slot, CKM_DES3_CBC, 0, 0, keyid, PR_TRUE, cx);
1246
0
}
1247
1248
PK11SymKey *
1249
PK11_ConvertSessionSymKeyToTokenSymKey(PK11SymKey *symk, void *wincx)
1250
0
{
1251
0
    PK11SlotInfo *slot = symk->slot;
1252
0
    CK_ATTRIBUTE template[1];
1253
0
    CK_ATTRIBUTE *attrs = template;
1254
0
    CK_BBOOL cktrue = CK_TRUE;
1255
0
    CK_RV crv;
1256
0
    CK_OBJECT_HANDLE newKeyID;
1257
0
    CK_SESSION_HANDLE rwsession;
1258
1259
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue));
1260
0
    attrs++;
1261
1262
0
    PK11_Authenticate(slot, PR_TRUE, wincx);
1263
0
    rwsession = PK11_GetRWSession(slot);
1264
0
    if (rwsession == CK_INVALID_HANDLE) {
1265
0
        PORT_SetError(SEC_ERROR_BAD_DATA);
1266
0
        return NULL;
1267
0
    }
1268
0
    crv = PK11_GETTAB(slot)->C_CopyObject(rwsession, symk->objectID,
1269
0
                                          template, 1, &newKeyID);
1270
0
    PK11_RestoreROSession(slot, rwsession);
1271
1272
0
    if (crv != CKR_OK) {
1273
0
        PORT_SetError(PK11_MapError(crv));
1274
0
        return NULL;
1275
0
    }
1276
1277
0
    return PK11_SymKeyFromHandle(slot, NULL /*parent*/, symk->origin,
1278
0
                                 symk->type, newKeyID, PR_FALSE /*owner*/, NULL /*wincx*/);
1279
0
}
1280
1281
/* This function does a straight public key wrap with the CKM_RSA_PKCS
1282
 * mechanism. */
1283
SECStatus
1284
PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
1285
                   PK11SymKey *symKey, SECItem *wrappedKey)
1286
0
{
1287
0
    CK_MECHANISM_TYPE inferred = pk11_mapWrapKeyType(pubKey->keyType);
1288
0
    return PK11_PubWrapSymKeyWithMechanism(pubKey, inferred, NULL, symKey,
1289
0
                                           wrappedKey);
1290
0
}
1291
1292
/* This function wraps a symmetric key with a public key, such as with the
1293
 * CKM_RSA_PKCS and CKM_RSA_PKCS_OAEP mechanisms. */
1294
SECStatus
1295
PK11_PubWrapSymKeyWithMechanism(SECKEYPublicKey *pubKey,
1296
                                CK_MECHANISM_TYPE mechType, SECItem *param,
1297
                                PK11SymKey *symKey, SECItem *wrappedKey)
1298
0
{
1299
0
    PK11SlotInfo *slot;
1300
0
    CK_ULONG len = wrappedKey->len;
1301
0
    PK11SymKey *newKey = NULL;
1302
0
    CK_OBJECT_HANDLE id;
1303
0
    CK_MECHANISM mechanism;
1304
0
    PRBool owner = PR_TRUE;
1305
0
    CK_SESSION_HANDLE session;
1306
0
    CK_RV crv;
1307
1308
0
    if (symKey == NULL) {
1309
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1310
0
        return SECFailure;
1311
0
    }
1312
1313
    /* if this slot doesn't support the mechanism, go to a slot that does */
1314
0
    newKey = pk11_ForceSlot(symKey, mechType, CKA_ENCRYPT);
1315
0
    if (newKey != NULL) {
1316
0
        symKey = newKey;
1317
0
    }
1318
1319
0
    if (symKey->slot == NULL) {
1320
0
        PORT_SetError(SEC_ERROR_NO_MODULE);
1321
0
        return SECFailure;
1322
0
    }
1323
1324
0
    slot = symKey->slot;
1325
1326
0
    mechanism.mechanism = mechType;
1327
0
    if (param == NULL) {
1328
0
        mechanism.pParameter = NULL;
1329
0
        mechanism.ulParameterLen = 0;
1330
0
    } else {
1331
0
        mechanism.pParameter = param->data;
1332
0
        mechanism.ulParameterLen = param->len;
1333
0
    }
1334
1335
0
    id = PK11_ImportPublicKey(slot, pubKey, PR_FALSE);
1336
0
    if (id == CK_INVALID_HANDLE) {
1337
0
        if (newKey) {
1338
0
            PK11_FreeSymKey(newKey);
1339
0
        }
1340
0
        return SECFailure; /* Error code has been set. */
1341
0
    }
1342
1343
0
    session = pk11_GetNewSession(slot, &owner);
1344
0
    if (!owner || !(slot->isThreadSafe))
1345
0
        PK11_EnterSlotMonitor(slot);
1346
0
    crv = PK11_GETTAB(slot)->C_WrapKey(session, &mechanism,
1347
0
                                       id, symKey->objectID, wrappedKey->data, &len);
1348
0
    if (!owner || !(slot->isThreadSafe))
1349
0
        PK11_ExitSlotMonitor(slot);
1350
0
    pk11_CloseSession(slot, session, owner);
1351
0
    if (newKey) {
1352
0
        PK11_FreeSymKey(newKey);
1353
0
    }
1354
1355
0
    if (crv != CKR_OK) {
1356
0
        PORT_SetError(PK11_MapError(crv));
1357
0
        return SECFailure;
1358
0
    }
1359
0
    wrappedKey->len = len;
1360
0
    return SECSuccess;
1361
0
}
1362
1363
/*
1364
 * this little function uses the Encrypt function to wrap a key, just in
1365
 * case we have problems with the wrap implementation for a token.
1366
 */
1367
static SECStatus
1368
pk11_HandWrap(PK11SymKey *wrappingKey, SECItem *param, CK_MECHANISM_TYPE type,
1369
              SECItem *inKey, SECItem *outKey)
1370
0
{
1371
0
    PK11SlotInfo *slot;
1372
0
    CK_ULONG len;
1373
0
    SECItem *data;
1374
0
    CK_MECHANISM mech;
1375
0
    PRBool owner = PR_TRUE;
1376
0
    CK_SESSION_HANDLE session;
1377
0
    CK_RV crv;
1378
1379
0
    slot = wrappingKey->slot;
1380
    /* use NULL IV's for wrapping */
1381
0
    mech.mechanism = type;
1382
0
    if (param) {
1383
0
        mech.pParameter = param->data;
1384
0
        mech.ulParameterLen = param->len;
1385
0
    } else {
1386
0
        mech.pParameter = NULL;
1387
0
        mech.ulParameterLen = 0;
1388
0
    }
1389
0
    session = pk11_GetNewSession(slot, &owner);
1390
0
    if (!owner || !(slot->isThreadSafe))
1391
0
        PK11_EnterSlotMonitor(slot);
1392
0
    crv = PK11_GETTAB(slot)->C_EncryptInit(session, &mech,
1393
0
                                           wrappingKey->objectID);
1394
0
    if (crv != CKR_OK) {
1395
0
        if (!owner || !(slot->isThreadSafe))
1396
0
            PK11_ExitSlotMonitor(slot);
1397
0
        pk11_CloseSession(slot, session, owner);
1398
0
        PORT_SetError(PK11_MapError(crv));
1399
0
        return SECFailure;
1400
0
    }
1401
1402
    /* keys are almost always aligned, but if we get this far,
1403
     * we've gone above and beyond anyway... */
1404
0
    data = PK11_BlockData(inKey, PK11_GetBlockSize(type, param));
1405
0
    if (data == NULL) {
1406
0
        if (!owner || !(slot->isThreadSafe))
1407
0
            PK11_ExitSlotMonitor(slot);
1408
0
        pk11_CloseSession(slot, session, owner);
1409
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
1410
0
        return SECFailure;
1411
0
    }
1412
0
    len = outKey->len;
1413
0
    crv = PK11_GETTAB(slot)->C_Encrypt(session, data->data, data->len,
1414
0
                                       outKey->data, &len);
1415
0
    if (!owner || !(slot->isThreadSafe))
1416
0
        PK11_ExitSlotMonitor(slot);
1417
0
    pk11_CloseSession(slot, session, owner);
1418
0
    SECITEM_FreeItem(data, PR_TRUE);
1419
0
    outKey->len = len;
1420
0
    if (crv != CKR_OK) {
1421
0
        PORT_SetError(PK11_MapError(crv));
1422
0
        return SECFailure;
1423
0
    }
1424
0
    return SECSuccess;
1425
0
}
1426
1427
/*
1428
 * helper function which moves two keys into a new slot based on the
1429
 * desired mechanism.
1430
 */
1431
static SECStatus
1432
pk11_moveTwoKeys(CK_MECHANISM_TYPE mech,
1433
                 CK_ATTRIBUTE_TYPE preferedOperation,
1434
                 CK_ATTRIBUTE_TYPE movingOperation,
1435
                 PK11SymKey *preferedKey, PK11SymKey *movingKey,
1436
                 PK11SymKey **newPreferedKey, PK11SymKey **newMovingKey)
1437
0
{
1438
0
    PK11SlotInfo *newSlot;
1439
0
    *newMovingKey = NULL;
1440
0
    *newPreferedKey = NULL;
1441
1442
0
    newSlot = PK11_GetBestSlot(mech, preferedKey->cx);
1443
0
    if (newSlot == NULL) {
1444
0
        return SECFailure;
1445
0
    }
1446
0
    *newMovingKey = pk11_CopyToSlot(newSlot, movingKey->type,
1447
0
                                    movingOperation, movingKey);
1448
0
    if (*newMovingKey == NULL) {
1449
0
        goto loser;
1450
0
    }
1451
0
    *newPreferedKey = pk11_CopyToSlot(newSlot, preferedKey->type,
1452
0
                                      preferedOperation, preferedKey);
1453
0
    if (*newPreferedKey == NULL) {
1454
0
        goto loser;
1455
0
    }
1456
1457
0
    PK11_FreeSlot(newSlot);
1458
0
    return SECSuccess;
1459
0
loser:
1460
0
    PK11_FreeSlot(newSlot);
1461
0
    PK11_FreeSymKey(*newMovingKey);
1462
0
    PK11_FreeSymKey(*newPreferedKey);
1463
0
    *newMovingKey = NULL;
1464
0
    *newPreferedKey = NULL;
1465
0
    return SECFailure;
1466
0
}
1467
1468
/*
1469
 * To do joint operations, we often need two keys in the same slot.
1470
 * Usually the PKCS #11 wrappers handle this correctly (like for PK11_WrapKey),
1471
 * but sometimes the wrappers don't know about mechanism specific keys in
1472
 * the Mechanism params. This function makes sure the two keys are in the
1473
 * same slot by copying one or both of the keys into a common slot. This
1474
 * functions makes sure the slot can handle the target mechanism. If the copy
1475
 * is warranted, this function will prefer to move the movingKey first, then
1476
 * the preferedKey. If the keys are moved, the new keys are returned in
1477
 * newMovingKey and/or newPreferedKey. The application is responsible
1478
 * for freeing those keys once the operation is complete.
1479
 */
1480
SECStatus
1481
PK11_SymKeysToSameSlot(CK_MECHANISM_TYPE mech,
1482
                       CK_ATTRIBUTE_TYPE preferedOperation,
1483
                       CK_ATTRIBUTE_TYPE movingOperation,
1484
                       PK11SymKey *preferedKey, PK11SymKey *movingKey,
1485
                       PK11SymKey **newPreferedKey, PK11SymKey **newMovingKey)
1486
0
{
1487
    /* usually don't return new keys */
1488
0
    *newMovingKey = NULL;
1489
0
    *newPreferedKey = NULL;
1490
0
    if (movingKey->slot == preferedKey->slot) {
1491
1492
        /* this should be the most common case */
1493
0
        if ((preferedKey->slot != NULL) &&
1494
0
            PK11_DoesMechanism(preferedKey->slot, mech)) {
1495
0
            return SECSuccess;
1496
0
        }
1497
1498
        /* we are in the same slot, but it doesn't do the operation,
1499
         * move both keys to an appropriate target slot */
1500
0
        return pk11_moveTwoKeys(mech, preferedOperation, movingOperation,
1501
0
                                preferedKey, movingKey,
1502
0
                                newPreferedKey, newMovingKey);
1503
0
    }
1504
1505
    /* keys are in different slot, try moving the moving key to the prefered
1506
     * key's slot */
1507
0
    if ((preferedKey->slot != NULL) &&
1508
0
        PK11_DoesMechanism(preferedKey->slot, mech)) {
1509
0
        *newMovingKey = pk11_CopyToSlot(preferedKey->slot, movingKey->type,
1510
0
                                        movingOperation, movingKey);
1511
0
        if (*newMovingKey != NULL) {
1512
0
            return SECSuccess;
1513
0
        }
1514
0
    }
1515
    /* couldn't moving the moving key to the prefered slot, try moving
1516
     * the prefered key */
1517
0
    if ((movingKey->slot != NULL) &&
1518
0
        PK11_DoesMechanism(movingKey->slot, mech)) {
1519
0
        *newPreferedKey = pk11_CopyToSlot(movingKey->slot, preferedKey->type,
1520
0
                                          preferedOperation, preferedKey);
1521
0
        if (*newPreferedKey != NULL) {
1522
0
            return SECSuccess;
1523
0
        }
1524
0
    }
1525
    /* Neither succeeded, but that could be that they were not in slots that
1526
     * supported the operation, try moving both keys into a common slot that
1527
     * can do the operation. */
1528
0
    return pk11_moveTwoKeys(mech, preferedOperation, movingOperation,
1529
0
                            preferedKey, movingKey,
1530
0
                            newPreferedKey, newMovingKey);
1531
0
}
1532
1533
/*
1534
 * This function does a symetric based wrap.
1535
 */
1536
SECStatus
1537
PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *param,
1538
                PK11SymKey *wrappingKey, PK11SymKey *symKey,
1539
                SECItem *wrappedKey)
1540
0
{
1541
0
    PK11SlotInfo *slot;
1542
0
    CK_ULONG len = wrappedKey->len;
1543
0
    PK11SymKey *newSymKey = NULL;
1544
0
    PK11SymKey *newWrappingKey = NULL;
1545
0
    SECItem *param_save = NULL;
1546
0
    CK_MECHANISM mechanism;
1547
0
    PRBool owner = PR_TRUE;
1548
0
    CK_SESSION_HANDLE session;
1549
0
    CK_RV crv;
1550
0
    SECStatus rv;
1551
1552
    /* force the keys into same slot */
1553
0
    rv = PK11_SymKeysToSameSlot(type, CKA_ENCRYPT, CKA_WRAP,
1554
0
                                symKey, wrappingKey,
1555
0
                                &newSymKey, &newWrappingKey);
1556
0
    if (rv != SECSuccess) {
1557
        /* Couldn't move the keys as desired, try to hand unwrap if possible */
1558
0
        if (symKey->data.data == NULL) {
1559
0
            rv = PK11_ExtractKeyValue(symKey);
1560
0
            if (rv != SECSuccess) {
1561
0
                PORT_SetError(SEC_ERROR_NO_MODULE);
1562
0
                return SECFailure;
1563
0
            }
1564
0
        }
1565
0
        if (param == NULL) {
1566
0
            param_save = param = PK11_ParamFromIV(type, NULL);
1567
0
        }
1568
0
        rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data, wrappedKey);
1569
0
        if (param_save)
1570
0
            SECITEM_FreeItem(param_save, PR_TRUE);
1571
0
        return rv;
1572
0
    }
1573
0
    if (newSymKey) {
1574
0
        symKey = newSymKey;
1575
0
    }
1576
0
    if (newWrappingKey) {
1577
0
        wrappingKey = newWrappingKey;
1578
0
    }
1579
1580
    /* at this point both keys are in the same token */
1581
0
    slot = wrappingKey->slot;
1582
0
    mechanism.mechanism = type;
1583
    /* use NULL IV's for wrapping */
1584
0
    if (param == NULL) {
1585
0
        param_save = param = PK11_ParamFromIV(type, NULL);
1586
0
    }
1587
0
    if (param) {
1588
0
        mechanism.pParameter = param->data;
1589
0
        mechanism.ulParameterLen = param->len;
1590
0
    } else {
1591
0
        mechanism.pParameter = NULL;
1592
0
        mechanism.ulParameterLen = 0;
1593
0
    }
1594
1595
0
    len = wrappedKey->len;
1596
1597
0
    session = pk11_GetNewSession(slot, &owner);
1598
0
    if (!owner || !(slot->isThreadSafe))
1599
0
        PK11_EnterSlotMonitor(slot);
1600
0
    crv = PK11_GETTAB(slot)->C_WrapKey(session, &mechanism,
1601
0
                                       wrappingKey->objectID, symKey->objectID,
1602
0
                                       wrappedKey->data, &len);
1603
0
    if (!owner || !(slot->isThreadSafe))
1604
0
        PK11_ExitSlotMonitor(slot);
1605
0
    pk11_CloseSession(slot, session, owner);
1606
0
    rv = SECSuccess;
1607
0
    if (crv != CKR_OK) {
1608
        /* can't wrap it? try hand wrapping it... */
1609
0
        do {
1610
0
            if (symKey->data.data == NULL) {
1611
0
                rv = PK11_ExtractKeyValue(symKey);
1612
0
                if (rv != SECSuccess)
1613
0
                    break;
1614
0
            }
1615
0
            rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data,
1616
0
                               wrappedKey);
1617
0
        } while (PR_FALSE);
1618
0
    } else {
1619
0
        wrappedKey->len = len;
1620
0
    }
1621
0
    PK11_FreeSymKey(newSymKey);
1622
0
    PK11_FreeSymKey(newWrappingKey);
1623
0
    if (param_save)
1624
0
        SECITEM_FreeItem(param_save, PR_TRUE);
1625
0
    return rv;
1626
0
}
1627
1628
/*
1629
 * This Generates a new key based on a symetricKey
1630
 */
1631
PK11SymKey *
1632
PK11_Derive(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, SECItem *param,
1633
            CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1634
            int keySize)
1635
52
{
1636
52
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1637
52
                                   keySize, NULL, 0, PR_FALSE);
1638
52
}
1639
1640
PK11SymKey *
1641
PK11_DeriveWithFlags(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1642
                     SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1643
                     int keySize, CK_FLAGS flags)
1644
0
{
1645
0
    CK_BBOOL ckTrue = CK_TRUE;
1646
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
1647
0
    unsigned int templateCount;
1648
1649
0
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
1650
0
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1651
0
                                   keySize, keyTemplate, templateCount, PR_FALSE);
1652
0
}
1653
1654
PK11SymKey *
1655
PK11_DeriveWithFlagsPerm(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1656
                         SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1657
                         int keySize, CK_FLAGS flags, PRBool isPerm)
1658
0
{
1659
0
    CK_BBOOL cktrue = CK_TRUE;
1660
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
1661
0
    CK_ATTRIBUTE *attrs;
1662
0
    unsigned int templateCount = 0;
1663
1664
0
    attrs = keyTemplate;
1665
0
    if (isPerm) {
1666
0
        PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
1667
0
        attrs++;
1668
0
    }
1669
0
    templateCount = attrs - keyTemplate;
1670
0
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
1671
0
    return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1672
0
                                   keySize, keyTemplate, templateCount, isPerm);
1673
0
}
1674
1675
PK11SymKey *
1676
PK11_DeriveWithTemplate(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1677
                        SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1678
                        int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs,
1679
                        PRBool isPerm)
1680
52
{
1681
52
    PK11SlotInfo *slot = baseKey->slot;
1682
52
    PK11SymKey *symKey;
1683
52
    PK11SymKey *newBaseKey = NULL;
1684
52
    CK_BBOOL cktrue = CK_TRUE;
1685
52
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
1686
52
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
1687
52
    CK_ULONG valueLen = 0;
1688
52
    CK_MECHANISM mechanism;
1689
52
    CK_RV crv;
1690
52
#define MAX_ADD_ATTRS 4
1691
52
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS + MAX_ADD_ATTRS];
1692
52
#undef MAX_ADD_ATTRS
1693
52
    CK_ATTRIBUTE *attrs = keyTemplate;
1694
52
    CK_SESSION_HANDLE session;
1695
52
    unsigned int templateCount;
1696
1697
52
    if (numAttrs > MAX_TEMPL_ATTRS) {
1698
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1699
0
        return NULL;
1700
0
    }
1701
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
1702
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
1703
     * it as a real attribute */
1704
52
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
1705
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
1706
         * etc. Strip out the real attribute here */
1707
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
1708
0
    }
1709
1710
    /* first copy caller attributes in. */
1711
52
    for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
1712
0
        *attrs++ = *userAttr++;
1713
0
    }
1714
1715
    /* We only add the following attributes to the template if the caller
1716
    ** didn't already supply them.
1717
    */
1718
52
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
1719
52
        PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
1720
52
        attrs++;
1721
52
    }
1722
52
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
1723
52
        keyType = PK11_GetKeyType(target, keySize);
1724
52
        PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType);
1725
52
        attrs++;
1726
52
    }
1727
52
    if (keySize > 0 &&
1728
52
        !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
1729
52
        valueLen = (CK_ULONG)keySize;
1730
52
        PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
1731
52
        attrs++;
1732
52
    }
1733
52
    if ((operation != CKA_FLAGS_ONLY) &&
1734
52
        !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
1735
52
        PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue);
1736
52
        attrs++;
1737
52
    }
1738
1739
52
    templateCount = attrs - keyTemplate;
1740
52
    PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
1741
1742
    /* move the key to a slot that can do the function */
1743
52
    if (!PK11_DoesMechanism(slot, derive)) {
1744
        /* get a new base key & slot */
1745
0
        PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
1746
1747
0
        if (newSlot == NULL)
1748
0
            return NULL;
1749
1750
0
        newBaseKey = pk11_CopyToSlot(newSlot, derive, CKA_DERIVE,
1751
0
                                     baseKey);
1752
0
        PK11_FreeSlot(newSlot);
1753
0
        if (newBaseKey == NULL)
1754
0
            return NULL;
1755
0
        baseKey = newBaseKey;
1756
0
        slot = baseKey->slot;
1757
0
    }
1758
1759
    /* get our key Structure */
1760
52
    symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE, baseKey->cx);
1761
52
    if (symKey == NULL) {
1762
0
        return NULL;
1763
0
    }
1764
1765
52
    symKey->size = keySize;
1766
1767
52
    mechanism.mechanism = derive;
1768
52
    if (param) {
1769
52
        mechanism.pParameter = param->data;
1770
52
        mechanism.ulParameterLen = param->len;
1771
52
    } else {
1772
0
        mechanism.pParameter = NULL;
1773
0
        mechanism.ulParameterLen = 0;
1774
0
    }
1775
52
    symKey->origin = PK11_OriginDerive;
1776
1777
52
    if (isPerm) {
1778
0
        session = PK11_GetRWSession(slot);
1779
52
    } else {
1780
52
        pk11_EnterKeyMonitor(symKey);
1781
52
        session = symKey->session;
1782
52
    }
1783
52
    if (session == CK_INVALID_HANDLE) {
1784
0
        if (!isPerm)
1785
0
            pk11_ExitKeyMonitor(symKey);
1786
0
        crv = CKR_SESSION_HANDLE_INVALID;
1787
52
    } else {
1788
52
        crv = PK11_GETTAB(slot)->C_DeriveKey(session, &mechanism,
1789
52
                                             baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
1790
52
        if (isPerm) {
1791
0
            PK11_RestoreROSession(slot, session);
1792
52
        } else {
1793
52
            pk11_ExitKeyMonitor(symKey);
1794
52
        }
1795
52
    }
1796
52
    if (newBaseKey)
1797
0
        PK11_FreeSymKey(newBaseKey);
1798
52
    if (crv != CKR_OK) {
1799
52
        PK11_FreeSymKey(symKey);
1800
52
        PORT_SetError(PK11_MapError(crv));
1801
52
        return NULL;
1802
52
    }
1803
0
    return symKey;
1804
52
}
1805
1806
/* Create a new key by concatenating base and data
1807
 */
1808
static PK11SymKey *
1809
pk11_ConcatenateBaseAndData(PK11SymKey *base,
1810
                            CK_BYTE *data, CK_ULONG dataLen, CK_MECHANISM_TYPE target,
1811
                            CK_ATTRIBUTE_TYPE operation)
1812
0
{
1813
0
    CK_KEY_DERIVATION_STRING_DATA mechParams;
1814
0
    SECItem param;
1815
1816
0
    if (base == NULL) {
1817
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1818
0
        return NULL;
1819
0
    }
1820
1821
0
    mechParams.pData = data;
1822
0
    mechParams.ulLen = dataLen;
1823
0
    param.data = (unsigned char *)&mechParams;
1824
0
    param.len = sizeof(CK_KEY_DERIVATION_STRING_DATA);
1825
1826
0
    return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_DATA,
1827
0
                       &param, target, operation, 0);
1828
0
}
1829
1830
/* Create a new key by concatenating base and key
1831
 */
1832
static PK11SymKey *
1833
pk11_ConcatenateBaseAndKey(PK11SymKey *base,
1834
                           PK11SymKey *key, CK_MECHANISM_TYPE target,
1835
                           CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1836
0
{
1837
0
    SECItem param;
1838
1839
0
    if ((base == NULL) || (key == NULL)) {
1840
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1841
0
        return NULL;
1842
0
    }
1843
1844
0
    param.data = (unsigned char *)&(key->objectID);
1845
0
    param.len = sizeof(CK_OBJECT_HANDLE);
1846
1847
0
    return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_KEY,
1848
0
                       &param, target, operation, keySize);
1849
0
}
1850
1851
PK11SymKey *
1852
PK11_ConcatSymKeys(PK11SymKey *left, PK11SymKey *right, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation)
1853
0
{
1854
0
    PK11SymKey *out = NULL;
1855
0
    PK11SymKey *copyOfLeft = NULL;
1856
0
    PK11SymKey *copyOfRight = NULL;
1857
1858
0
    if ((left == NULL) || (right == NULL)) {
1859
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1860
0
        return NULL;
1861
0
    }
1862
1863
0
    SECStatus rv = PK11_SymKeysToSameSlot(CKM_CONCATENATE_BASE_AND_KEY,
1864
0
                                          CKA_DERIVE, CKA_DERIVE, left, right,
1865
0
                                          &copyOfLeft, &copyOfRight);
1866
0
    if (rv != SECSuccess) {
1867
        /* error code already set */
1868
0
        return NULL;
1869
0
    }
1870
1871
0
    out = pk11_ConcatenateBaseAndKey(copyOfLeft ? copyOfLeft : left, copyOfRight ? copyOfRight : right, target, operation, 0);
1872
0
    PK11_FreeSymKey(copyOfLeft);
1873
0
    PK11_FreeSymKey(copyOfRight);
1874
0
    return out;
1875
0
}
1876
1877
/* Create a new key whose value is the hash of tobehashed.
1878
 * type is the mechanism for the derived key.
1879
 */
1880
static PK11SymKey *
1881
pk11_HashKeyDerivation(PK11SymKey *toBeHashed,
1882
                       CK_MECHANISM_TYPE hashMechanism, CK_MECHANISM_TYPE target,
1883
                       CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1884
0
{
1885
0
    return PK11_Derive(toBeHashed, hashMechanism, NULL, target, operation, keySize);
1886
0
}
1887
1888
/* This function implements the ANSI X9.63 key derivation function
1889
 */
1890
static PK11SymKey *
1891
pk11_ANSIX963Derive(PK11SymKey *sharedSecret,
1892
                    CK_EC_KDF_TYPE kdf, SECItem *sharedData,
1893
                    CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1894
                    CK_ULONG keySize)
1895
0
{
1896
0
    CK_KEY_TYPE keyType;
1897
0
    CK_MECHANISM_TYPE hashMechanism, mechanismArray[4];
1898
0
    CK_ULONG derivedKeySize, HashLen, counter, maxCounter, bufferLen;
1899
0
    CK_ULONG SharedInfoLen;
1900
0
    CK_BYTE *buffer = NULL;
1901
0
    PK11SymKey *toBeHashed, *hashOutput;
1902
0
    PK11SymKey *newSharedSecret = NULL;
1903
0
    PK11SymKey *oldIntermediateResult, *intermediateResult = NULL;
1904
1905
0
    if (sharedSecret == NULL) {
1906
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1907
0
        return NULL;
1908
0
    }
1909
1910
0
    switch (kdf) {
1911
0
        case CKD_SHA1_KDF:
1912
0
            HashLen = SHA1_LENGTH;
1913
0
            hashMechanism = CKM_SHA1_KEY_DERIVATION;
1914
0
            break;
1915
0
        case CKD_SHA224_KDF:
1916
0
            HashLen = SHA224_LENGTH;
1917
0
            hashMechanism = CKM_SHA224_KEY_DERIVATION;
1918
0
            break;
1919
0
        case CKD_SHA256_KDF:
1920
0
            HashLen = SHA256_LENGTH;
1921
0
            hashMechanism = CKM_SHA256_KEY_DERIVATION;
1922
0
            break;
1923
0
        case CKD_SHA384_KDF:
1924
0
            HashLen = SHA384_LENGTH;
1925
0
            hashMechanism = CKM_SHA384_KEY_DERIVATION;
1926
0
            break;
1927
0
        case CKD_SHA512_KDF:
1928
0
            HashLen = SHA512_LENGTH;
1929
0
            hashMechanism = CKM_SHA512_KEY_DERIVATION;
1930
0
            break;
1931
0
        default:
1932
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
1933
0
            return NULL;
1934
0
    }
1935
1936
0
    derivedKeySize = keySize;
1937
0
    if (derivedKeySize == 0) {
1938
0
        keyType = PK11_GetKeyType(target, keySize);
1939
0
        derivedKeySize = pk11_GetPredefinedKeyLength(keyType);
1940
0
        if (derivedKeySize == 0) {
1941
0
            derivedKeySize = HashLen;
1942
0
        }
1943
0
    }
1944
1945
    /* Check that key_len isn't too long.  The maximum key length could be
1946
     * greatly increased if the code below did not limit the 4-byte counter
1947
     * to a maximum value of 255. */
1948
0
    if (derivedKeySize > 254 * HashLen) {
1949
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1950
0
        return NULL;
1951
0
    }
1952
1953
0
    maxCounter = derivedKeySize / HashLen;
1954
0
    if (derivedKeySize > maxCounter * HashLen)
1955
0
        maxCounter++;
1956
1957
0
    if ((sharedData == NULL) || (sharedData->data == NULL))
1958
0
        SharedInfoLen = 0;
1959
0
    else
1960
0
        SharedInfoLen = sharedData->len;
1961
1962
0
    bufferLen = SharedInfoLen + 4;
1963
1964
    /* Populate buffer with Counter || sharedData
1965
     * where Counter is 0x00000001. */
1966
0
    buffer = (unsigned char *)PORT_Alloc(bufferLen);
1967
0
    if (buffer == NULL) {
1968
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
1969
0
        return NULL;
1970
0
    }
1971
1972
0
    buffer[0] = 0;
1973
0
    buffer[1] = 0;
1974
0
    buffer[2] = 0;
1975
0
    buffer[3] = 1;
1976
0
    if (SharedInfoLen > 0) {
1977
0
        PORT_Memcpy(&buffer[4], sharedData->data, SharedInfoLen);
1978
0
    }
1979
1980
    /* Look for a slot that supports the mechanisms needed
1981
     * to implement the ANSI X9.63 KDF as well as the
1982
     * target mechanism.
1983
     */
1984
0
    mechanismArray[0] = CKM_CONCATENATE_BASE_AND_DATA;
1985
0
    mechanismArray[1] = hashMechanism;
1986
0
    mechanismArray[2] = CKM_CONCATENATE_BASE_AND_KEY;
1987
0
    mechanismArray[3] = target;
1988
1989
0
    newSharedSecret = pk11_ForceSlotMultiple(sharedSecret,
1990
0
                                             mechanismArray, 4, operation);
1991
0
    if (newSharedSecret != NULL) {
1992
0
        sharedSecret = newSharedSecret;
1993
0
    }
1994
1995
0
    for (counter = 1; counter <= maxCounter; counter++) {
1996
        /* Concatenate shared_secret and buffer */
1997
0
        toBeHashed = pk11_ConcatenateBaseAndData(sharedSecret, buffer,
1998
0
                                                 bufferLen, hashMechanism, operation);
1999
0
        if (toBeHashed == NULL) {
2000
0
            goto loser;
2001
0
        }
2002
2003
        /* Hash value */
2004
0
        if (maxCounter == 1) {
2005
            /* In this case the length of the key to be derived is
2006
             * less than or equal to the length of the hash output.
2007
             * So, the output of the hash operation will be the
2008
             * dervied key. */
2009
0
            hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2010
0
                                                target, operation, keySize);
2011
0
        } else {
2012
            /* In this case, the output of the hash operation will be
2013
             * concatenated with other data to create the derived key. */
2014
0
            hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2015
0
                                                CKM_CONCATENATE_BASE_AND_KEY, operation, 0);
2016
0
        }
2017
0
        PK11_FreeSymKey(toBeHashed);
2018
0
        if (hashOutput == NULL) {
2019
0
            goto loser;
2020
0
        }
2021
2022
        /* Append result to intermediate result, if necessary */
2023
0
        oldIntermediateResult = intermediateResult;
2024
2025
0
        if (oldIntermediateResult == NULL) {
2026
0
            intermediateResult = hashOutput;
2027
0
        } else {
2028
0
            if (counter == maxCounter) {
2029
                /* This is the final concatenation, and so the output
2030
                 * will be the derived key. */
2031
0
                intermediateResult =
2032
0
                    pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2033
0
                                               hashOutput, target, operation, keySize);
2034
0
            } else {
2035
                /* The output of this concatenation will be concatenated
2036
                 * with other data to create the derived key. */
2037
0
                intermediateResult =
2038
0
                    pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2039
0
                                               hashOutput, CKM_CONCATENATE_BASE_AND_KEY,
2040
0
                                               operation, 0);
2041
0
            }
2042
2043
0
            PK11_FreeSymKey(hashOutput);
2044
0
            PK11_FreeSymKey(oldIntermediateResult);
2045
0
            if (intermediateResult == NULL) {
2046
0
                goto loser;
2047
0
            }
2048
0
        }
2049
2050
        /* Increment counter (assumes maxCounter < 255) */
2051
0
        buffer[3]++;
2052
0
    }
2053
2054
0
    PORT_ZFree(buffer, bufferLen);
2055
0
    if (newSharedSecret != NULL)
2056
0
        PK11_FreeSymKey(newSharedSecret);
2057
0
    return intermediateResult;
2058
2059
0
loser:
2060
0
    PORT_ZFree(buffer, bufferLen);
2061
0
    if (newSharedSecret != NULL)
2062
0
        PK11_FreeSymKey(newSharedSecret);
2063
0
    if (intermediateResult != NULL)
2064
0
        PK11_FreeSymKey(intermediateResult);
2065
0
    return NULL;
2066
0
}
2067
2068
/*
2069
 * This regenerate a public key from a private key. This function is currently
2070
 * NSS private. If we want to make it public, we need to add and optional
2071
 * template or at least flags (a.la. PK11_DeriveWithFlags).
2072
 */
2073
CK_OBJECT_HANDLE
2074
PK11_DerivePubKeyFromPrivKey(SECKEYPrivateKey *privKey)
2075
0
{
2076
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
2077
0
    CK_MECHANISM mechanism;
2078
0
    CK_OBJECT_HANDLE objectID = CK_INVALID_HANDLE;
2079
0
    CK_RV crv;
2080
2081
0
    mechanism.mechanism = CKM_NSS_PUB_FROM_PRIV;
2082
0
    mechanism.pParameter = NULL;
2083
0
    mechanism.ulParameterLen = 0;
2084
2085
0
    PK11_EnterSlotMonitor(slot);
2086
0
    crv = PK11_GETTAB(slot)->C_DeriveKey(slot->session, &mechanism,
2087
0
                                         privKey->pkcs11ID, NULL, 0,
2088
0
                                         &objectID);
2089
0
    PK11_ExitSlotMonitor(slot);
2090
0
    if (crv != CKR_OK) {
2091
0
        PORT_SetError(PK11_MapError(crv));
2092
0
        return CK_INVALID_HANDLE;
2093
0
    }
2094
0
    return objectID;
2095
0
}
2096
2097
/*
2098
 * This Generates a wrapping key based on a privateKey, publicKey, and two
2099
 * random numbers. For Mail usage RandomB should be NULL. In the Sender's
2100
 * case RandomA is generate, otherwise it is passed.
2101
 */
2102
PK11SymKey *
2103
PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2104
               PRBool isSender, SECItem *randomA, SECItem *randomB,
2105
               CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2106
               CK_ATTRIBUTE_TYPE operation, int keySize, void *wincx)
2107
0
{
2108
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
2109
0
    CK_MECHANISM mechanism;
2110
0
    PK11SymKey *symKey;
2111
0
    CK_RV crv;
2112
2113
    /* get our key Structure */
2114
0
    symKey = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, wincx);
2115
0
    if (symKey == NULL) {
2116
0
        return NULL;
2117
0
    }
2118
2119
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2120
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2121
     * it as a real attribute */
2122
0
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
2123
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2124
         * etc. Strip out the real attribute here */
2125
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
2126
0
    }
2127
2128
0
    symKey->origin = PK11_OriginDerive;
2129
2130
0
    switch (privKey->keyType) {
2131
0
        case rsaKey:
2132
0
        case rsaPssKey:
2133
0
        case rsaOaepKey:
2134
0
        case kyberKey:
2135
0
        case nullKey:
2136
0
        case edKey:
2137
0
        case ecMontKey:
2138
0
            PORT_SetError(SEC_ERROR_BAD_KEY);
2139
0
            break;
2140
0
        case dsaKey:
2141
0
        case keaKey:
2142
0
        case fortezzaKey: {
2143
0
            static unsigned char rb_email[128] = { 0 };
2144
0
            CK_KEA_DERIVE_PARAMS param;
2145
0
            param.isSender = (CK_BBOOL)isSender;
2146
0
            param.ulRandomLen = randomA->len;
2147
0
            param.pRandomA = randomA->data;
2148
0
            param.pRandomB = rb_email;
2149
0
            param.pRandomB[127] = 1;
2150
0
            if (randomB)
2151
0
                param.pRandomB = randomB->data;
2152
0
            if (pubKey->keyType == fortezzaKey) {
2153
0
                param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2154
0
                param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2155
0
            } else {
2156
                /* assert type == keaKey */
2157
                /* XXX change to match key key types */
2158
0
                param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2159
0
                param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2160
0
            }
2161
2162
0
            mechanism.mechanism = derive;
2163
0
            mechanism.pParameter = &param;
2164
0
            mechanism.ulParameterLen = sizeof(param);
2165
2166
            /* get a new symKey structure */
2167
0
            pk11_EnterKeyMonitor(symKey);
2168
0
            crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
2169
0
                                                 privKey->pkcs11ID, NULL, 0,
2170
0
                                                 &symKey->objectID);
2171
0
            pk11_ExitKeyMonitor(symKey);
2172
0
            if (crv == CKR_OK)
2173
0
                return symKey;
2174
0
            PORT_SetError(PK11_MapError(crv));
2175
0
        } break;
2176
0
        case dhKey: {
2177
0
            CK_BBOOL cktrue = CK_TRUE;
2178
0
            CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
2179
0
            CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
2180
0
            CK_ULONG key_size = 0;
2181
0
            CK_ATTRIBUTE keyTemplate[4];
2182
0
            int templateCount;
2183
0
            CK_ATTRIBUTE *attrs = keyTemplate;
2184
2185
0
            if (pubKey->keyType != dhKey) {
2186
0
                PORT_SetError(SEC_ERROR_BAD_KEY);
2187
0
                break;
2188
0
            }
2189
2190
0
            PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
2191
0
            attrs++;
2192
0
            PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
2193
0
            attrs++;
2194
0
            PK11_SETATTRS(attrs, operation, &cktrue, 1);
2195
0
            attrs++;
2196
0
            PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
2197
0
            attrs++;
2198
0
            templateCount = attrs - keyTemplate;
2199
0
            PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
2200
2201
0
            keyType = PK11_GetKeyType(target, keySize);
2202
0
            key_size = keySize;
2203
0
            symKey->size = keySize;
2204
0
            if (key_size == 0)
2205
0
                templateCount--;
2206
2207
0
            mechanism.mechanism = derive;
2208
2209
            /* we can undefine these when we define diffie-helman keys */
2210
2211
0
            mechanism.pParameter = pubKey->u.dh.publicValue.data;
2212
0
            mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
2213
2214
0
            pk11_EnterKeyMonitor(symKey);
2215
0
            crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
2216
0
                                                 privKey->pkcs11ID, keyTemplate,
2217
0
                                                 templateCount, &symKey->objectID);
2218
0
            pk11_ExitKeyMonitor(symKey);
2219
0
            if (crv == CKR_OK)
2220
0
                return symKey;
2221
0
            PORT_SetError(PK11_MapError(crv));
2222
0
        } break;
2223
0
        case ecKey: {
2224
0
            CK_BBOOL cktrue = CK_TRUE;
2225
0
            CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
2226
0
            CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
2227
0
            CK_ULONG key_size = 0;
2228
0
            CK_ATTRIBUTE keyTemplate[4];
2229
0
            int templateCount;
2230
0
            CK_ATTRIBUTE *attrs = keyTemplate;
2231
0
            CK_ECDH1_DERIVE_PARAMS *mechParams = NULL;
2232
2233
0
            if (pubKey->keyType != ecKey) {
2234
0
                PORT_SetError(SEC_ERROR_BAD_KEY);
2235
0
                break;
2236
0
            }
2237
2238
0
            PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
2239
0
            attrs++;
2240
0
            PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
2241
0
            attrs++;
2242
0
            PK11_SETATTRS(attrs, operation, &cktrue, 1);
2243
0
            attrs++;
2244
0
            PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
2245
0
            attrs++;
2246
0
            templateCount = attrs - keyTemplate;
2247
0
            PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
2248
2249
0
            keyType = PK11_GetKeyType(target, keySize);
2250
0
            key_size = keySize;
2251
0
            if (key_size == 0) {
2252
0
                if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2253
0
                    templateCount--;
2254
0
                } else {
2255
                    /* sigh, some tokens can't figure this out and require
2256
                     * CKA_VALUE_LEN to be set */
2257
0
                    key_size = SHA1_LENGTH;
2258
0
                }
2259
0
            }
2260
0
            symKey->size = key_size;
2261
2262
0
            mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS);
2263
0
            mechParams->kdf = CKD_SHA1_KDF;
2264
0
            mechParams->ulSharedDataLen = 0;
2265
0
            mechParams->pSharedData = NULL;
2266
0
            mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2267
0
            mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2268
2269
0
            mechanism.mechanism = derive;
2270
0
            mechanism.pParameter = mechParams;
2271
0
            mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2272
2273
0
            pk11_EnterKeyMonitor(symKey);
2274
0
            crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session,
2275
0
                                                 &mechanism, privKey->pkcs11ID, keyTemplate,
2276
0
                                                 templateCount, &symKey->objectID);
2277
0
            pk11_ExitKeyMonitor(symKey);
2278
2279
            /* old PKCS #11 spec was ambiguous on what needed to be passed,
2280
             * try this again with and encoded public key */
2281
0
            if (crv != CKR_OK && pk11_ECGetPubkeyEncoding(pubKey) != ECPoint_XOnly) {
2282
0
                SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL,
2283
0
                                                       &pubKey->u.ec.publicValue,
2284
0
                                                       SEC_ASN1_GET(SEC_OctetStringTemplate));
2285
0
                if (pubValue == NULL) {
2286
0
                    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2287
0
                    break;
2288
0
                }
2289
0
                mechParams->ulPublicDataLen = pubValue->len;
2290
0
                mechParams->pPublicData = pubValue->data;
2291
2292
0
                pk11_EnterKeyMonitor(symKey);
2293
0
                crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session,
2294
0
                                                     &mechanism, privKey->pkcs11ID, keyTemplate,
2295
0
                                                     templateCount, &symKey->objectID);
2296
0
                pk11_ExitKeyMonitor(symKey);
2297
2298
0
                SECITEM_FreeItem(pubValue, PR_TRUE);
2299
0
            }
2300
2301
0
            PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2302
2303
0
            if (crv == CKR_OK)
2304
0
                return symKey;
2305
0
            PORT_SetError(PK11_MapError(crv));
2306
0
        }
2307
0
    }
2308
2309
0
    PK11_FreeSymKey(symKey);
2310
0
    return NULL;
2311
0
}
2312
2313
/* Test for curves that are known to use a special encoding.
2314
 * Extend this function when additional curves are added. */
2315
static ECPointEncoding
2316
pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey)
2317
0
{
2318
0
    SECItem oid;
2319
0
    SECStatus rv;
2320
0
    PORTCheapArenaPool tmpArena;
2321
0
    ECPointEncoding encoding = ECPoint_Undefined;
2322
2323
0
    PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE);
2324
2325
    /* decode the OID tag */
2326
0
    rv = SEC_QuickDERDecodeItem(&tmpArena.arena, &oid,
2327
0
                                SEC_ASN1_GET(SEC_ObjectIDTemplate),
2328
0
                                &pubKey->u.ec.DEREncodedParams);
2329
0
    if (rv == SECSuccess) {
2330
0
        SECOidTag tag = SECOID_FindOIDTag(&oid);
2331
0
        switch (tag) {
2332
0
            case SEC_OID_X25519:
2333
0
            case SEC_OID_CURVE25519:
2334
0
                encoding = ECPoint_XOnly;
2335
0
                break;
2336
0
            case SEC_OID_SECG_EC_SECP256R1:
2337
0
            case SEC_OID_SECG_EC_SECP384R1:
2338
0
            case SEC_OID_SECG_EC_SECP521R1:
2339
0
            default:
2340
                /* unknown curve, default to uncompressed */
2341
0
                encoding = ECPoint_Uncompressed;
2342
0
        }
2343
0
    }
2344
0
    PORT_DestroyCheapArena(&tmpArena);
2345
0
    return encoding;
2346
0
}
2347
2348
/* Returns the size of the public key, or 0 if there
2349
 * is an error. */
2350
static CK_ULONG
2351
pk11_ECPubKeySize(SECKEYPublicKey *pubKey)
2352
0
{
2353
0
    SECItem *publicValue = &pubKey->u.ec.publicValue;
2354
2355
0
    ECPointEncoding encoding = pk11_ECGetPubkeyEncoding(pubKey);
2356
0
    if (encoding == ECPoint_XOnly) {
2357
0
        return publicValue->len;
2358
0
    }
2359
0
    if (encoding == ECPoint_Uncompressed) {
2360
        /* key encoded in uncompressed form */
2361
0
        return ((publicValue->len - 1) / 2);
2362
0
    }
2363
    /* key encoding not recognized */
2364
0
    return 0;
2365
0
}
2366
2367
static PK11SymKey *
2368
pk11_PubDeriveECKeyWithKDF(
2369
    SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2370
    PRBool isSender, SECItem *randomA, SECItem *randomB,
2371
    CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2372
    CK_ATTRIBUTE_TYPE operation, int keySize,
2373
    CK_ULONG kdf, SECItem *sharedData, void *wincx)
2374
0
{
2375
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
2376
0
    PK11SymKey *symKey;
2377
0
    PK11SymKey *SharedSecret;
2378
0
    CK_MECHANISM mechanism;
2379
0
    CK_RV crv;
2380
0
    CK_BBOOL cktrue = CK_TRUE;
2381
0
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
2382
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
2383
0
    CK_ULONG key_size = 0;
2384
0
    CK_ATTRIBUTE keyTemplate[4];
2385
0
    int templateCount;
2386
0
    CK_ATTRIBUTE *attrs = keyTemplate;
2387
0
    CK_ECDH1_DERIVE_PARAMS *mechParams = NULL;
2388
2389
0
    if (pubKey->keyType != ecKey && pubKey->keyType != ecMontKey) {
2390
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
2391
0
        return NULL;
2392
0
    }
2393
0
    if ((kdf != CKD_NULL) && (kdf != CKD_SHA1_KDF) &&
2394
0
        (kdf != CKD_SHA224_KDF) && (kdf != CKD_SHA256_KDF) &&
2395
0
        (kdf != CKD_SHA384_KDF) && (kdf != CKD_SHA512_KDF)) {
2396
0
        PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
2397
0
        return NULL;
2398
0
    }
2399
2400
    /* get our key Structure */
2401
0
    symKey = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, wincx);
2402
0
    if (symKey == NULL) {
2403
0
        return NULL;
2404
0
    }
2405
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2406
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2407
     * it as a real attribute */
2408
0
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
2409
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2410
         * etc. Strip out the real attribute here */
2411
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
2412
0
    }
2413
2414
0
    symKey->origin = PK11_OriginDerive;
2415
2416
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
2417
0
    attrs++;
2418
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
2419
0
    attrs++;
2420
0
    PK11_SETATTRS(attrs, operation, &cktrue, 1);
2421
0
    attrs++;
2422
0
    PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
2423
0
    attrs++;
2424
0
    templateCount = attrs - keyTemplate;
2425
0
    PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
2426
2427
0
    keyType = PK11_GetKeyType(target, keySize);
2428
0
    key_size = keySize;
2429
0
    if (key_size == 0) {
2430
0
        if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2431
0
            templateCount--;
2432
0
        } else {
2433
            /* sigh, some tokens can't figure this out and require
2434
             * CKA_VALUE_LEN to be set */
2435
0
            switch (kdf) {
2436
0
                case CKD_NULL:
2437
0
                    key_size = pk11_ECPubKeySize(pubKey);
2438
0
                    if (key_size == 0) {
2439
0
                        PK11_FreeSymKey(symKey);
2440
0
                        return NULL;
2441
0
                    }
2442
0
                    break;
2443
0
                case CKD_SHA1_KDF:
2444
0
                    key_size = SHA1_LENGTH;
2445
0
                    break;
2446
0
                case CKD_SHA224_KDF:
2447
0
                    key_size = SHA224_LENGTH;
2448
0
                    break;
2449
0
                case CKD_SHA256_KDF:
2450
0
                    key_size = SHA256_LENGTH;
2451
0
                    break;
2452
0
                case CKD_SHA384_KDF:
2453
0
                    key_size = SHA384_LENGTH;
2454
0
                    break;
2455
0
                case CKD_SHA512_KDF:
2456
0
                    key_size = SHA512_LENGTH;
2457
0
                    break;
2458
0
                default:
2459
0
                    PORT_AssertNotReached("Invalid CKD");
2460
0
                    PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
2461
0
                    PK11_FreeSymKey(symKey);
2462
0
                    return NULL;
2463
0
            }
2464
0
        }
2465
0
    }
2466
0
    symKey->size = key_size;
2467
2468
0
    mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS);
2469
0
    if (!mechParams) {
2470
0
        PK11_FreeSymKey(symKey);
2471
0
        return NULL;
2472
0
    }
2473
0
    mechParams->kdf = kdf;
2474
0
    if (sharedData == NULL) {
2475
0
        mechParams->ulSharedDataLen = 0;
2476
0
        mechParams->pSharedData = NULL;
2477
0
    } else {
2478
0
        mechParams->ulSharedDataLen = sharedData->len;
2479
0
        mechParams->pSharedData = sharedData->data;
2480
0
    }
2481
0
    mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2482
0
    mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2483
2484
0
    mechanism.mechanism = derive;
2485
0
    mechanism.pParameter = mechParams;
2486
0
    mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2487
2488
0
    pk11_EnterKeyMonitor(symKey);
2489
0
    crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
2490
0
                                         privKey->pkcs11ID, keyTemplate,
2491
0
                                         templateCount, &symKey->objectID);
2492
0
    pk11_ExitKeyMonitor(symKey);
2493
2494
    /* old PKCS #11 spec was ambiguous on what needed to be passed,
2495
     * try this again with an encoded public key */
2496
0
    if (crv != CKR_OK) {
2497
        /* For curves that only use X as public value and no encoding we don't
2498
         * have to try again. (Currently only Curve25519) */
2499
0
        if (pk11_ECGetPubkeyEncoding(pubKey) == ECPoint_XOnly) {
2500
0
            goto loser;
2501
0
        }
2502
0
        SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL,
2503
0
                                               &pubKey->u.ec.publicValue,
2504
0
                                               SEC_ASN1_GET(SEC_OctetStringTemplate));
2505
0
        if (pubValue == NULL) {
2506
0
            goto loser;
2507
0
        }
2508
0
        mechParams->ulPublicDataLen = pubValue->len;
2509
0
        mechParams->pPublicData = pubValue->data;
2510
2511
0
        pk11_EnterKeyMonitor(symKey);
2512
0
        crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session,
2513
0
                                             &mechanism, privKey->pkcs11ID, keyTemplate,
2514
0
                                             templateCount, &symKey->objectID);
2515
0
        pk11_ExitKeyMonitor(symKey);
2516
2517
0
        if ((crv != CKR_OK) && (kdf != CKD_NULL)) {
2518
            /* Some PKCS #11 libraries cannot perform the key derivation
2519
             * function. So, try calling C_DeriveKey with CKD_NULL and then
2520
             * performing the KDF separately.
2521
             */
2522
0
            CK_ULONG derivedKeySize = key_size;
2523
2524
0
            keyType = CKK_GENERIC_SECRET;
2525
0
            key_size = pk11_ECPubKeySize(pubKey);
2526
0
            if (key_size == 0) {
2527
0
                SECITEM_FreeItem(pubValue, PR_TRUE);
2528
0
                goto loser;
2529
0
            }
2530
0
            SharedSecret = symKey;
2531
0
            SharedSecret->size = key_size;
2532
2533
0
            mechParams->kdf = CKD_NULL;
2534
0
            mechParams->ulSharedDataLen = 0;
2535
0
            mechParams->pSharedData = NULL;
2536
0
            mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2537
0
            mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2538
2539
0
            pk11_EnterKeyMonitor(SharedSecret);
2540
0
            crv = PK11_GETTAB(slot)->C_DeriveKey(SharedSecret->session,
2541
0
                                                 &mechanism, privKey->pkcs11ID, keyTemplate,
2542
0
                                                 templateCount, &SharedSecret->objectID);
2543
0
            pk11_ExitKeyMonitor(SharedSecret);
2544
2545
0
            if (crv != CKR_OK) {
2546
                /* old PKCS #11 spec was ambiguous on what needed to be passed,
2547
                 * try this one final time with an encoded public key */
2548
0
                mechParams->ulPublicDataLen = pubValue->len;
2549
0
                mechParams->pPublicData = pubValue->data;
2550
2551
0
                pk11_EnterKeyMonitor(SharedSecret);
2552
0
                crv = PK11_GETTAB(slot)->C_DeriveKey(SharedSecret->session,
2553
0
                                                     &mechanism, privKey->pkcs11ID, keyTemplate,
2554
0
                                                     templateCount, &SharedSecret->objectID);
2555
0
                pk11_ExitKeyMonitor(SharedSecret);
2556
0
            }
2557
2558
            /* Perform KDF. */
2559
0
            if (crv == CKR_OK) {
2560
0
                symKey = pk11_ANSIX963Derive(SharedSecret, kdf,
2561
0
                                             sharedData, target, operation,
2562
0
                                             derivedKeySize);
2563
0
                PK11_FreeSymKey(SharedSecret);
2564
0
                if (symKey == NULL) {
2565
0
                    SECITEM_FreeItem(pubValue, PR_TRUE);
2566
0
                    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2567
0
                    return NULL;
2568
0
                }
2569
0
            }
2570
0
        }
2571
0
        SECITEM_FreeItem(pubValue, PR_TRUE);
2572
0
    }
2573
2574
0
loser:
2575
0
    PORT_ZFree(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2576
2577
0
    if (crv != CKR_OK) {
2578
0
        PK11_FreeSymKey(symKey);
2579
0
        symKey = NULL;
2580
0
        PORT_SetError(PK11_MapError(crv));
2581
0
    }
2582
0
    return symKey;
2583
0
}
2584
2585
PK11SymKey *
2586
PK11_PubDeriveWithKDF(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2587
                      PRBool isSender, SECItem *randomA, SECItem *randomB,
2588
                      CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2589
                      CK_ATTRIBUTE_TYPE operation, int keySize,
2590
                      CK_ULONG kdf, SECItem *sharedData, void *wincx)
2591
0
{
2592
2593
0
    switch (privKey->keyType) {
2594
0
        case rsaKey:
2595
0
        case nullKey:
2596
0
        case dsaKey:
2597
0
        case keaKey:
2598
0
        case fortezzaKey:
2599
0
        case dhKey:
2600
0
            return PK11_PubDerive(privKey, pubKey, isSender, randomA, randomB,
2601
0
                                  derive, target, operation, keySize, wincx);
2602
0
        case ecKey:
2603
0
        case ecMontKey:
2604
0
            return pk11_PubDeriveECKeyWithKDF(privKey, pubKey, isSender,
2605
0
                                              randomA, randomB, derive, target,
2606
0
                                              operation, keySize,
2607
0
                                              kdf, sharedData, wincx);
2608
0
        default:
2609
0
            PORT_SetError(SEC_ERROR_BAD_KEY);
2610
0
            break;
2611
0
    }
2612
2613
0
    return NULL;
2614
0
}
2615
2616
/*
2617
 * this little function uses the Decrypt function to unwrap a key, just in
2618
 * case we are having problem with unwrap. NOTE: The key size may
2619
 * not be preserved properly for some algorithms!
2620
 */
2621
static PK11SymKey *
2622
pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2623
                CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target,
2624
                CK_ATTRIBUTE *keyTemplate, unsigned int templateCount,
2625
                int key_size, void *wincx, CK_RV *crvp, PRBool isPerm)
2626
0
{
2627
0
    CK_ULONG len;
2628
0
    SECItem outKey;
2629
0
    PK11SymKey *symKey;
2630
0
    CK_RV crv;
2631
0
    PRBool owner = PR_TRUE;
2632
0
    CK_SESSION_HANDLE session;
2633
2634
    /* remove any VALUE_LEN parameters */
2635
0
    if (keyTemplate[templateCount - 1].type == CKA_VALUE_LEN) {
2636
0
        templateCount--;
2637
0
    }
2638
2639
    /* keys are almost always aligned, but if we get this far,
2640
     * we've gone above and beyond anyway... */
2641
0
    outKey.data = (unsigned char *)PORT_Alloc(inKey->len);
2642
0
    if (outKey.data == NULL) {
2643
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
2644
0
        if (crvp)
2645
0
            *crvp = CKR_HOST_MEMORY;
2646
0
        return NULL;
2647
0
    }
2648
0
    len = inKey->len;
2649
2650
    /* use NULL IV's for wrapping */
2651
0
    session = pk11_GetNewSession(slot, &owner);
2652
0
    if (!owner || !(slot->isThreadSafe))
2653
0
        PK11_EnterSlotMonitor(slot);
2654
0
    crv = PK11_GETTAB(slot)->C_DecryptInit(session, mech, wrappingKey);
2655
0
    if (crv != CKR_OK) {
2656
0
        if (!owner || !(slot->isThreadSafe))
2657
0
            PK11_ExitSlotMonitor(slot);
2658
0
        pk11_CloseSession(slot, session, owner);
2659
0
        PORT_Free(outKey.data);
2660
0
        PORT_SetError(PK11_MapError(crv));
2661
0
        if (crvp)
2662
0
            *crvp = crv;
2663
0
        return NULL;
2664
0
    }
2665
0
    crv = PK11_GETTAB(slot)->C_Decrypt(session, inKey->data, inKey->len,
2666
0
                                       outKey.data, &len);
2667
0
    if (!owner || !(slot->isThreadSafe))
2668
0
        PK11_ExitSlotMonitor(slot);
2669
0
    pk11_CloseSession(slot, session, owner);
2670
0
    if (crv != CKR_OK) {
2671
0
        PORT_Free(outKey.data);
2672
0
        PORT_SetError(PK11_MapError(crv));
2673
0
        if (crvp)
2674
0
            *crvp = crv;
2675
0
        return NULL;
2676
0
    }
2677
2678
0
    outKey.len = (key_size == 0) ? len : key_size;
2679
0
    outKey.type = siBuffer;
2680
2681
0
    if (PK11_DoesMechanism(slot, target)) {
2682
0
        symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2683
0
                                            isPerm, keyTemplate,
2684
0
                                            templateCount, &outKey, wincx);
2685
0
    } else {
2686
0
        slot = PK11_GetBestSlot(target, wincx);
2687
0
        if (slot == NULL) {
2688
0
            PORT_SetError(SEC_ERROR_NO_MODULE);
2689
0
            PORT_Free(outKey.data);
2690
0
            if (crvp)
2691
0
                *crvp = CKR_DEVICE_ERROR;
2692
0
            return NULL;
2693
0
        }
2694
0
        symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2695
0
                                            isPerm, keyTemplate,
2696
0
                                            templateCount, &outKey, wincx);
2697
0
        PK11_FreeSlot(slot);
2698
0
    }
2699
0
    PORT_Free(outKey.data);
2700
2701
0
    if (crvp)
2702
0
        *crvp = symKey ? CKR_OK : CKR_DEVICE_ERROR;
2703
0
    return symKey;
2704
0
}
2705
2706
/*
2707
 * The wrap/unwrap function is pretty much the same for private and
2708
 * public keys. It's just getting the Object ID and slot right. This is
2709
 * the combined unwrap function.
2710
 */
2711
static PK11SymKey *
2712
pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2713
                  CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
2714
                  CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
2715
                  void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs, PRBool isPerm)
2716
0
{
2717
0
    PK11SymKey *symKey;
2718
0
    SECItem *param_free = NULL;
2719
0
    CK_BBOOL cktrue = CK_TRUE;
2720
0
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
2721
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
2722
0
    CK_ULONG valueLen = 0;
2723
0
    CK_MECHANISM mechanism;
2724
0
    CK_SESSION_HANDLE rwsession;
2725
0
    CK_RV crv;
2726
0
    CK_MECHANISM_INFO mechanism_info;
2727
0
#define MAX_ADD_ATTRS 4
2728
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS + MAX_ADD_ATTRS];
2729
0
#undef MAX_ADD_ATTRS
2730
0
    CK_ATTRIBUTE *attrs = keyTemplate;
2731
0
    unsigned int templateCount;
2732
2733
0
    if (numAttrs > MAX_TEMPL_ATTRS) {
2734
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2735
0
        return NULL;
2736
0
    }
2737
    /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2738
     * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2739
     * it as a real attribute */
2740
0
    if ((operation & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
2741
        /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2742
         * etc. Strip out the real attribute here */
2743
0
        operation &= ~CKA_NSS_MESSAGE_MASK;
2744
0
    }
2745
2746
    /* first copy caller attributes in. */
2747
0
    for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
2748
0
        *attrs++ = *userAttr++;
2749
0
    }
2750
2751
    /* We only add the following attributes to the template if the caller
2752
    ** didn't already supply them.
2753
    */
2754
0
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
2755
0
        PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
2756
0
        attrs++;
2757
0
    }
2758
0
    if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
2759
0
        keyType = PK11_GetKeyType(target, keySize);
2760
0
        PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType);
2761
0
        attrs++;
2762
0
    }
2763
0
    if ((operation != CKA_FLAGS_ONLY) &&
2764
0
        !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
2765
0
        PK11_SETATTRS(attrs, operation, &cktrue, 1);
2766
0
        attrs++;
2767
0
    }
2768
2769
    /*
2770
     * must be last in case we need to use this template to import the key
2771
     */
2772
0
    if (keySize > 0 &&
2773
0
        !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
2774
0
        valueLen = (CK_ULONG)keySize;
2775
0
        PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
2776
0
        attrs++;
2777
0
    }
2778
2779
0
    templateCount = attrs - keyTemplate;
2780
0
    PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
2781
2782
    /* find out if we can do wrap directly. Because the RSA case if *very*
2783
     * common, cache the results for it. */
2784
0
    if ((wrapType == CKM_RSA_PKCS) && (slot->hasRSAInfo)) {
2785
0
        mechanism_info.flags = slot->RSAInfoFlags;
2786
0
    } else {
2787
0
        if (!slot->isThreadSafe)
2788
0
            PK11_EnterSlotMonitor(slot);
2789
0
        crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID, wrapType,
2790
0
                                                    &mechanism_info);
2791
0
        if (!slot->isThreadSafe)
2792
0
            PK11_ExitSlotMonitor(slot);
2793
0
        if (crv != CKR_OK) {
2794
0
            mechanism_info.flags = 0;
2795
0
        }
2796
0
        if (wrapType == CKM_RSA_PKCS) {
2797
0
            slot->RSAInfoFlags = mechanism_info.flags;
2798
0
            slot->hasRSAInfo = PR_TRUE;
2799
0
        }
2800
0
    }
2801
2802
    /* initialize the mechanism structure */
2803
0
    mechanism.mechanism = wrapType;
2804
    /* use NULL IV's for wrapping */
2805
0
    if (param == NULL)
2806
0
        param = param_free = PK11_ParamFromIV(wrapType, NULL);
2807
0
    if (param) {
2808
0
        mechanism.pParameter = param->data;
2809
0
        mechanism.ulParameterLen = param->len;
2810
0
    } else {
2811
0
        mechanism.pParameter = NULL;
2812
0
        mechanism.ulParameterLen = 0;
2813
0
    }
2814
2815
0
    if ((mechanism_info.flags & CKF_DECRYPT) && !PK11_DoesMechanism(slot, target)) {
2816
0
        symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2817
0
                                 target, keyTemplate, templateCount, keySize,
2818
0
                                 wincx, &crv, isPerm);
2819
0
        if (symKey) {
2820
0
            if (param_free)
2821
0
                SECITEM_FreeItem(param_free, PR_TRUE);
2822
0
            return symKey;
2823
0
        }
2824
        /*
2825
         * if the RSA OP simply failed, don't try to unwrap again
2826
         * with this module.
2827
         */
2828
0
        if (crv == CKR_DEVICE_ERROR) {
2829
0
            if (param_free)
2830
0
                SECITEM_FreeItem(param_free, PR_TRUE);
2831
0
            return NULL;
2832
0
        }
2833
        /* fall through, maybe they incorrectly set CKF_DECRYPT */
2834
0
    }
2835
2836
    /* get our key Structure */
2837
0
    symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE, wincx);
2838
0
    if (symKey == NULL) {
2839
0
        if (param_free)
2840
0
            SECITEM_FreeItem(param_free, PR_TRUE);
2841
0
        return NULL;
2842
0
    }
2843
2844
0
    symKey->size = keySize;
2845
0
    symKey->origin = PK11_OriginUnwrap;
2846
2847
0
    if (isPerm) {
2848
0
        rwsession = PK11_GetRWSession(slot);
2849
0
    } else {
2850
0
        pk11_EnterKeyMonitor(symKey);
2851
0
        rwsession = symKey->session;
2852
0
    }
2853
0
    PORT_Assert(rwsession != CK_INVALID_HANDLE);
2854
0
    if (rwsession == CK_INVALID_HANDLE)
2855
0
        crv = CKR_SESSION_HANDLE_INVALID;
2856
0
    else
2857
0
        crv = PK11_GETTAB(slot)->C_UnwrapKey(rwsession, &mechanism, wrappingKey,
2858
0
                                             wrappedKey->data, wrappedKey->len,
2859
0
                                             keyTemplate, templateCount,
2860
0
                                             &symKey->objectID);
2861
0
    if (isPerm) {
2862
0
        if (rwsession != CK_INVALID_HANDLE)
2863
0
            PK11_RestoreROSession(slot, rwsession);
2864
0
    } else {
2865
0
        pk11_ExitKeyMonitor(symKey);
2866
0
    }
2867
0
    if (param_free)
2868
0
        SECITEM_FreeItem(param_free, PR_TRUE);
2869
0
    if (crv != CKR_OK) {
2870
0
        PK11_FreeSymKey(symKey);
2871
0
        symKey = NULL;
2872
0
        if (crv != CKR_DEVICE_ERROR) {
2873
            /* try hand Unwrapping */
2874
0
            symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2875
0
                                     target, keyTemplate, templateCount,
2876
0
                                     keySize, wincx, NULL, isPerm);
2877
0
        }
2878
0
    }
2879
2880
0
    return symKey;
2881
0
}
2882
2883
/* use a symetric key to unwrap another symetric key */
2884
PK11SymKey *
2885
PK11_UnwrapSymKey(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2886
                  SECItem *param, SECItem *wrappedKey,
2887
                  CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2888
                  int keySize)
2889
0
{
2890
0
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2891
0
                             wrapType, param, wrappedKey, target, operation, keySize,
2892
0
                             wrappingKey->cx, NULL, 0, PR_FALSE);
2893
0
}
2894
2895
/* use a symetric key to unwrap another symetric key */
2896
PK11SymKey *
2897
PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2898
                           SECItem *param, SECItem *wrappedKey,
2899
                           CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2900
                           int keySize, CK_FLAGS flags)
2901
0
{
2902
0
    CK_BBOOL ckTrue = CK_TRUE;
2903
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
2904
0
    unsigned int templateCount;
2905
2906
0
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2907
0
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2908
0
                             wrapType, param, wrappedKey, target, operation, keySize,
2909
0
                             wrappingKey->cx, keyTemplate, templateCount, PR_FALSE);
2910
0
}
2911
2912
PK11SymKey *
2913
PK11_UnwrapSymKeyWithFlagsPerm(PK11SymKey *wrappingKey,
2914
                               CK_MECHANISM_TYPE wrapType,
2915
                               SECItem *param, SECItem *wrappedKey,
2916
                               CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2917
                               int keySize, CK_FLAGS flags, PRBool isPerm)
2918
0
{
2919
0
    CK_BBOOL cktrue = CK_TRUE;
2920
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
2921
0
    CK_ATTRIBUTE *attrs;
2922
0
    unsigned int templateCount;
2923
2924
0
    attrs = keyTemplate;
2925
0
    if (isPerm) {
2926
0
        PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
2927
0
        attrs++;
2928
0
    }
2929
0
    templateCount = attrs - keyTemplate;
2930
0
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
2931
2932
0
    return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2933
0
                             wrapType, param, wrappedKey, target, operation, keySize,
2934
0
                             wrappingKey->cx, keyTemplate, templateCount, isPerm);
2935
0
}
2936
2937
/* unwrap a symmetric key with a private key. Only supports CKM_RSA_PKCS. */
2938
PK11SymKey *
2939
PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
2940
                     CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
2941
0
{
2942
0
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2943
2944
0
    return PK11_PubUnwrapSymKeyWithMechanism(wrappingKey, wrapType, NULL,
2945
0
                                             wrappedKey, target, operation,
2946
0
                                             keySize);
2947
0
}
2948
2949
/* unwrap a symmetric key with a private key with the given parameters. */
2950
PK11SymKey *
2951
PK11_PubUnwrapSymKeyWithMechanism(SECKEYPrivateKey *wrappingKey,
2952
                                  CK_MECHANISM_TYPE mechType, SECItem *param,
2953
                                  SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2954
                                  CK_ATTRIBUTE_TYPE operation, int keySize)
2955
0
{
2956
0
    PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2957
2958
0
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)) {
2959
0
        PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2960
0
    }
2961
2962
0
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID, mechType, param,
2963
0
                             wrappedKey, target, operation, keySize,
2964
0
                             wrappingKey->wincx, NULL, 0, PR_FALSE);
2965
0
}
2966
2967
/* unwrap a symetric key with a private key. */
2968
PK11SymKey *
2969
PK11_PubUnwrapSymKeyWithFlags(SECKEYPrivateKey *wrappingKey,
2970
                              SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2971
                              CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags)
2972
0
{
2973
0
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2974
0
    CK_BBOOL ckTrue = CK_TRUE;
2975
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
2976
0
    unsigned int templateCount;
2977
0
    PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2978
2979
0
    templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2980
2981
0
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)) {
2982
0
        PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2983
0
    }
2984
2985
0
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
2986
0
                             wrapType, NULL, wrappedKey, target, operation, keySize,
2987
0
                             wrappingKey->wincx, keyTemplate, templateCount, PR_FALSE);
2988
0
}
2989
2990
PK11SymKey *
2991
PK11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey,
2992
                                  SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2993
                                  CK_ATTRIBUTE_TYPE operation, int keySize,
2994
                                  CK_FLAGS flags, PRBool isPerm)
2995
0
{
2996
0
    CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2997
0
    CK_BBOOL cktrue = CK_TRUE;
2998
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
2999
0
    CK_ATTRIBUTE *attrs;
3000
0
    unsigned int templateCount;
3001
0
    PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
3002
3003
0
    attrs = keyTemplate;
3004
0
    if (isPerm) {
3005
0
        PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
3006
0
        attrs++;
3007
0
    }
3008
0
    templateCount = attrs - keyTemplate;
3009
3010
0
    templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
3011
3012
0
    if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)) {
3013
0
        PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
3014
0
    }
3015
3016
0
    return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
3017
0
                             wrapType, NULL, wrappedKey, target, operation, keySize,
3018
0
                             wrappingKey->wincx, keyTemplate, templateCount, isPerm);
3019
0
}
3020
3021
PK11SymKey *
3022
PK11_CopySymKeyForSigning(PK11SymKey *originalKey, CK_MECHANISM_TYPE mech)
3023
0
{
3024
0
    CK_RV crv;
3025
0
    CK_ATTRIBUTE setTemplate;
3026
0
    CK_BBOOL ckTrue = CK_TRUE;
3027
0
    PK11SlotInfo *slot = originalKey->slot;
3028
3029
    /* first just try to set this key up for signing */
3030
0
    PK11_SETATTRS(&setTemplate, CKA_SIGN, &ckTrue, sizeof(ckTrue));
3031
0
    pk11_EnterKeyMonitor(originalKey);
3032
0
    crv = PK11_GETTAB(slot)->C_SetAttributeValue(originalKey->session,
3033
0
                                                 originalKey->objectID, &setTemplate, 1);
3034
0
    pk11_ExitKeyMonitor(originalKey);
3035
0
    if (crv == CKR_OK) {
3036
0
        return PK11_ReferenceSymKey(originalKey);
3037
0
    }
3038
3039
    /* nope, doesn't like it, use the pk11 copy object command */
3040
0
    return pk11_CopyToSlot(slot, mech, CKA_SIGN, originalKey);
3041
0
}
3042
3043
void
3044
PK11_SetFortezzaHack(PK11SymKey *symKey)
3045
0
{
3046
0
    symKey->origin = PK11_OriginFortezzaHack;
3047
0
}
3048
3049
/*
3050
 * This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
3051
 * working. This function simply gets a valid IV for the keys.
3052
 */
3053
SECStatus
3054
PK11_GenerateFortezzaIV(PK11SymKey *symKey, unsigned char *iv, int len)
3055
0
{
3056
0
    CK_MECHANISM mech_info;
3057
0
    CK_ULONG count = 0;
3058
0
    CK_RV crv;
3059
0
    SECStatus rv = SECFailure;
3060
3061
0
    mech_info.mechanism = CKM_SKIPJACK_CBC64;
3062
0
    mech_info.pParameter = iv;
3063
0
    mech_info.ulParameterLen = len;
3064
3065
    /* generate the IV for fortezza */
3066
0
    PK11_EnterSlotMonitor(symKey->slot);
3067
0
    crv = PK11_GETTAB(symKey->slot)->C_EncryptInit(symKey->slot->session, &mech_info, symKey->objectID);
3068
0
    if (crv == CKR_OK) {
3069
0
        PK11_GETTAB(symKey->slot)->C_EncryptFinal(symKey->slot->session, NULL, &count);
3070
0
        rv = SECSuccess;
3071
0
    }
3072
0
    PK11_ExitSlotMonitor(symKey->slot);
3073
0
    return rv;
3074
0
}
3075
3076
CK_OBJECT_HANDLE
3077
PK11_GetSymKeyHandle(PK11SymKey *symKey)
3078
0
{
3079
0
    return symKey->objectID;
3080
0
}
3081
3082
static CK_ULONG
3083
pk11_KyberCiphertextLength(SECKEYKyberPublicKey *pubKey)
3084
0
{
3085
0
    switch (pubKey->params) {
3086
0
        case params_kyber768_round3:
3087
0
        case params_kyber768_round3_test_mode:
3088
0
        case params_ml_kem768:
3089
0
        case params_ml_kem768_test_mode:
3090
0
            return KYBER768_CIPHERTEXT_BYTES;
3091
0
        default:
3092
            // unreachable
3093
0
            return 0;
3094
0
    }
3095
0
}
3096
3097
static CK_ULONG
3098
pk11_KEMCiphertextLength(SECKEYPublicKey *pubKey)
3099
0
{
3100
0
    switch (pubKey->keyType) {
3101
0
        case kyberKey:
3102
0
            return pk11_KyberCiphertextLength(&pubKey->u.kyber);
3103
0
        default:
3104
            // unreachable
3105
0
            PORT_Assert(0);
3106
0
            return 0;
3107
0
    }
3108
0
}
3109
3110
SECStatus
3111
PK11_Encapsulate(SECKEYPublicKey *pubKey, CK_MECHANISM_TYPE target, PK11AttrFlags attrFlags, CK_FLAGS opFlags, PK11SymKey **outKey, SECItem **outCiphertext)
3112
0
{
3113
0
    PORT_Assert(pubKey);
3114
0
    PORT_Assert(outKey);
3115
0
    PORT_Assert(outCiphertext);
3116
3117
0
    PK11SlotInfo *slot = pubKey->pkcs11Slot;
3118
3119
0
    PK11SymKey *sharedSecret = NULL;
3120
0
    SECItem *ciphertext = NULL;
3121
3122
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
3123
0
    unsigned int templateCount;
3124
3125
0
    CK_ATTRIBUTE *attrs;
3126
0
    CK_BBOOL cktrue = CK_TRUE;
3127
0
    CK_BBOOL ckfalse = CK_FALSE;
3128
0
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
3129
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
3130
3131
0
    CK_INTERFACE_PTR KEMInterface = NULL;
3132
0
    CK_UTF8CHAR_PTR KEMInterfaceName = (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3133
0
    CK_VERSION KEMInterfaceVersion = { 1, 0 };
3134
0
    CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL;
3135
3136
0
    CK_RV crv;
3137
3138
0
    *outKey = NULL;
3139
0
    *outCiphertext = NULL;
3140
3141
0
    CK_MECHANISM_TYPE kemType;
3142
0
    CK_NSS_KEM_PARAMETER_SET_TYPE kemParameterSet = PK11_ReadULongAttribute(slot, pubKey->pkcs11ID, CKA_NSS_PARAMETER_SET);
3143
0
    switch (kemParameterSet) {
3144
0
        case CKP_NSS_KYBER_768_ROUND3:
3145
0
            kemType = CKM_NSS_KYBER;
3146
0
            break;
3147
0
        case CKP_NSS_ML_KEM_768:
3148
0
            kemType = CKM_NSS_ML_KEM;
3149
0
            break;
3150
0
        default:
3151
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
3152
0
            return SECFailure;
3153
0
    }
3154
0
    CK_MECHANISM mech = { kemType, &kemParameterSet, sizeof(kemParameterSet) };
3155
3156
0
    sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, NULL);
3157
0
    if (sharedSecret == NULL) {
3158
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
3159
0
        return SECFailure;
3160
0
    }
3161
0
    sharedSecret->origin = PK11_OriginGenerated;
3162
3163
0
    attrs = keyTemplate;
3164
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
3165
0
    attrs++;
3166
3167
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
3168
0
    attrs++;
3169
3170
0
    attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3171
0
    attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3172
3173
0
    templateCount = attrs - keyTemplate;
3174
0
    PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
3175
3176
0
    crv = PK11_GETTAB(slot)->C_GetInterface(KEMInterfaceName, &KEMInterfaceVersion, &KEMInterface, 0);
3177
0
    if (crv != CKR_OK) {
3178
0
        goto error;
3179
0
    }
3180
0
    KEMInterfaceFunctions = (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3181
3182
0
    CK_ULONG ciphertextLen = pk11_KEMCiphertextLength(pubKey);
3183
0
    ciphertext = SECITEM_AllocItem(NULL, NULL, ciphertextLen);
3184
0
    if (ciphertext == NULL) {
3185
0
        crv = CKR_HOST_MEMORY;
3186
0
        goto error;
3187
0
    }
3188
3189
0
    pk11_EnterKeyMonitor(sharedSecret);
3190
0
    crv = KEMInterfaceFunctions->C_Encapsulate(sharedSecret->session,
3191
0
                                               &mech,
3192
0
                                               pubKey->pkcs11ID,
3193
0
                                               keyTemplate,
3194
0
                                               templateCount,
3195
0
                                               &sharedSecret->objectID,
3196
0
                                               ciphertext->data,
3197
0
                                               &ciphertextLen);
3198
0
    pk11_ExitKeyMonitor(sharedSecret);
3199
0
    if (crv != CKR_OK) {
3200
0
        goto error;
3201
0
    }
3202
3203
0
    PORT_Assert(ciphertextLen == ciphertext->len);
3204
3205
0
    *outKey = sharedSecret;
3206
0
    *outCiphertext = ciphertext;
3207
3208
0
    return SECSuccess;
3209
3210
0
error:
3211
0
    PORT_SetError(PK11_MapError(crv));
3212
0
    PK11_FreeSymKey(sharedSecret);
3213
0
    SECITEM_FreeItem(ciphertext, PR_TRUE);
3214
0
    return SECFailure;
3215
0
}
3216
3217
SECStatus
3218
PK11_Decapsulate(SECKEYPrivateKey *privKey, const SECItem *ciphertext, CK_MECHANISM_TYPE target, PK11AttrFlags attrFlags, CK_FLAGS opFlags, PK11SymKey **outKey)
3219
0
{
3220
0
    PORT_Assert(privKey);
3221
0
    PORT_Assert(ciphertext);
3222
0
    PORT_Assert(outKey);
3223
3224
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
3225
3226
0
    PK11SymKey *sharedSecret;
3227
3228
0
    CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
3229
0
    unsigned int templateCount;
3230
3231
0
    CK_ATTRIBUTE *attrs;
3232
0
    CK_BBOOL cktrue = CK_TRUE;
3233
0
    CK_BBOOL ckfalse = CK_FALSE;
3234
0
    CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
3235
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
3236
3237
0
    CK_INTERFACE_PTR KEMInterface = NULL;
3238
0
    CK_UTF8CHAR_PTR KEMInterfaceName = (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3239
0
    CK_VERSION KEMInterfaceVersion = { 1, 0 };
3240
0
    CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL;
3241
3242
0
    CK_RV crv;
3243
3244
0
    *outKey = NULL;
3245
3246
0
    CK_MECHANISM_TYPE kemType;
3247
0
    CK_NSS_KEM_PARAMETER_SET_TYPE kemParameterSet = PK11_ReadULongAttribute(slot, privKey->pkcs11ID, CKA_NSS_PARAMETER_SET);
3248
0
    switch (kemParameterSet) {
3249
0
        case CKP_NSS_KYBER_768_ROUND3:
3250
0
            kemType = CKM_NSS_KYBER;
3251
0
            break;
3252
0
        case CKP_NSS_ML_KEM_768:
3253
0
            kemType = CKM_NSS_ML_KEM;
3254
0
            break;
3255
0
        default:
3256
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
3257
0
            return SECFailure;
3258
0
    }
3259
0
    CK_MECHANISM mech = { kemType, &kemParameterSet, sizeof(kemParameterSet) };
3260
3261
0
    sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE, PR_TRUE, NULL);
3262
0
    if (sharedSecret == NULL) {
3263
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
3264
0
        return SECFailure;
3265
0
    }
3266
0
    sharedSecret->origin = PK11_OriginUnwrap;
3267
3268
0
    attrs = keyTemplate;
3269
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
3270
0
    attrs++;
3271
3272
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
3273
0
    attrs++;
3274
3275
0
    attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3276
0
    attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3277
3278
0
    templateCount = attrs - keyTemplate;
3279
0
    PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE));
3280
3281
0
    crv = PK11_GETTAB(slot)->C_GetInterface(KEMInterfaceName, &KEMInterfaceVersion, &KEMInterface, 0);
3282
0
    if (crv != CKR_OK) {
3283
0
        PORT_SetError(PK11_MapError(crv));
3284
0
        goto error;
3285
0
    }
3286
0
    KEMInterfaceFunctions = (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3287
3288
0
    pk11_EnterKeyMonitor(sharedSecret);
3289
0
    crv = KEMInterfaceFunctions->C_Decapsulate(sharedSecret->session,
3290
0
                                               &mech,
3291
0
                                               privKey->pkcs11ID,
3292
0
                                               ciphertext->data,
3293
0
                                               ciphertext->len,
3294
0
                                               keyTemplate,
3295
0
                                               templateCount,
3296
0
                                               &sharedSecret->objectID);
3297
0
    pk11_ExitKeyMonitor(sharedSecret);
3298
0
    if (crv != CKR_OK) {
3299
0
        goto error;
3300
0
    }
3301
3302
0
    *outKey = sharedSecret;
3303
0
    return SECSuccess;
3304
3305
0
error:
3306
0
    PK11_FreeSymKey(sharedSecret);
3307
0
    return SECFailure;
3308
0
}