Coverage Report

Created: 2025-11-05 06:16

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