Coverage Report

Created: 2026-11-15 06:55

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