Coverage Report

Created: 2025-06-24 06:49

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