Coverage Report

Created: 2024-05-20 06:23

/src/nss/lib/pk11wrap/pk11akey.c
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
/*
5
 * This file contains functions to manage asymetric keys, (public and
6
 * private keys).
7
 */
8
#include <stddef.h>
9
10
#include "seccomon.h"
11
#include "secmod.h"
12
#include "secmodi.h"
13
#include "secmodti.h"
14
#include "pkcs11.h"
15
#include "pkcs11t.h"
16
#include "pk11func.h"
17
#include "cert.h"
18
#include "keyhi.h"
19
#include "keyi.h"
20
#include "secitem.h"
21
#include "secasn1.h"
22
#include "secoid.h"
23
#include "secerr.h"
24
#include "sechash.h"
25
26
#include "secpkcs5.h"
27
#include "blapit.h"
28
29
static SECItem *
30
pk11_MakeIDFromPublicKey(SECKEYPublicKey *pubKey)
31
0
{
32
    /* set the ID to the public key so we can find it again */
33
0
    SECItem *pubKeyIndex = NULL;
34
0
    switch (pubKey->keyType) {
35
0
        case rsaKey:
36
0
            pubKeyIndex = &pubKey->u.rsa.modulus;
37
0
            break;
38
0
        case dsaKey:
39
0
            pubKeyIndex = &pubKey->u.dsa.publicValue;
40
0
            break;
41
0
        case dhKey:
42
0
            pubKeyIndex = &pubKey->u.dh.publicValue;
43
0
            break;
44
0
        case edKey:
45
0
        case ecKey:
46
0
            pubKeyIndex = &pubKey->u.ec.publicValue;
47
0
            break;
48
0
        case kyberKey:
49
0
            pubKeyIndex = &pubKey->u.kyber.publicValue;
50
0
            break;
51
0
        default:
52
0
            return NULL;
53
0
    }
54
0
    PORT_Assert(pubKeyIndex != NULL);
55
56
0
    return PK11_MakeIDFromPubKey(pubKeyIndex);
57
0
}
58
59
/*
60
 * import a public key into the desired slot
61
 *
62
 * This function takes a public key structure and creates a public key in a
63
 * given slot. If isToken is set, then a persistant public key is created.
64
 *
65
 * Note: it is possible for this function to return a handle for a key which
66
 * is persistant, even if isToken is not set.
67
 */
68
CK_OBJECT_HANDLE
69
PK11_ImportPublicKey(PK11SlotInfo *slot, SECKEYPublicKey *pubKey,
70
                     PRBool isToken)
71
0
{
72
0
    CK_BBOOL cktrue = CK_TRUE;
73
0
    CK_BBOOL ckfalse = CK_FALSE;
74
0
    CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
75
0
    CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
76
0
    CK_OBJECT_HANDLE objectID;
77
0
    CK_ATTRIBUTE theTemplate[11];
78
0
    CK_ATTRIBUTE *signedattr = NULL;
79
0
    CK_ATTRIBUTE *attrs = theTemplate;
80
0
    CK_NSS_KEM_PARAMETER_SET_TYPE kemParams;
81
0
    SECItem *ckaId = NULL;
82
0
    SECItem *pubValue = NULL;
83
0
    int signedcount = 0;
84
0
    unsigned int templateCount = 0;
85
0
    SECStatus rv;
86
87
    /* if we already have an object in the desired slot, use it */
88
0
    if (!isToken && pubKey->pkcs11Slot == slot) {
89
0
        return pubKey->pkcs11ID;
90
0
    }
91
92
    /* free the existing key */
93
0
    if (pubKey->pkcs11Slot != NULL) {
94
0
        PK11SlotInfo *oSlot = pubKey->pkcs11Slot;
95
0
        if (!PK11_IsPermObject(pubKey->pkcs11Slot, pubKey->pkcs11ID)) {
96
0
            PK11_EnterSlotMonitor(oSlot);
97
0
            (void)PK11_GETTAB(oSlot)->C_DestroyObject(oSlot->session,
98
0
                                                      pubKey->pkcs11ID);
99
0
            PK11_ExitSlotMonitor(oSlot);
100
0
        }
101
0
        PK11_FreeSlot(oSlot);
102
0
        pubKey->pkcs11Slot = NULL;
103
0
    }
104
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
105
0
    attrs++;
106
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
107
0
    attrs++;
108
0
    PK11_SETATTRS(attrs, CKA_TOKEN, isToken ? &cktrue : &ckfalse,
109
0
                  sizeof(CK_BBOOL));
110
0
    attrs++;
111
0
    if (isToken) {
112
0
        ckaId = pk11_MakeIDFromPublicKey(pubKey);
113
0
        if (ckaId == NULL) {
114
0
            PORT_SetError(SEC_ERROR_BAD_KEY);
115
0
            return CK_INVALID_HANDLE;
116
0
        }
117
0
        PK11_SETATTRS(attrs, CKA_ID, ckaId->data, ckaId->len);
118
0
        attrs++;
119
0
    }
120
121
    /* now import the key */
122
0
    {
123
0
        switch (pubKey->keyType) {
124
0
            case rsaKey:
125
0
                keyType = CKK_RSA;
126
0
                PK11_SETATTRS(attrs, CKA_WRAP, &cktrue, sizeof(CK_BBOOL));
127
0
                attrs++;
128
0
                PK11_SETATTRS(attrs, CKA_ENCRYPT, &cktrue,
129
0
                              sizeof(CK_BBOOL));
130
0
                attrs++;
131
0
                PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
132
0
                attrs++;
133
0
                signedattr = attrs;
134
0
                PK11_SETATTRS(attrs, CKA_MODULUS, pubKey->u.rsa.modulus.data,
135
0
                              pubKey->u.rsa.modulus.len);
136
0
                attrs++;
137
0
                PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
138
0
                              pubKey->u.rsa.publicExponent.data,
139
0
                              pubKey->u.rsa.publicExponent.len);
140
0
                attrs++;
141
0
                break;
142
0
            case dsaKey:
143
0
                keyType = CKK_DSA;
144
0
                PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
145
0
                attrs++;
146
0
                signedattr = attrs;
147
0
                PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dsa.params.prime.data,
148
0
                              pubKey->u.dsa.params.prime.len);
149
0
                attrs++;
150
0
                PK11_SETATTRS(attrs, CKA_SUBPRIME, pubKey->u.dsa.params.subPrime.data,
151
0
                              pubKey->u.dsa.params.subPrime.len);
152
0
                attrs++;
153
0
                PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dsa.params.base.data,
154
0
                              pubKey->u.dsa.params.base.len);
155
0
                attrs++;
156
0
                PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dsa.publicValue.data,
157
0
                              pubKey->u.dsa.publicValue.len);
158
0
                attrs++;
159
0
                break;
160
0
            case fortezzaKey:
161
0
                keyType = CKK_DSA;
162
0
                PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
163
0
                attrs++;
164
0
                signedattr = attrs;
165
0
                PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.fortezza.params.prime.data,
166
0
                              pubKey->u.fortezza.params.prime.len);
167
0
                attrs++;
168
0
                PK11_SETATTRS(attrs, CKA_SUBPRIME,
169
0
                              pubKey->u.fortezza.params.subPrime.data,
170
0
                              pubKey->u.fortezza.params.subPrime.len);
171
0
                attrs++;
172
0
                PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.fortezza.params.base.data,
173
0
                              pubKey->u.fortezza.params.base.len);
174
0
                attrs++;
175
0
                PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.fortezza.DSSKey.data,
176
0
                              pubKey->u.fortezza.DSSKey.len);
177
0
                attrs++;
178
0
                break;
179
0
            case dhKey:
180
0
                keyType = CKK_DH;
181
0
                PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));
182
0
                attrs++;
183
0
                signedattr = attrs;
184
0
                PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dh.prime.data,
185
0
                              pubKey->u.dh.prime.len);
186
0
                attrs++;
187
0
                PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dh.base.data,
188
0
                              pubKey->u.dh.base.len);
189
0
                attrs++;
190
0
                PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dh.publicValue.data,
191
0
                              pubKey->u.dh.publicValue.len);
192
0
                attrs++;
193
0
                break;
194
0
            case edKey:
195
0
                keyType = CKK_EC_EDWARDS;
196
0
                PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
197
0
                attrs++;
198
0
                PK11_SETATTRS(attrs, CKA_EC_PARAMS,
199
0
                              pubKey->u.ec.DEREncodedParams.data,
200
0
                              pubKey->u.ec.DEREncodedParams.len);
201
0
                attrs++;
202
0
                PK11_SETATTRS(attrs, CKA_EC_POINT,
203
0
                              pubKey->u.ec.publicValue.data,
204
0
                              pubKey->u.ec.publicValue.len);
205
0
                attrs++;
206
0
                break;
207
0
            case ecKey:
208
0
                keyType = CKK_EC;
209
0
                PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
210
0
                attrs++;
211
0
                PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));
212
0
                attrs++;
213
0
                PK11_SETATTRS(attrs, CKA_EC_PARAMS,
214
0
                              pubKey->u.ec.DEREncodedParams.data,
215
0
                              pubKey->u.ec.DEREncodedParams.len);
216
0
                attrs++;
217
0
                if (PR_GetEnvSecure("NSS_USE_DECODED_CKA_EC_POINT")) {
218
0
                    PK11_SETATTRS(attrs, CKA_EC_POINT,
219
0
                                  pubKey->u.ec.publicValue.data,
220
0
                                  pubKey->u.ec.publicValue.len);
221
0
                    attrs++;
222
0
                } else {
223
0
                    pubValue = SEC_ASN1EncodeItem(NULL, NULL,
224
0
                                                  &pubKey->u.ec.publicValue,
225
0
                                                  SEC_ASN1_GET(SEC_OctetStringTemplate));
226
0
                    if (pubValue == NULL) {
227
0
                        if (ckaId) {
228
0
                            SECITEM_FreeItem(ckaId, PR_TRUE);
229
0
                        }
230
0
                        return CK_INVALID_HANDLE;
231
0
                    }
232
0
                    PK11_SETATTRS(attrs, CKA_EC_POINT,
233
0
                                  pubValue->data, pubValue->len);
234
0
                    attrs++;
235
0
                }
236
0
                break;
237
0
            case kyberKey:
238
0
                keyType = CKK_NSS_KYBER;
239
0
                switch (pubKey->u.kyber.params) {
240
0
                    case params_kyber768_round3:
241
0
                    case params_kyber768_round3_test_mode:
242
0
                        kemParams = CKP_NSS_KYBER_768_ROUND3;
243
0
                        break;
244
0
                    default:
245
0
                        kemParams = CKP_INVALID_ID;
246
0
                        break;
247
0
                }
248
0
                PK11_SETATTRS(attrs, CKA_NSS_PARAMETER_SET,
249
0
                              &kemParams,
250
0
                              sizeof(CK_NSS_KEM_PARAMETER_SET_TYPE));
251
0
                attrs++;
252
0
                PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.kyber.publicValue.data,
253
0
                              pubKey->u.kyber.publicValue.len);
254
0
                attrs++;
255
0
                break;
256
0
            default:
257
0
                if (ckaId) {
258
0
                    SECITEM_FreeItem(ckaId, PR_TRUE);
259
0
                }
260
0
                PORT_SetError(SEC_ERROR_BAD_KEY);
261
0
                return CK_INVALID_HANDLE;
262
0
        }
263
0
        templateCount = attrs - theTemplate;
264
0
        PORT_Assert(templateCount <= (sizeof(theTemplate) / sizeof(CK_ATTRIBUTE)));
265
0
        if (pubKey->keyType != ecKey && pubKey->keyType != kyberKey && pubKey->keyType != edKey) {
266
0
            PORT_Assert(signedattr);
267
0
            signedcount = attrs - signedattr;
268
0
            for (attrs = signedattr; signedcount; attrs++, signedcount--) {
269
0
                pk11_SignedToUnsigned(attrs);
270
0
            }
271
0
        }
272
0
        rv = PK11_CreateNewObject(slot, CK_INVALID_HANDLE, theTemplate,
273
0
                                  templateCount, isToken, &objectID);
274
0
        if (ckaId) {
275
0
            SECITEM_FreeItem(ckaId, PR_TRUE);
276
0
        }
277
0
        if (pubValue) {
278
0
            SECITEM_FreeItem(pubValue, PR_TRUE);
279
0
        }
280
0
        if (rv != SECSuccess) {
281
0
            return CK_INVALID_HANDLE;
282
0
        }
283
0
    }
284
285
0
    pubKey->pkcs11ID = objectID;
286
0
    pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
287
288
0
    return objectID;
289
0
}
290
291
/*
292
 * take an attribute and copy it into a secitem
293
 */
294
static CK_RV
295
pk11_Attr2SecItem(PLArenaPool *arena, const CK_ATTRIBUTE *attr, SECItem *item)
296
0
{
297
0
    item->data = NULL;
298
299
0
    (void)SECITEM_AllocItem(arena, item, attr->ulValueLen);
300
0
    if (item->data == NULL) {
301
0
        return CKR_HOST_MEMORY;
302
0
    }
303
0
    PORT_Memcpy(item->data, attr->pValue, item->len);
304
0
    return CKR_OK;
305
0
}
306
307
/*
308
 * get a curve length from a set of ecParams.
309
 *
310
 * We need this so we can reliably determine if the ecPoint passed to us
311
 * was encoded or not. With out this, for many curves, we would incorrectly
312
 * identify an unencoded curve as an encoded curve 1 in 65536 times, and for
313
 * a few we would make that same mistake 1 in 32768 times. These are bad
314
 * numbers since they are rare enough to pass tests, but common enough to
315
 * be tripped over in the field.
316
 *
317
 * This function will only work for curves we recognized as of March 2009.
318
 * The assumption is curves in use after March of 2009 would be supplied by
319
 * PKCS #11 modules that already pass the correct encoding to us.
320
 *
321
 * Point length = (Roundup(curveLenInBits/8)*2+1)
322
 */
323
static int
324
pk11_get_EC_PointLenInBytes(PLArenaPool *arena, const SECItem *ecParams,
325
                            PRBool *plain)
326
0
{
327
0
    SECItem oid;
328
0
    SECOidTag tag;
329
0
    SECStatus rv;
330
331
    /* decode the OID tag */
332
0
    rv = SEC_QuickDERDecodeItem(arena, &oid,
333
0
                                SEC_ASN1_GET(SEC_ObjectIDTemplate), ecParams);
334
0
    if (rv != SECSuccess) {
335
        /* could be explict curves, allow them to work if the
336
         * PKCS #11 module support them. If we try to parse the
337
         * explicit curve value in the future, we may return -1 here
338
         * to indicate an invalid parameter if the explicit curve
339
         * decode fails. */
340
0
        return 0;
341
0
    }
342
343
0
    *plain = PR_FALSE;
344
0
    tag = SECOID_FindOIDTag(&oid);
345
0
    switch (tag) {
346
0
        case SEC_OID_SECG_EC_SECP112R1:
347
0
        case SEC_OID_SECG_EC_SECP112R2:
348
0
            return 29; /* curve len in bytes = 14 bytes */
349
0
        case SEC_OID_SECG_EC_SECT113R1:
350
0
        case SEC_OID_SECG_EC_SECT113R2:
351
0
            return 31; /* curve len in bytes = 15 bytes */
352
0
        case SEC_OID_SECG_EC_SECP128R1:
353
0
        case SEC_OID_SECG_EC_SECP128R2:
354
0
            return 33; /* curve len in bytes = 16 bytes */
355
0
        case SEC_OID_SECG_EC_SECT131R1:
356
0
        case SEC_OID_SECG_EC_SECT131R2:
357
0
            return 35; /* curve len in bytes = 17 bytes */
358
0
        case SEC_OID_SECG_EC_SECP160K1:
359
0
        case SEC_OID_SECG_EC_SECP160R1:
360
0
        case SEC_OID_SECG_EC_SECP160R2:
361
0
            return 41; /* curve len in bytes = 20 bytes */
362
0
        case SEC_OID_SECG_EC_SECT163K1:
363
0
        case SEC_OID_SECG_EC_SECT163R1:
364
0
        case SEC_OID_SECG_EC_SECT163R2:
365
0
        case SEC_OID_ANSIX962_EC_C2PNB163V1:
366
0
        case SEC_OID_ANSIX962_EC_C2PNB163V2:
367
0
        case SEC_OID_ANSIX962_EC_C2PNB163V3:
368
0
            return 43; /* curve len in bytes = 21 bytes */
369
0
        case SEC_OID_ANSIX962_EC_C2PNB176V1:
370
0
            return 45; /* curve len in bytes = 22 bytes */
371
0
        case SEC_OID_ANSIX962_EC_C2TNB191V1:
372
0
        case SEC_OID_ANSIX962_EC_C2TNB191V2:
373
0
        case SEC_OID_ANSIX962_EC_C2TNB191V3:
374
0
        case SEC_OID_SECG_EC_SECP192K1:
375
0
        case SEC_OID_ANSIX962_EC_PRIME192V1:
376
0
        case SEC_OID_ANSIX962_EC_PRIME192V2:
377
0
        case SEC_OID_ANSIX962_EC_PRIME192V3:
378
0
            return 49; /*curve len in bytes = 24 bytes */
379
0
        case SEC_OID_SECG_EC_SECT193R1:
380
0
        case SEC_OID_SECG_EC_SECT193R2:
381
0
            return 51; /*curve len in bytes = 25 bytes */
382
0
        case SEC_OID_ANSIX962_EC_C2PNB208W1:
383
0
            return 53; /*curve len in bytes = 26 bytes */
384
0
        case SEC_OID_SECG_EC_SECP224K1:
385
0
        case SEC_OID_SECG_EC_SECP224R1:
386
0
            return 57; /*curve len in bytes = 28 bytes */
387
0
        case SEC_OID_SECG_EC_SECT233K1:
388
0
        case SEC_OID_SECG_EC_SECT233R1:
389
0
        case SEC_OID_SECG_EC_SECT239K1:
390
0
        case SEC_OID_ANSIX962_EC_PRIME239V1:
391
0
        case SEC_OID_ANSIX962_EC_PRIME239V2:
392
0
        case SEC_OID_ANSIX962_EC_PRIME239V3:
393
0
        case SEC_OID_ANSIX962_EC_C2TNB239V1:
394
0
        case SEC_OID_ANSIX962_EC_C2TNB239V2:
395
0
        case SEC_OID_ANSIX962_EC_C2TNB239V3:
396
0
            return 61; /*curve len in bytes = 30 bytes */
397
0
        case SEC_OID_ANSIX962_EC_PRIME256V1:
398
0
        case SEC_OID_SECG_EC_SECP256K1:
399
0
            return 65; /*curve len in bytes = 32 bytes */
400
0
        case SEC_OID_ANSIX962_EC_C2PNB272W1:
401
0
            return 69; /*curve len in bytes = 34 bytes */
402
0
        case SEC_OID_SECG_EC_SECT283K1:
403
0
        case SEC_OID_SECG_EC_SECT283R1:
404
0
            return 73; /*curve len in bytes = 36 bytes */
405
0
        case SEC_OID_ANSIX962_EC_C2PNB304W1:
406
0
            return 77; /*curve len in bytes = 38 bytes */
407
0
        case SEC_OID_ANSIX962_EC_C2TNB359V1:
408
0
            return 91; /*curve len in bytes = 45 bytes */
409
0
        case SEC_OID_ANSIX962_EC_C2PNB368W1:
410
0
            return 93; /*curve len in bytes = 46 bytes */
411
0
        case SEC_OID_SECG_EC_SECP384R1:
412
0
            return 97; /*curve len in bytes = 48 bytes */
413
0
        case SEC_OID_SECG_EC_SECT409K1:
414
0
        case SEC_OID_SECG_EC_SECT409R1:
415
0
            return 105; /*curve len in bytes = 52 bytes */
416
0
        case SEC_OID_ANSIX962_EC_C2TNB431R1:
417
0
            return 109; /*curve len in bytes = 54 bytes */
418
0
        case SEC_OID_SECG_EC_SECP521R1:
419
0
            return 133; /*curve len in bytes = 66 bytes */
420
0
        case SEC_OID_SECG_EC_SECT571K1:
421
0
        case SEC_OID_SECG_EC_SECT571R1:
422
0
            return 145; /*curve len in bytes = 72 bytes */
423
0
        case SEC_OID_CURVE25519:
424
0
        case SEC_OID_ED25519_PUBLIC_KEY:
425
0
            *plain = PR_TRUE;
426
0
            return 32; /* curve len in bytes = 32 bytes (only X) */
427
        /* unknown or unrecognized OIDs. return unknown length */
428
0
        default:
429
0
            break;
430
0
    }
431
0
    return 0;
432
0
}
433
434
/*
435
 * returns the decoded point. In some cases the point may already be decoded.
436
 * this function tries to detect those cases and return the point in
437
 * publicKeyValue. In other cases it's DER encoded. In those cases the point
438
 * is first decoded and returned. Space for the point is allocated out of
439
 * the passed in arena.
440
 */
441
static CK_RV
442
pk11_get_Decoded_ECPoint(PLArenaPool *arena, const SECItem *ecParams,
443
                         const CK_ATTRIBUTE *ecPoint, SECItem *publicKeyValue)
444
0
{
445
0
    SECItem encodedPublicValue;
446
0
    SECStatus rv;
447
0
    int keyLen;
448
0
    PRBool plain = PR_FALSE;
449
450
0
    if (ecPoint->ulValueLen == 0) {
451
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
452
0
    }
453
454
    /*
455
     * The PKCS #11 spec requires ecPoints to be encoded as a DER OCTET String.
456
     * NSS has mistakenly passed unencoded values, and some PKCS #11 vendors
457
     * followed that mistake. Now we need to detect which encoding we were
458
     * passed in. The task is made more complicated by the fact the the
459
     * DER encoding byte (SEC_ASN_OCTET_STRING) is the same as the
460
     * EC_POINT_FORM_UNCOMPRESSED byte (0x04), so we can't use that to
461
     * determine which curve we are using.
462
     */
463
464
    /* get the expected key length for the passed in curve.
465
     * pk11_get_EC_PointLenInBytes only returns valid values for curves
466
     * NSS has traditionally recognized. If the curve is not recognized,
467
     * it will return '0', and we have to figure out if the key was
468
     * encoded or not heuristically. If the ecParams are invalid, it
469
     * will return -1 for the keyLen.
470
     */
471
0
    keyLen = pk11_get_EC_PointLenInBytes(arena, ecParams, &plain);
472
0
    if (keyLen < 0) {
473
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
474
0
    }
475
476
    /*
477
     * Some curves are not encoded but we don't have the name here.
478
     * Instead, pk11_get_EC_PointLenInBytes returns true plain if this is the
479
     * case.
480
     */
481
0
    if (plain && ecPoint->ulValueLen == (unsigned int)keyLen) {
482
0
        return pk11_Attr2SecItem(arena, ecPoint, publicKeyValue);
483
0
    }
484
485
    /* If the point is uncompressed and the lengths match, it
486
     * must be an unencoded point */
487
0
    if ((*((char *)ecPoint->pValue) == EC_POINT_FORM_UNCOMPRESSED) &&
488
0
        (ecPoint->ulValueLen == (unsigned int)keyLen)) {
489
0
        return pk11_Attr2SecItem(arena, ecPoint, publicKeyValue);
490
0
    }
491
492
    /* now assume the key passed to us was encoded and decode it */
493
0
    if (*((char *)ecPoint->pValue) == SEC_ASN1_OCTET_STRING) {
494
        /* OK, now let's try to decode it and see if it's valid */
495
0
        encodedPublicValue.data = ecPoint->pValue;
496
0
        encodedPublicValue.len = ecPoint->ulValueLen;
497
0
        rv = SEC_QuickDERDecodeItem(arena, publicKeyValue,
498
0
                                    SEC_ASN1_GET(SEC_OctetStringTemplate), &encodedPublicValue);
499
500
        /* it coded correctly & we know the key length (and they match)
501
         * then we are done, return the results. */
502
0
        if (keyLen && rv == SECSuccess && publicKeyValue->len == (unsigned int)keyLen) {
503
0
            return CKR_OK;
504
0
        }
505
506
        /* if we know the key length, one of the above tests should have
507
         * succeded. If it doesn't the module gave us bad data */
508
0
        if (keyLen) {
509
0
            return CKR_ATTRIBUTE_VALUE_INVALID;
510
0
        }
511
512
        /* We don't know the key length, so we don't know deterministically
513
         * which encoding was used. We now will try to pick the most likely
514
         * form that's correct, with a preference for the encoded form if we
515
         * can't determine for sure. We do this by checking the key we got
516
         * back from SEC_QuickDERDecodeItem for defects. If no defects are
517
         * found, we assume the encoded parameter was was passed to us.
518
         * our defect tests include:
519
         *   1) it didn't decode.
520
         *   2) The decode key had an invalid length (must be odd).
521
         *   3) The decoded key wasn't an UNCOMPRESSED key.
522
         *   4) The decoded key didn't include the entire encoded block
523
         *   except the DER encoding values. (fixing DER length to one
524
         *   particular value).
525
         */
526
0
        if ((rv != SECSuccess) || ((publicKeyValue->len & 1) != 1) ||
527
0
            (publicKeyValue->data[0] != EC_POINT_FORM_UNCOMPRESSED) ||
528
0
            (PORT_Memcmp(&encodedPublicValue.data[encodedPublicValue.len - publicKeyValue->len],
529
0
                         publicKeyValue->data,
530
0
                         publicKeyValue->len) != 0)) {
531
            /* The decoded public key was flawed, the original key must have
532
             * already been in decoded form. Do a quick sanity check then
533
             * return the original key value.
534
             */
535
0
            if ((encodedPublicValue.len & 1) == 0) {
536
0
                return CKR_ATTRIBUTE_VALUE_INVALID;
537
0
            }
538
0
            return pk11_Attr2SecItem(arena, ecPoint, publicKeyValue);
539
0
        }
540
541
        /* as best we can figure, the passed in key was encoded, and we've
542
         * now decoded it. Note: there is a chance this could be wrong if the
543
         * following conditions hold:
544
         *  1) The first byte or bytes of the X point looks like a valid length
545
         * of precisely the right size (2*curveSize -1). this means for curves
546
         * less than 512 bits (64 bytes), this will happen 1 in 256 times*.
547
         * for curves between 512 and 1024, this will happen 1 in 65,536 times*
548
         * for curves between 1024 and 256K this will happen 1 in 16 million*
549
         *  2) The length of the 'DER length field' is odd
550
         * (making both the encoded and decode
551
         * values an odd length. this is true of all curves less than 512,
552
         * as well as curves between 1024 and 256K).
553
         *  3) The X[length of the 'DER length field'] == 0x04, 1 in 256.
554
         *
555
         *  (* assuming all values are equally likely in the first byte,
556
         * This isn't true if the curve length is not a multiple of 8. In these
557
         * cases, if the DER length is possible, it's more likely,
558
         * if it's not possible, then we have no false decodes).
559
         *
560
         * For reference here are the odds for the various curves we currently
561
         * have support for (and the only curves SSL will negotiate at this
562
         * time). NOTE: None of the supported curves will show up here
563
         * because we return a valid length for all of these curves.
564
         * The only way to get here is to have some application (not SSL)
565
         * which supports some unknown curve and have some vendor supplied
566
         * PKCS #11 module support that curve. NOTE: in this case, one
567
         * presumes that that pkcs #11 module is likely to be using the
568
         * correct encodings.
569
         *
570
         * Prime Curves (GFp):
571
         *   Bit    False       Odds of
572
         *  Size    DER Len  False Decode Positive
573
         *  112     27     1 in 65536
574
         *  128     31     1 in 65536
575
         *  160     39     1 in 65536
576
         *  192     47     1 in 65536
577
         *  224     55     1 in 65536
578
         *  239     59     1 in 32768 (top byte can only be 0-127)
579
         *  256     63     1 in 65536
580
         *  521     129,131      0        (decoded value would be even)
581
         *
582
         * Binary curves (GF2m).
583
         *   Bit    False       Odds of
584
         *  Size    DER Len  False Decode Positive
585
         *  131     33       0        (top byte can only be 0-7)
586
         *  163     41       0        (top byte can only be 0-7)
587
         *  176     43     1 in 65536
588
         *  191     47     1 in 32768 (top byte can only be 0-127)
589
         *  193     49       0        (top byte can only be 0-1)
590
         *  208     51     1 in 65536
591
         *  233     59       0        (top byte can only be 0-1)
592
         *  239     59     1 in 32768 (top byte can only be 0-127)
593
         *  272     67     1 in 65536
594
         *  283     71       0        (top byte can only be 0-7)
595
         *  304     75     1 in 65536
596
         *  359     89     1 in 32768 (top byte can only be 0-127)
597
         *  368     91     1 in 65536
598
         *  409     103      0        (top byte can only be 0-1)
599
         *  431     107    1 in 32768 (top byte can only be 0-127)
600
         *  571     129,143      0        (decoded value would be even)
601
         *
602
         */
603
604
0
        return CKR_OK;
605
0
    }
606
607
    /* In theory, we should handle the case where the curve == 0 and
608
     * the first byte is EC_POINT_FORM_UNCOMPRESSED, (which would be
609
     * handled by doing a santity check on the key length and returning
610
     * pk11_Attr2SecItem() to copy the ecPoint to the publicKeyValue).
611
     *
612
     * This test is unnecessary, however, due to the fact that
613
     * EC_POINT_FORM_UNCOMPRESSED == SEC_ASIN1_OCTET_STRING, that case is
614
     * handled in the above if. That means if we get here, the initial
615
     * byte of our ecPoint value was invalid, so we can safely return.
616
     * invalid attribute.
617
     */
618
619
0
    return CKR_ATTRIBUTE_VALUE_INVALID;
620
0
}
621
622
/*
623
 * extract a public key from a slot and id
624
 */
625
SECKEYPublicKey *
626
PK11_ExtractPublicKey(PK11SlotInfo *slot, KeyType keyType, CK_OBJECT_HANDLE id)
627
0
{
628
0
    CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
629
0
    PLArenaPool *arena;
630
0
    PLArenaPool *tmp_arena;
631
0
    SECKEYPublicKey *pubKey;
632
0
    unsigned int templateCount = 0;
633
0
    CK_KEY_TYPE pk11KeyType;
634
0
    CK_RV crv;
635
0
    CK_ATTRIBUTE template[8];
636
0
    CK_ATTRIBUTE *attrs = template;
637
0
    CK_ATTRIBUTE *modulus, *exponent, *base, *prime, *subprime, *value;
638
0
    CK_ATTRIBUTE *ecparams, *kemParams;
639
640
    /* if we didn't know the key type, get it */
641
0
    if (keyType == nullKey) {
642
643
0
        pk11KeyType = PK11_ReadULongAttribute(slot, id, CKA_KEY_TYPE);
644
0
        if (pk11KeyType == CK_UNAVAILABLE_INFORMATION) {
645
0
            return NULL;
646
0
        }
647
0
        switch (pk11KeyType) {
648
0
            case CKK_RSA:
649
0
                keyType = rsaKey;
650
0
                break;
651
0
            case CKK_DSA:
652
0
                keyType = dsaKey;
653
0
                break;
654
0
            case CKK_DH:
655
0
                keyType = dhKey;
656
0
                break;
657
0
            case CKK_EC:
658
0
                keyType = ecKey;
659
0
                break;
660
0
            case CKK_EC_EDWARDS:
661
0
                keyType = edKey;
662
0
                break;
663
0
            case CKK_NSS_KYBER:
664
0
                keyType = kyberKey;
665
0
                break;
666
0
            default:
667
0
                PORT_SetError(SEC_ERROR_BAD_KEY);
668
0
                return NULL;
669
0
        }
670
0
    }
671
672
    /* now we need to create space for the public key */
673
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
674
0
    if (arena == NULL)
675
0
        return NULL;
676
0
    tmp_arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
677
0
    if (tmp_arena == NULL) {
678
0
        PORT_FreeArena(arena, PR_FALSE);
679
0
        return NULL;
680
0
    }
681
682
0
    pubKey = (SECKEYPublicKey *)
683
0
        PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
684
0
    if (pubKey == NULL) {
685
0
        PORT_FreeArena(arena, PR_FALSE);
686
0
        PORT_FreeArena(tmp_arena, PR_FALSE);
687
0
        return NULL;
688
0
    }
689
690
0
    pubKey->arena = arena;
691
0
    pubKey->keyType = keyType;
692
0
    pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
693
0
    pubKey->pkcs11ID = id;
694
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass,
695
0
                  sizeof(keyClass));
696
0
    attrs++;
697
0
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &pk11KeyType,
698
0
                  sizeof(pk11KeyType));
699
0
    attrs++;
700
0
    switch (pubKey->keyType) {
701
0
        case rsaKey:
702
0
            modulus = attrs;
703
0
            PK11_SETATTRS(attrs, CKA_MODULUS, NULL, 0);
704
0
            attrs++;
705
0
            exponent = attrs;
706
0
            PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, NULL, 0);
707
0
            attrs++;
708
709
0
            templateCount = attrs - template;
710
0
            PR_ASSERT(templateCount <= sizeof(template) / sizeof(CK_ATTRIBUTE));
711
0
            crv = PK11_GetAttributes(tmp_arena, slot, id, template, templateCount);
712
0
            if (crv != CKR_OK)
713
0
                break;
714
715
0
            if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_RSA)) {
716
0
                crv = CKR_OBJECT_HANDLE_INVALID;
717
0
                break;
718
0
            }
719
0
            crv = pk11_Attr2SecItem(arena, modulus, &pubKey->u.rsa.modulus);
720
0
            if (crv != CKR_OK)
721
0
                break;
722
0
            crv = pk11_Attr2SecItem(arena, exponent, &pubKey->u.rsa.publicExponent);
723
0
            if (crv != CKR_OK)
724
0
                break;
725
0
            break;
726
0
        case dsaKey:
727
0
            prime = attrs;
728
0
            PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0);
729
0
            attrs++;
730
0
            subprime = attrs;
731
0
            PK11_SETATTRS(attrs, CKA_SUBPRIME, NULL, 0);
732
0
            attrs++;
733
0
            base = attrs;
734
0
            PK11_SETATTRS(attrs, CKA_BASE, NULL, 0);
735
0
            attrs++;
736
0
            value = attrs;
737
0
            PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0);
738
0
            attrs++;
739
0
            templateCount = attrs - template;
740
0
            PR_ASSERT(templateCount <= sizeof(template) / sizeof(CK_ATTRIBUTE));
741
0
            crv = PK11_GetAttributes(tmp_arena, slot, id, template, templateCount);
742
0
            if (crv != CKR_OK)
743
0
                break;
744
745
0
            if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DSA)) {
746
0
                crv = CKR_OBJECT_HANDLE_INVALID;
747
0
                break;
748
0
            }
749
0
            crv = pk11_Attr2SecItem(arena, prime, &pubKey->u.dsa.params.prime);
750
0
            if (crv != CKR_OK)
751
0
                break;
752
0
            crv = pk11_Attr2SecItem(arena, subprime, &pubKey->u.dsa.params.subPrime);
753
0
            if (crv != CKR_OK)
754
0
                break;
755
0
            crv = pk11_Attr2SecItem(arena, base, &pubKey->u.dsa.params.base);
756
0
            if (crv != CKR_OK)
757
0
                break;
758
0
            crv = pk11_Attr2SecItem(arena, value, &pubKey->u.dsa.publicValue);
759
0
            if (crv != CKR_OK)
760
0
                break;
761
0
            break;
762
0
        case dhKey:
763
0
            prime = attrs;
764
0
            PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0);
765
0
            attrs++;
766
0
            base = attrs;
767
0
            PK11_SETATTRS(attrs, CKA_BASE, NULL, 0);
768
0
            attrs++;
769
0
            value = attrs;
770
0
            PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0);
771
0
            attrs++;
772
0
            templateCount = attrs - template;
773
0
            PR_ASSERT(templateCount <= sizeof(template) / sizeof(CK_ATTRIBUTE));
774
0
            crv = PK11_GetAttributes(tmp_arena, slot, id, template, templateCount);
775
0
            if (crv != CKR_OK)
776
0
                break;
777
778
0
            if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DH)) {
779
0
                crv = CKR_OBJECT_HANDLE_INVALID;
780
0
                break;
781
0
            }
782
0
            crv = pk11_Attr2SecItem(arena, prime, &pubKey->u.dh.prime);
783
0
            if (crv != CKR_OK)
784
0
                break;
785
0
            crv = pk11_Attr2SecItem(arena, base, &pubKey->u.dh.base);
786
0
            if (crv != CKR_OK)
787
0
                break;
788
0
            crv = pk11_Attr2SecItem(arena, value, &pubKey->u.dh.publicValue);
789
0
            if (crv != CKR_OK)
790
0
                break;
791
0
            break;
792
0
        case edKey:
793
0
        case ecKey:
794
0
            pubKey->u.ec.size = 0;
795
0
            ecparams = attrs;
796
0
            PK11_SETATTRS(attrs, CKA_EC_PARAMS, NULL, 0);
797
0
            attrs++;
798
0
            value = attrs;
799
0
            PK11_SETATTRS(attrs, CKA_EC_POINT, NULL, 0);
800
0
            attrs++;
801
0
            templateCount = attrs - template;
802
0
            PR_ASSERT(templateCount <= sizeof(template) / sizeof(CK_ATTRIBUTE));
803
0
            crv = PK11_GetAttributes(arena, slot, id, template, templateCount);
804
0
            if (crv != CKR_OK)
805
0
                break;
806
807
0
            if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_EC && pk11KeyType != CKK_EC_EDWARDS)) {
808
0
                crv = CKR_OBJECT_HANDLE_INVALID;
809
0
                break;
810
0
            }
811
812
0
            crv = pk11_Attr2SecItem(arena, ecparams,
813
0
                                    &pubKey->u.ec.DEREncodedParams);
814
0
            if (crv != CKR_OK)
815
0
                break;
816
0
            pubKey->u.ec.encoding = ECPoint_Undefined;
817
0
            crv = pk11_get_Decoded_ECPoint(arena,
818
0
                                           &pubKey->u.ec.DEREncodedParams, value,
819
0
                                           &pubKey->u.ec.publicValue);
820
0
            break;
821
0
        case kyberKey:
822
0
            value = attrs;
823
0
            PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0);
824
0
            attrs++;
825
0
            kemParams = attrs;
826
0
            PK11_SETATTRS(attrs, CKA_NSS_PARAMETER_SET, NULL, 0);
827
0
            attrs++;
828
0
            templateCount = attrs - template;
829
0
            PR_ASSERT(templateCount <= sizeof(template) / sizeof(CK_ATTRIBUTE));
830
831
0
            crv = PK11_GetAttributes(arena, slot, id, template, templateCount);
832
0
            if (crv != CKR_OK)
833
0
                break;
834
835
0
            if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_NSS_KYBER)) {
836
0
                crv = CKR_OBJECT_HANDLE_INVALID;
837
0
                break;
838
0
            }
839
840
0
            if (kemParams->ulValueLen != sizeof(CK_NSS_KEM_PARAMETER_SET_TYPE)) {
841
0
                crv = CKR_OBJECT_HANDLE_INVALID;
842
0
                break;
843
0
            }
844
0
            CK_NSS_KEM_PARAMETER_SET_TYPE *pPK11Params = kemParams->pValue;
845
0
            switch (*pPK11Params) {
846
0
                case CKP_NSS_KYBER_768_ROUND3:
847
0
                    pubKey->u.kyber.params = params_kyber768_round3;
848
0
                    break;
849
0
                default:
850
0
                    pubKey->u.kyber.params = params_kyber_invalid;
851
0
                    break;
852
0
            }
853
0
            crv = pk11_Attr2SecItem(arena, value, &pubKey->u.kyber.publicValue);
854
0
            break;
855
0
        case fortezzaKey:
856
0
        case nullKey:
857
0
        default:
858
0
            crv = CKR_OBJECT_HANDLE_INVALID;
859
0
            break;
860
0
    }
861
862
0
    PORT_FreeArena(tmp_arena, PR_FALSE);
863
864
0
    if (crv != CKR_OK) {
865
0
        PORT_FreeArena(arena, PR_FALSE);
866
0
        PK11_FreeSlot(slot);
867
0
        PORT_SetError(PK11_MapError(crv));
868
0
        return NULL;
869
0
    }
870
871
0
    return pubKey;
872
0
}
873
874
/*
875
 * Build a Private Key structure from raw PKCS #11 information.
876
 */
877
SECKEYPrivateKey *
878
PK11_MakePrivKey(PK11SlotInfo *slot, KeyType keyType,
879
                 PRBool isTemp, CK_OBJECT_HANDLE privID, void *wincx)
880
0
{
881
0
    PLArenaPool *arena;
882
0
    SECKEYPrivateKey *privKey;
883
0
    PRBool isPrivate;
884
0
    SECStatus rv;
885
886
    /* don't know? look it up */
887
0
    if (keyType == nullKey) {
888
0
        CK_KEY_TYPE pk11Type = CKK_RSA;
889
890
0
        pk11Type = PK11_ReadULongAttribute(slot, privID, CKA_KEY_TYPE);
891
0
        isTemp = (PRBool)!PK11_HasAttributeSet(slot, privID, CKA_TOKEN, PR_FALSE);
892
0
        switch (pk11Type) {
893
0
            case CKK_RSA:
894
0
                keyType = rsaKey;
895
0
                break;
896
0
            case CKK_DSA:
897
0
                keyType = dsaKey;
898
0
                break;
899
0
            case CKK_DH:
900
0
                keyType = dhKey;
901
0
                break;
902
0
            case CKK_KEA:
903
0
                keyType = fortezzaKey;
904
0
                break;
905
0
            case CKK_EC:
906
0
                keyType = ecKey;
907
0
                break;
908
0
            case CKK_EC_EDWARDS:
909
0
                keyType = edKey;
910
0
                break;
911
0
            case CKK_NSS_KYBER:
912
0
                keyType = kyberKey;
913
0
                break;
914
0
            default:
915
0
                break;
916
0
        }
917
0
    }
918
919
    /* if the key is private, make sure we are authenticated to the
920
     * token before we try to use it */
921
0
    isPrivate = (PRBool)PK11_HasAttributeSet(slot, privID, CKA_PRIVATE, PR_FALSE);
922
0
    if (isPrivate) {
923
0
        rv = PK11_Authenticate(slot, PR_TRUE, wincx);
924
0
        if (rv != SECSuccess) {
925
0
            return NULL;
926
0
        }
927
0
    }
928
929
    /* now we need to create space for the private key */
930
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
931
0
    if (arena == NULL)
932
0
        return NULL;
933
934
0
    privKey = (SECKEYPrivateKey *)
935
0
        PORT_ArenaZAlloc(arena, sizeof(SECKEYPrivateKey));
936
0
    if (privKey == NULL) {
937
0
        PORT_FreeArena(arena, PR_FALSE);
938
0
        return NULL;
939
0
    }
940
941
0
    privKey->arena = arena;
942
0
    privKey->keyType = keyType;
943
0
    privKey->pkcs11Slot = PK11_ReferenceSlot(slot);
944
0
    privKey->pkcs11ID = privID;
945
0
    privKey->pkcs11IsTemp = isTemp;
946
0
    privKey->wincx = wincx;
947
948
0
    return privKey;
949
0
}
950
951
PK11SlotInfo *
952
PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key)
953
0
{
954
0
    PK11SlotInfo *slot = key->pkcs11Slot;
955
0
    slot = PK11_ReferenceSlot(slot);
956
0
    return slot;
957
0
}
958
959
/*
960
 * Get the modulus length for raw parsing
961
 */
962
int
963
PK11_GetPrivateModulusLen(SECKEYPrivateKey *key)
964
0
{
965
0
    CK_ATTRIBUTE theTemplate = { CKA_MODULUS, NULL, 0 };
966
0
    PK11SlotInfo *slot = key->pkcs11Slot;
967
0
    CK_RV crv;
968
0
    int length;
969
970
0
    switch (key->keyType) {
971
0
        case rsaKey:
972
0
            crv = PK11_GetAttributes(NULL, slot, key->pkcs11ID, &theTemplate, 1);
973
0
            if (crv != CKR_OK) {
974
0
                PORT_SetError(PK11_MapError(crv));
975
0
                return -1;
976
0
            }
977
0
            if (theTemplate.pValue == NULL) {
978
0
                PORT_SetError(PK11_MapError(CKR_ATTRIBUTE_VALUE_INVALID));
979
0
                return -1;
980
0
            }
981
0
            length = theTemplate.ulValueLen;
982
0
            if (*(unsigned char *)theTemplate.pValue == 0) {
983
0
                length--;
984
0
            }
985
0
            PORT_Free(theTemplate.pValue);
986
0
            return (int)length;
987
988
0
        case fortezzaKey:
989
0
        case dsaKey:
990
0
        case dhKey:
991
0
        default:
992
0
            break;
993
0
    }
994
0
    if (theTemplate.pValue != NULL)
995
0
        PORT_Free(theTemplate.pValue);
996
0
    PORT_SetError(SEC_ERROR_INVALID_KEY);
997
0
    return -1;
998
0
}
999
1000
/*
1001
 * take a private key in one pkcs11 module and load it into another:
1002
 *  NOTE: the source private key is a rare animal... it can't be sensitive.
1003
 *  This is used to do a key gen using one pkcs11 module and storing the
1004
 *  result into another.
1005
 */
1006
static SECKEYPrivateKey *
1007
pk11_loadPrivKeyWithFlags(PK11SlotInfo *slot, SECKEYPrivateKey *privKey,
1008
                          SECKEYPublicKey *pubKey, PK11AttrFlags attrFlags)
1009
0
{
1010
0
    CK_ATTRIBUTE privTemplate[] = {
1011
        /* class must be first */
1012
0
        { CKA_CLASS, NULL, 0 },
1013
0
        { CKA_KEY_TYPE, NULL, 0 },
1014
0
        { CKA_ID, NULL, 0 },
1015
        /* RSA - the attributes below will be replaced for other
1016
         *       key types.
1017
         */
1018
0
        { CKA_MODULUS, NULL, 0 },
1019
0
        { CKA_PRIVATE_EXPONENT, NULL, 0 },
1020
0
        { CKA_PUBLIC_EXPONENT, NULL, 0 },
1021
0
        { CKA_PRIME_1, NULL, 0 },
1022
0
        { CKA_PRIME_2, NULL, 0 },
1023
0
        { CKA_EXPONENT_1, NULL, 0 },
1024
0
        { CKA_EXPONENT_2, NULL, 0 },
1025
0
        { CKA_COEFFICIENT, NULL, 0 },
1026
0
        { CKA_DECRYPT, NULL, 0 },
1027
0
        { CKA_DERIVE, NULL, 0 },
1028
0
        { CKA_SIGN, NULL, 0 },
1029
0
        { CKA_SIGN_RECOVER, NULL, 0 },
1030
0
        { CKA_UNWRAP, NULL, 0 },
1031
        /* reserve space for the attributes that may be
1032
         * specified in attrFlags */
1033
0
        { CKA_TOKEN, NULL, 0 },
1034
0
        { CKA_PRIVATE, NULL, 0 },
1035
0
        { CKA_MODIFIABLE, NULL, 0 },
1036
0
        { CKA_SENSITIVE, NULL, 0 },
1037
0
        { CKA_EXTRACTABLE, NULL, 0 },
1038
0
#define NUM_RESERVED_ATTRS 5 /* number of reserved attributes above */
1039
0
    };
1040
0
    CK_BBOOL cktrue = CK_TRUE;
1041
0
    CK_BBOOL ckfalse = CK_FALSE;
1042
0
    CK_ATTRIBUTE *attrs = NULL, *ap;
1043
0
    const int templateSize = sizeof(privTemplate) / sizeof(privTemplate[0]);
1044
0
    PLArenaPool *arena;
1045
0
    CK_OBJECT_HANDLE objectID;
1046
0
    int i, count = 0;
1047
0
    int extra_count = 0;
1048
0
    CK_RV crv;
1049
0
    SECStatus rv;
1050
0
    PRBool token = ((attrFlags & PK11_ATTR_TOKEN) != 0);
1051
1052
0
    if (pk11_BadAttrFlags(attrFlags)) {
1053
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1054
0
        return NULL;
1055
0
    }
1056
1057
0
    for (i = 0; i < templateSize; i++) {
1058
0
        if (privTemplate[i].type == CKA_MODULUS) {
1059
0
            attrs = &privTemplate[i];
1060
0
            count = i;
1061
0
            break;
1062
0
        }
1063
0
    }
1064
0
    PORT_Assert(attrs != NULL);
1065
0
    if (attrs == NULL) {
1066
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1067
0
        return NULL;
1068
0
    }
1069
1070
0
    ap = attrs;
1071
1072
0
    switch (privKey->keyType) {
1073
0
        case rsaKey:
1074
0
            count = templateSize - NUM_RESERVED_ATTRS;
1075
0
            extra_count = count - (attrs - privTemplate);
1076
0
            break;
1077
0
        case dsaKey:
1078
0
            ap->type = CKA_PRIME;
1079
0
            ap++;
1080
0
            count++;
1081
0
            extra_count++;
1082
0
            ap->type = CKA_SUBPRIME;
1083
0
            ap++;
1084
0
            count++;
1085
0
            extra_count++;
1086
0
            ap->type = CKA_BASE;
1087
0
            ap++;
1088
0
            count++;
1089
0
            extra_count++;
1090
0
            ap->type = CKA_VALUE;
1091
0
            ap++;
1092
0
            count++;
1093
0
            extra_count++;
1094
0
            ap->type = CKA_SIGN;
1095
0
            ap++;
1096
0
            count++;
1097
0
            extra_count++;
1098
0
            break;
1099
0
        case dhKey:
1100
0
            ap->type = CKA_PRIME;
1101
0
            ap++;
1102
0
            count++;
1103
0
            extra_count++;
1104
0
            ap->type = CKA_BASE;
1105
0
            ap++;
1106
0
            count++;
1107
0
            extra_count++;
1108
0
            ap->type = CKA_VALUE;
1109
0
            ap++;
1110
0
            count++;
1111
0
            extra_count++;
1112
0
            ap->type = CKA_DERIVE;
1113
0
            ap++;
1114
0
            count++;
1115
0
            extra_count++;
1116
0
            break;
1117
0
        case ecKey:
1118
0
        case edKey:
1119
0
            ap->type = CKA_EC_PARAMS;
1120
0
            ap++;
1121
0
            count++;
1122
0
            extra_count++;
1123
0
            ap->type = CKA_VALUE;
1124
0
            ap++;
1125
0
            count++;
1126
0
            extra_count++;
1127
0
            if (privKey->keyType == ecKey) {
1128
0
                ap->type = CKA_DERIVE;
1129
0
                ap++;
1130
0
                count++;
1131
0
                extra_count++;
1132
0
            }
1133
1134
0
            ap->type = CKA_SIGN;
1135
0
            ap++;
1136
0
            count++;
1137
0
            extra_count++;
1138
0
            break;
1139
0
        default:
1140
0
            count = 0;
1141
0
            extra_count = 0;
1142
0
            break;
1143
0
    }
1144
1145
0
    if (count == 0) {
1146
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1147
0
        return NULL;
1148
0
    }
1149
1150
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1151
0
    if (arena == NULL)
1152
0
        return NULL;
1153
    /*
1154
      * read out the old attributes.
1155
      */
1156
0
    crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID,
1157
0
                             privTemplate, count);
1158
0
    if (crv != CKR_OK) {
1159
0
        PORT_SetError(PK11_MapError(crv));
1160
0
        PORT_FreeArena(arena, PR_TRUE);
1161
0
        return NULL;
1162
0
    }
1163
1164
    /* Set token, private, modifiable, sensitive, and extractable */
1165
0
    count += pk11_AttrFlagsToAttributes(attrFlags, &privTemplate[count],
1166
0
                                        &cktrue, &ckfalse);
1167
1168
    /* Not everyone can handle zero padded key values, give
1169
     * them the raw data as unsigned. The exception is EC,
1170
     * where the values are encoded or zero-preserving
1171
     * per-RFC5915 */
1172
0
    if (privKey->keyType != ecKey && privKey->keyType != edKey) {
1173
0
        for (ap = attrs; extra_count; ap++, extra_count--) {
1174
0
            pk11_SignedToUnsigned(ap);
1175
0
        }
1176
0
    }
1177
1178
    /* now Store the puppies */
1179
0
    rv = PK11_CreateNewObject(slot, CK_INVALID_HANDLE, privTemplate,
1180
0
                              count, token, &objectID);
1181
0
    PORT_FreeArena(arena, PR_TRUE);
1182
0
    if (rv != SECSuccess) {
1183
0
        return NULL;
1184
0
    }
1185
1186
    /* try loading the public key */
1187
0
    if (pubKey) {
1188
0
        PK11_ImportPublicKey(slot, pubKey, token);
1189
0
        if (pubKey->pkcs11Slot) {
1190
0
            PK11_FreeSlot(pubKey->pkcs11Slot);
1191
0
            pubKey->pkcs11Slot = NULL;
1192
0
            pubKey->pkcs11ID = CK_INVALID_HANDLE;
1193
0
        }
1194
0
    }
1195
1196
    /* build new key structure */
1197
0
    return PK11_MakePrivKey(slot, privKey->keyType, !token,
1198
0
                            objectID, privKey->wincx);
1199
0
}
1200
1201
static SECKEYPrivateKey *
1202
pk11_loadPrivKey(PK11SlotInfo *slot, SECKEYPrivateKey *privKey,
1203
                 SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive)
1204
0
{
1205
0
    PK11AttrFlags attrFlags = 0;
1206
0
    if (token) {
1207
0
        attrFlags |= (PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE);
1208
0
    } else {
1209
0
        attrFlags |= (PK11_ATTR_SESSION | PK11_ATTR_PUBLIC);
1210
0
    }
1211
0
    if (sensitive) {
1212
0
        attrFlags |= PK11_ATTR_SENSITIVE;
1213
0
    } else {
1214
0
        attrFlags |= PK11_ATTR_INSENSITIVE;
1215
0
    }
1216
0
    return pk11_loadPrivKeyWithFlags(slot, privKey, pubKey, attrFlags);
1217
0
}
1218
1219
/*
1220
 * export this for PSM
1221
 */
1222
SECKEYPrivateKey *
1223
PK11_LoadPrivKey(PK11SlotInfo *slot, SECKEYPrivateKey *privKey,
1224
                 SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive)
1225
0
{
1226
0
    return pk11_loadPrivKey(slot, privKey, pubKey, token, sensitive);
1227
0
}
1228
1229
/*
1230
 * Use the token to generate a key pair.
1231
 */
1232
SECKEYPrivateKey *
1233
PK11_GenerateKeyPairWithOpFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1234
                                void *param, SECKEYPublicKey **pubKey, PK11AttrFlags attrFlags,
1235
                                CK_FLAGS opFlags, CK_FLAGS opFlagsMask, void *wincx)
1236
0
{
1237
    /* we have to use these native types because when we call PKCS 11 modules
1238
     * we have to make sure that we are using the correct sizes for all the
1239
     * parameters. */
1240
0
    CK_BBOOL ckfalse = CK_FALSE;
1241
0
    CK_BBOOL cktrue = CK_TRUE;
1242
0
    CK_ULONG modulusBits;
1243
0
    CK_BYTE publicExponent[4];
1244
0
    CK_ATTRIBUTE privTemplate[] = {
1245
0
        { CKA_SENSITIVE, NULL, 0 },
1246
0
        { CKA_TOKEN, NULL, 0 },
1247
0
        { CKA_PRIVATE, NULL, 0 },
1248
0
        { CKA_DERIVE, NULL, 0 },
1249
0
        { CKA_UNWRAP, NULL, 0 },
1250
0
        { CKA_SIGN, NULL, 0 },
1251
0
        { CKA_DECRYPT, NULL, 0 },
1252
0
        { CKA_EXTRACTABLE, NULL, 0 },
1253
0
        { CKA_MODIFIABLE, NULL, 0 },
1254
0
    };
1255
0
    CK_ATTRIBUTE rsaPubTemplate[] = {
1256
0
        { CKA_MODULUS_BITS, NULL, 0 },
1257
0
        { CKA_PUBLIC_EXPONENT, NULL, 0 },
1258
0
        { CKA_TOKEN, NULL, 0 },
1259
0
        { CKA_DERIVE, NULL, 0 },
1260
0
        { CKA_WRAP, NULL, 0 },
1261
0
        { CKA_VERIFY, NULL, 0 },
1262
0
        { CKA_VERIFY_RECOVER, NULL, 0 },
1263
0
        { CKA_ENCRYPT, NULL, 0 },
1264
0
        { CKA_MODIFIABLE, NULL, 0 },
1265
0
    };
1266
0
    CK_ATTRIBUTE dsaPubTemplate[] = {
1267
0
        { CKA_PRIME, NULL, 0 },
1268
0
        { CKA_SUBPRIME, NULL, 0 },
1269
0
        { CKA_BASE, NULL, 0 },
1270
0
        { CKA_TOKEN, NULL, 0 },
1271
0
        { CKA_DERIVE, NULL, 0 },
1272
0
        { CKA_WRAP, NULL, 0 },
1273
0
        { CKA_VERIFY, NULL, 0 },
1274
0
        { CKA_VERIFY_RECOVER, NULL, 0 },
1275
0
        { CKA_ENCRYPT, NULL, 0 },
1276
0
        { CKA_MODIFIABLE, NULL, 0 },
1277
0
    };
1278
0
    CK_ATTRIBUTE dhPubTemplate[] = {
1279
0
        { CKA_PRIME, NULL, 0 },
1280
0
        { CKA_BASE, NULL, 0 },
1281
0
        { CKA_TOKEN, NULL, 0 },
1282
0
        { CKA_DERIVE, NULL, 0 },
1283
0
        { CKA_WRAP, NULL, 0 },
1284
0
        { CKA_VERIFY, NULL, 0 },
1285
0
        { CKA_VERIFY_RECOVER, NULL, 0 },
1286
0
        { CKA_ENCRYPT, NULL, 0 },
1287
0
        { CKA_MODIFIABLE, NULL, 0 },
1288
0
    };
1289
0
    CK_ATTRIBUTE ecPubTemplate[] = {
1290
0
        { CKA_EC_PARAMS, NULL, 0 },
1291
0
        { CKA_TOKEN, NULL, 0 },
1292
0
        { CKA_DERIVE, NULL, 0 },
1293
0
        { CKA_WRAP, NULL, 0 },
1294
0
        { CKA_VERIFY, NULL, 0 },
1295
0
        { CKA_VERIFY_RECOVER, NULL, 0 },
1296
0
        { CKA_ENCRYPT, NULL, 0 },
1297
0
        { CKA_MODIFIABLE, NULL, 0 },
1298
0
    };
1299
0
    SECKEYECParams *ecParams;
1300
1301
0
    CK_ATTRIBUTE kyberPubTemplate[] = {
1302
0
        { CKA_NSS_PARAMETER_SET, NULL, 0 },
1303
0
        { CKA_TOKEN, NULL, 0 },
1304
0
        { CKA_DERIVE, NULL, 0 },
1305
0
        { CKA_WRAP, NULL, 0 },
1306
0
        { CKA_VERIFY, NULL, 0 },
1307
0
        { CKA_VERIFY_RECOVER, NULL, 0 },
1308
0
        { CKA_ENCRYPT, NULL, 0 },
1309
0
        { CKA_MODIFIABLE, NULL, 0 },
1310
0
    };
1311
1312
    /*CK_ULONG key_size = 0;*/
1313
0
    CK_ATTRIBUTE *pubTemplate;
1314
0
    int privCount = 0;
1315
0
    int pubCount = 0;
1316
0
    PK11RSAGenParams *rsaParams;
1317
0
    SECKEYPQGParams *dsaParams;
1318
0
    SECKEYDHParams *dhParams;
1319
0
    CK_NSS_KEM_PARAMETER_SET_TYPE *kemParams;
1320
0
    CK_MECHANISM mechanism;
1321
0
    CK_MECHANISM test_mech;
1322
0
    CK_MECHANISM test_mech2;
1323
0
    CK_SESSION_HANDLE session_handle;
1324
0
    CK_RV crv;
1325
0
    CK_OBJECT_HANDLE privID, pubID;
1326
0
    SECKEYPrivateKey *privKey;
1327
0
    KeyType keyType;
1328
0
    PRBool restore;
1329
0
    int peCount, i;
1330
0
    CK_ATTRIBUTE *attrs;
1331
0
    CK_ATTRIBUTE *privattrs;
1332
0
    CK_ATTRIBUTE setTemplate;
1333
0
    CK_MECHANISM_INFO mechanism_info;
1334
0
    CK_OBJECT_CLASS keyClass;
1335
0
    SECItem *cka_id;
1336
0
    PRBool haslock = PR_FALSE;
1337
0
    PRBool pubIsToken = PR_FALSE;
1338
0
    PRBool token = ((attrFlags & PK11_ATTR_TOKEN) != 0);
1339
    /* subset of attrFlags applicable to the public key */
1340
0
    PK11AttrFlags pubKeyAttrFlags = attrFlags &
1341
0
                                    (PK11_ATTR_TOKEN | PK11_ATTR_SESSION | PK11_ATTR_MODIFIABLE | PK11_ATTR_UNMODIFIABLE);
1342
1343
0
    if (pk11_BadAttrFlags(attrFlags)) {
1344
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1345
0
        return NULL;
1346
0
    }
1347
1348
0
    if (!param) {
1349
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1350
0
        return NULL;
1351
0
    }
1352
1353
    /*
1354
     * The opFlags and opFlagMask parameters allow us to control the
1355
     * settings of the key usage attributes (CKA_ENCRYPT and friends).
1356
     * opFlagMask is set to one if the flag is specified in opFlags and
1357
     *  zero if it is to take on a default value calculated by
1358
     *  PK11_GenerateKeyPairWithOpFlags.
1359
     * opFlags specifies the actual value of the flag 1 or 0.
1360
     *   Bits not corresponding to one bits in opFlagMask should be zero.
1361
     */
1362
1363
    /* if we are trying to turn on a flag, it better be in the mask */
1364
0
    PORT_Assert((opFlags & ~opFlagsMask) == 0);
1365
0
    opFlags &= opFlagsMask;
1366
1367
0
    PORT_Assert(slot != NULL);
1368
0
    if (slot == NULL) {
1369
0
        PORT_SetError(SEC_ERROR_NO_MODULE);
1370
0
        return NULL;
1371
0
    }
1372
1373
    /* if our slot really doesn't do this mechanism, Generate the key
1374
     * in our internal token and write it out */
1375
0
    if (!PK11_DoesMechanism(slot, type)) {
1376
0
        PK11SlotInfo *int_slot = PK11_GetInternalSlot();
1377
1378
        /* don't loop forever looking for a slot */
1379
0
        if (slot == int_slot) {
1380
0
            PK11_FreeSlot(int_slot);
1381
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1382
0
            return NULL;
1383
0
        }
1384
1385
        /* if there isn't a suitable slot, then we can't do the keygen */
1386
0
        if (int_slot == NULL) {
1387
0
            PORT_SetError(SEC_ERROR_NO_MODULE);
1388
0
            return NULL;
1389
0
        }
1390
1391
        /* generate the temporary key to load */
1392
0
        privKey = PK11_GenerateKeyPair(int_slot, type, param, pubKey, PR_FALSE,
1393
0
                                       PR_FALSE, wincx);
1394
0
        PK11_FreeSlot(int_slot);
1395
1396
        /* if successful, load the temp key into the new token */
1397
0
        if (privKey != NULL) {
1398
0
            SECKEYPrivateKey *newPrivKey = pk11_loadPrivKeyWithFlags(slot,
1399
0
                                                                     privKey, *pubKey, attrFlags);
1400
0
            SECKEY_DestroyPrivateKey(privKey);
1401
0
            if (newPrivKey == NULL) {
1402
0
                SECKEY_DestroyPublicKey(*pubKey);
1403
0
                *pubKey = NULL;
1404
0
            }
1405
0
            return newPrivKey;
1406
0
        }
1407
0
        return NULL;
1408
0
    }
1409
1410
0
    mechanism.mechanism = type;
1411
0
    mechanism.pParameter = NULL;
1412
0
    mechanism.ulParameterLen = 0;
1413
0
    test_mech.pParameter = NULL;
1414
0
    test_mech.ulParameterLen = 0;
1415
0
    test_mech2.mechanism = CKM_INVALID_MECHANISM;
1416
0
    test_mech2.pParameter = NULL;
1417
0
    test_mech2.ulParameterLen = 0;
1418
1419
    /* set up the private key template */
1420
0
    privattrs = privTemplate;
1421
0
    privattrs += pk11_AttrFlagsToAttributes(attrFlags, privattrs,
1422
0
                                            &cktrue, &ckfalse);
1423
1424
    /* set up the mechanism specific info */
1425
0
    switch (type) {
1426
0
        case CKM_RSA_PKCS_KEY_PAIR_GEN:
1427
0
        case CKM_RSA_X9_31_KEY_PAIR_GEN:
1428
0
            rsaParams = (PK11RSAGenParams *)param;
1429
0
            if (rsaParams->pe == 0) {
1430
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1431
0
                return NULL;
1432
0
            }
1433
0
            modulusBits = rsaParams->keySizeInBits;
1434
0
            peCount = 0;
1435
1436
            /* convert pe to a PKCS #11 string */
1437
0
            for (i = 0; i < 4; i++) {
1438
0
                if (peCount || (rsaParams->pe &
1439
0
                                ((unsigned long)0xff000000L >> (i * 8)))) {
1440
0
                    publicExponent[peCount] =
1441
0
                        (CK_BYTE)((rsaParams->pe >> (3 - i) * 8) & 0xff);
1442
0
                    peCount++;
1443
0
                }
1444
0
            }
1445
0
            PORT_Assert(peCount != 0);
1446
0
            attrs = rsaPubTemplate;
1447
0
            PK11_SETATTRS(attrs, CKA_MODULUS_BITS,
1448
0
                          &modulusBits, sizeof(modulusBits));
1449
0
            attrs++;
1450
0
            PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
1451
0
                          publicExponent, peCount);
1452
0
            attrs++;
1453
0
            pubTemplate = rsaPubTemplate;
1454
0
            keyType = rsaKey;
1455
0
            test_mech.mechanism = CKM_RSA_PKCS;
1456
0
            break;
1457
0
        case CKM_DSA_KEY_PAIR_GEN:
1458
0
            dsaParams = (SECKEYPQGParams *)param;
1459
0
            attrs = dsaPubTemplate;
1460
0
            PK11_SETATTRS(attrs, CKA_PRIME, dsaParams->prime.data,
1461
0
                          dsaParams->prime.len);
1462
0
            attrs++;
1463
0
            PK11_SETATTRS(attrs, CKA_SUBPRIME, dsaParams->subPrime.data,
1464
0
                          dsaParams->subPrime.len);
1465
0
            attrs++;
1466
0
            PK11_SETATTRS(attrs, CKA_BASE, dsaParams->base.data,
1467
0
                          dsaParams->base.len);
1468
0
            attrs++;
1469
0
            pubTemplate = dsaPubTemplate;
1470
0
            keyType = dsaKey;
1471
0
            test_mech.mechanism = CKM_DSA;
1472
0
            break;
1473
0
        case CKM_DH_PKCS_KEY_PAIR_GEN:
1474
0
            dhParams = (SECKEYDHParams *)param;
1475
0
            attrs = dhPubTemplate;
1476
0
            PK11_SETATTRS(attrs, CKA_PRIME, dhParams->prime.data,
1477
0
                          dhParams->prime.len);
1478
0
            attrs++;
1479
0
            PK11_SETATTRS(attrs, CKA_BASE, dhParams->base.data,
1480
0
                          dhParams->base.len);
1481
0
            attrs++;
1482
0
            pubTemplate = dhPubTemplate;
1483
0
            keyType = dhKey;
1484
0
            test_mech.mechanism = CKM_DH_PKCS_DERIVE;
1485
0
            break;
1486
0
        case CKM_EC_KEY_PAIR_GEN:
1487
0
            ecParams = (SECKEYECParams *)param;
1488
0
            attrs = ecPubTemplate;
1489
0
            PK11_SETATTRS(attrs, CKA_EC_PARAMS, ecParams->data,
1490
0
                          ecParams->len);
1491
0
            attrs++;
1492
0
            pubTemplate = ecPubTemplate;
1493
0
            keyType = ecKey;
1494
            /*
1495
             * ECC supports 2 different mechanism types (unlike RSA, which
1496
             * supports different usages with the same mechanism).
1497
             * We may need to query both mechanism types and or the results
1498
             * together -- but we only do that if either the user has
1499
             * requested both usages, or not specified any usages.
1500
             */
1501
0
            if ((opFlags & (CKF_SIGN | CKF_DERIVE)) == (CKF_SIGN | CKF_DERIVE)) {
1502
                /* We've explicitly turned on both flags, use both mechanism */
1503
0
                test_mech.mechanism = CKM_ECDH1_DERIVE;
1504
0
                test_mech2.mechanism = CKM_ECDSA;
1505
0
            } else if (opFlags & CKF_SIGN) {
1506
                /* just do signing */
1507
0
                test_mech.mechanism = CKM_ECDSA;
1508
0
            } else if (opFlags & CKF_DERIVE) {
1509
                /* just do ECDH */
1510
0
                test_mech.mechanism = CKM_ECDH1_DERIVE;
1511
0
            } else {
1512
                /* neither was specified default to both */
1513
0
                test_mech.mechanism = CKM_ECDH1_DERIVE;
1514
0
                test_mech2.mechanism = CKM_ECDSA;
1515
0
            }
1516
0
            break;
1517
0
        case CKM_NSS_KYBER_KEY_PAIR_GEN:
1518
0
            kemParams = (CK_NSS_KEM_PARAMETER_SET_TYPE *)param;
1519
0
            attrs = kyberPubTemplate;
1520
0
            PK11_SETATTRS(attrs, CKA_NSS_PARAMETER_SET,
1521
0
                          kemParams,
1522
0
                          sizeof(CK_NSS_KEM_PARAMETER_SET_TYPE));
1523
0
            attrs++;
1524
0
            pubTemplate = kyberPubTemplate;
1525
0
            keyType = kyberKey;
1526
0
            test_mech.mechanism = CKM_NSS_KYBER;
1527
0
            break;
1528
0
        case CKM_EC_EDWARDS_KEY_PAIR_GEN:
1529
0
            ecParams = (SECKEYECParams *)param;
1530
0
            attrs = ecPubTemplate;
1531
0
            PK11_SETATTRS(attrs, CKA_EC_PARAMS, ecParams->data,
1532
0
                          ecParams->len);
1533
0
            attrs++;
1534
0
            pubTemplate = ecPubTemplate;
1535
0
            keyType = edKey;
1536
0
            test_mech.mechanism = CKM_EDDSA;
1537
0
            break;
1538
0
        default:
1539
0
            PORT_SetError(SEC_ERROR_BAD_KEY);
1540
0
            return NULL;
1541
0
    }
1542
1543
    /* now query the slot to find out how "good" a key we can generate */
1544
0
    if (!slot->isThreadSafe)
1545
0
        PK11_EnterSlotMonitor(slot);
1546
0
    crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
1547
0
                                                test_mech.mechanism, &mechanism_info);
1548
    /*
1549
     * EC keys are used in multiple different types of mechanism, if we
1550
     * are using dual use keys, we need to query the second mechanism
1551
     * as well.
1552
     */
1553
0
    if (test_mech2.mechanism != CKM_INVALID_MECHANISM) {
1554
0
        CK_MECHANISM_INFO mechanism_info2;
1555
0
        CK_RV crv2;
1556
1557
0
        if (crv != CKR_OK) {
1558
            /* the first failed, make sure there is no trash in the
1559
             * mechanism flags when we or it below */
1560
0
            mechanism_info.flags = 0;
1561
0
        }
1562
0
        crv2 = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
1563
0
                                                     test_mech2.mechanism, &mechanism_info2);
1564
0
        if (crv2 == CKR_OK) {
1565
0
            crv = CKR_OK; /* succeed if either mechnaism info succeeds */
1566
            /* combine the 2 sets of mechnanism flags */
1567
0
            mechanism_info.flags |= mechanism_info2.flags;
1568
0
        }
1569
0
    }
1570
0
    if (!slot->isThreadSafe)
1571
0
        PK11_ExitSlotMonitor(slot);
1572
0
    if ((crv != CKR_OK) || (mechanism_info.flags == 0)) {
1573
        /* must be old module... guess what it should be... */
1574
0
        switch (test_mech.mechanism) {
1575
0
            case CKM_RSA_PKCS:
1576
0
                mechanism_info.flags = (CKF_SIGN | CKF_DECRYPT |
1577
0
                                        CKF_WRAP | CKF_VERIFY_RECOVER | CKF_ENCRYPT | CKF_WRAP);
1578
0
                break;
1579
0
            case CKM_DSA:
1580
0
                mechanism_info.flags = CKF_SIGN | CKF_VERIFY;
1581
0
                break;
1582
0
            case CKM_DH_PKCS_DERIVE:
1583
0
                mechanism_info.flags = CKF_DERIVE;
1584
0
                break;
1585
0
            case CKM_ECDH1_DERIVE:
1586
0
                mechanism_info.flags = CKF_DERIVE;
1587
0
                if (test_mech2.mechanism == CKM_ECDSA) {
1588
0
                    mechanism_info.flags |= CKF_SIGN | CKF_VERIFY;
1589
0
                }
1590
0
                break;
1591
0
            case CKM_ECDSA:
1592
0
                mechanism_info.flags = CKF_SIGN | CKF_VERIFY;
1593
0
                break;
1594
0
            case CKM_EDDSA:
1595
0
                mechanism_info.flags = CKF_SIGN | CKF_VERIFY;
1596
0
                break;
1597
1598
0
            default:
1599
0
                break;
1600
0
        }
1601
0
    }
1602
    /* now adjust our flags according to the user's key usage passed to us */
1603
0
    mechanism_info.flags = (mechanism_info.flags & (~opFlagsMask)) | opFlags;
1604
    /* set the public key attributes */
1605
0
    attrs += pk11_AttrFlagsToAttributes(pubKeyAttrFlags, attrs,
1606
0
                                        &cktrue, &ckfalse);
1607
0
    PK11_SETATTRS(attrs, CKA_DERIVE,
1608
0
                  mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
1609
0
                  sizeof(CK_BBOOL));
1610
0
    attrs++;
1611
0
    PK11_SETATTRS(attrs, CKA_WRAP,
1612
0
                  mechanism_info.flags & CKF_WRAP ? &cktrue : &ckfalse,
1613
0
                  sizeof(CK_BBOOL));
1614
0
    attrs++;
1615
0
    PK11_SETATTRS(attrs, CKA_VERIFY,
1616
0
                  mechanism_info.flags & CKF_VERIFY ? &cktrue : &ckfalse,
1617
0
                  sizeof(CK_BBOOL));
1618
0
    attrs++;
1619
0
    PK11_SETATTRS(attrs, CKA_VERIFY_RECOVER,
1620
0
                  mechanism_info.flags & CKF_VERIFY_RECOVER ? &cktrue : &ckfalse,
1621
0
                  sizeof(CK_BBOOL));
1622
0
    attrs++;
1623
0
    PK11_SETATTRS(attrs, CKA_ENCRYPT,
1624
0
                  mechanism_info.flags & CKF_ENCRYPT ? &cktrue : &ckfalse,
1625
0
                  sizeof(CK_BBOOL));
1626
0
    attrs++;
1627
    /* set the private key attributes */
1628
0
    PK11_SETATTRS(privattrs, CKA_DERIVE,
1629
0
                  mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
1630
0
                  sizeof(CK_BBOOL));
1631
0
    privattrs++;
1632
0
    PK11_SETATTRS(privattrs, CKA_UNWRAP,
1633
0
                  mechanism_info.flags & CKF_UNWRAP ? &cktrue : &ckfalse,
1634
0
                  sizeof(CK_BBOOL));
1635
0
    privattrs++;
1636
0
    PK11_SETATTRS(privattrs, CKA_SIGN,
1637
0
                  mechanism_info.flags & CKF_SIGN ? &cktrue : &ckfalse,
1638
0
                  sizeof(CK_BBOOL));
1639
0
    privattrs++;
1640
0
    PK11_SETATTRS(privattrs, CKA_DECRYPT,
1641
0
                  mechanism_info.flags & CKF_DECRYPT ? &cktrue : &ckfalse,
1642
0
                  sizeof(CK_BBOOL));
1643
0
    privattrs++;
1644
1645
0
    if (token) {
1646
0
        session_handle = PK11_GetRWSession(slot);
1647
0
        haslock = PK11_RWSessionHasLock(slot, session_handle);
1648
0
        restore = PR_TRUE;
1649
0
    } else {
1650
0
        session_handle = slot->session;
1651
0
        if (session_handle != CK_INVALID_HANDLE)
1652
0
            PK11_EnterSlotMonitor(slot);
1653
0
        restore = PR_FALSE;
1654
0
        haslock = PR_TRUE;
1655
0
    }
1656
1657
0
    if (session_handle == CK_INVALID_HANDLE) {
1658
0
        PORT_SetError(SEC_ERROR_BAD_DATA);
1659
0
        return NULL;
1660
0
    }
1661
0
    privCount = privattrs - privTemplate;
1662
0
    pubCount = attrs - pubTemplate;
1663
0
    crv = PK11_GETTAB(slot)->C_GenerateKeyPair(session_handle, &mechanism,
1664
0
                                               pubTemplate, pubCount, privTemplate, privCount, &pubID, &privID);
1665
1666
0
    if (crv != CKR_OK) {
1667
0
        if (restore) {
1668
0
            PK11_RestoreROSession(slot, session_handle);
1669
0
        } else
1670
0
            PK11_ExitSlotMonitor(slot);
1671
0
        PORT_SetError(PK11_MapError(crv));
1672
0
        return NULL;
1673
0
    }
1674
    /* This locking code is dangerous and needs to be more thought
1675
     * out... the real problem is that we're holding the mutex open this long
1676
     */
1677
0
    if (haslock) {
1678
0
        PK11_ExitSlotMonitor(slot);
1679
0
    }
1680
1681
    /* swap around the ID's for older PKCS #11 modules */
1682
0
    keyClass = PK11_ReadULongAttribute(slot, pubID, CKA_CLASS);
1683
0
    if (keyClass != CKO_PUBLIC_KEY) {
1684
0
        CK_OBJECT_HANDLE tmp = pubID;
1685
0
        pubID = privID;
1686
0
        privID = tmp;
1687
0
    }
1688
1689
0
    *pubKey = PK11_ExtractPublicKey(slot, keyType, pubID);
1690
0
    if (*pubKey == NULL) {
1691
0
        if (restore) {
1692
            /* we may have to restore the mutex so it get's exited properly
1693
             * in RestoreROSession */
1694
0
            if (haslock)
1695
0
                PK11_EnterSlotMonitor(slot);
1696
0
            PK11_RestoreROSession(slot, session_handle);
1697
0
        }
1698
0
        PK11_DestroyObject(slot, pubID);
1699
0
        PK11_DestroyObject(slot, privID);
1700
0
        return NULL;
1701
0
    }
1702
1703
    /* set the ID to the public key so we can find it again */
1704
0
    cka_id = pk11_MakeIDFromPublicKey(*pubKey);
1705
0
    pubIsToken = (PRBool)PK11_HasAttributeSet(slot, pubID, CKA_TOKEN, PR_FALSE);
1706
1707
0
    PK11_SETATTRS(&setTemplate, CKA_ID, cka_id->data, cka_id->len);
1708
1709
0
    if (haslock) {
1710
0
        PK11_EnterSlotMonitor(slot);
1711
0
    }
1712
0
    crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, privID,
1713
0
                                                 &setTemplate, 1);
1714
1715
0
    if (crv == CKR_OK && pubIsToken) {
1716
0
        crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, pubID,
1717
0
                                                     &setTemplate, 1);
1718
0
    }
1719
1720
0
    if (restore) {
1721
0
        PK11_RestoreROSession(slot, session_handle);
1722
0
    } else {
1723
0
        PK11_ExitSlotMonitor(slot);
1724
0
    }
1725
0
    SECITEM_FreeItem(cka_id, PR_TRUE);
1726
1727
0
    if (crv != CKR_OK) {
1728
0
        PK11_DestroyObject(slot, pubID);
1729
0
        PK11_DestroyObject(slot, privID);
1730
0
        PORT_SetError(PK11_MapError(crv));
1731
0
        *pubKey = NULL;
1732
0
        return NULL;
1733
0
    }
1734
1735
0
    privKey = PK11_MakePrivKey(slot, keyType, !token, privID, wincx);
1736
0
    if (privKey == NULL) {
1737
0
        SECKEY_DestroyPublicKey(*pubKey);
1738
0
        PK11_DestroyObject(slot, privID);
1739
0
        *pubKey = NULL;
1740
0
        return NULL;
1741
0
    }
1742
1743
0
    return privKey;
1744
0
}
1745
1746
SECKEYPrivateKey *
1747
PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1748
                              void *param, SECKEYPublicKey **pubKey, PK11AttrFlags attrFlags, void *wincx)
1749
0
{
1750
0
    return PK11_GenerateKeyPairWithOpFlags(slot, type, param, pubKey, attrFlags,
1751
0
                                           0, 0, wincx);
1752
0
}
1753
1754
/*
1755
 * Use the token to generate a key pair.
1756
 */
1757
SECKEYPrivateKey *
1758
PK11_GenerateKeyPair(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1759
                     void *param, SECKEYPublicKey **pubKey, PRBool token,
1760
                     PRBool sensitive, void *wincx)
1761
0
{
1762
0
    PK11AttrFlags attrFlags = 0;
1763
1764
0
    if (token) {
1765
0
        attrFlags |= PK11_ATTR_TOKEN;
1766
0
    } else {
1767
0
        attrFlags |= PK11_ATTR_SESSION;
1768
0
    }
1769
0
    if (sensitive) {
1770
0
        attrFlags |= (PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE);
1771
0
    } else {
1772
0
        attrFlags |= (PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC);
1773
0
    }
1774
0
    return PK11_GenerateKeyPairWithFlags(slot, type, param, pubKey,
1775
0
                                         attrFlags, wincx);
1776
0
}
1777
1778
/* build a public KEA key from the public value */
1779
SECKEYPublicKey *
1780
PK11_MakeKEAPubKey(unsigned char *keyData, int length)
1781
0
{
1782
0
    SECKEYPublicKey *pubk;
1783
0
    SECItem pkData;
1784
0
    SECStatus rv;
1785
0
    PLArenaPool *arena;
1786
1787
0
    pkData.data = keyData;
1788
0
    pkData.len = length;
1789
0
    pkData.type = siBuffer;
1790
1791
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1792
0
    if (arena == NULL)
1793
0
        return NULL;
1794
1795
0
    pubk = (SECKEYPublicKey *)PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
1796
0
    if (pubk == NULL) {
1797
0
        PORT_FreeArena(arena, PR_FALSE);
1798
0
        return NULL;
1799
0
    }
1800
1801
0
    pubk->arena = arena;
1802
0
    pubk->pkcs11Slot = 0;
1803
0
    pubk->pkcs11ID = CK_INVALID_HANDLE;
1804
0
    pubk->keyType = fortezzaKey;
1805
0
    rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.KEAKey, &pkData);
1806
0
    if (rv != SECSuccess) {
1807
0
        PORT_FreeArena(arena, PR_FALSE);
1808
0
        return NULL;
1809
0
    }
1810
0
    return pubk;
1811
0
}
1812
1813
SECStatus
1814
SECKEY_SetPublicValue(SECKEYPrivateKey *privKey, SECItem *publicValue)
1815
0
{
1816
0
    SECStatus rv;
1817
0
    SECKEYPublicKey pubKey;
1818
0
    PLArenaPool *arena;
1819
0
    PK11SlotInfo *slot;
1820
0
    CK_OBJECT_HANDLE privKeyID;
1821
1822
0
    if (privKey == NULL || publicValue == NULL ||
1823
0
        publicValue->data == NULL || publicValue->len == 0) {
1824
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1825
0
        return SECFailure;
1826
0
    }
1827
1828
0
    pubKey.arena = NULL;
1829
0
    pubKey.keyType = privKey->keyType;
1830
0
    pubKey.pkcs11Slot = NULL;
1831
0
    pubKey.pkcs11ID = CK_INVALID_HANDLE;
1832
    /* can't use PORT_InitCheapArena here becase SECKEY_DestroyPublic is used
1833
      * to free it, and it uses PORT_FreeArena which not only frees the 
1834
      * underlying arena, it also frees the allocated arena struct. */
1835
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1836
0
    pubKey.arena = arena;
1837
0
    if (arena == NULL) {
1838
0
        return SECFailure;
1839
0
    }
1840
1841
0
    slot = privKey->pkcs11Slot;
1842
0
    privKeyID = privKey->pkcs11ID;
1843
0
    rv = SECFailure;
1844
0
    switch (privKey->keyType) {
1845
0
        default:
1846
            /* error code already set to SECFailure */
1847
0
            break;
1848
0
        case rsaKey:
1849
0
            pubKey.u.rsa.modulus = *publicValue;
1850
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_PUBLIC_EXPONENT,
1851
0
                                    arena, &pubKey.u.rsa.publicExponent);
1852
0
            break;
1853
0
        case dsaKey:
1854
0
            pubKey.u.dsa.publicValue = *publicValue;
1855
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_PRIME,
1856
0
                                    arena, &pubKey.u.dsa.params.prime);
1857
0
            if (rv != SECSuccess) {
1858
0
                break;
1859
0
            }
1860
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_SUBPRIME,
1861
0
                                    arena, &pubKey.u.dsa.params.subPrime);
1862
0
            if (rv != SECSuccess) {
1863
0
                break;
1864
0
            }
1865
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_BASE,
1866
0
                                    arena, &pubKey.u.dsa.params.base);
1867
0
            break;
1868
0
        case dhKey:
1869
0
            pubKey.u.dh.publicValue = *publicValue;
1870
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_PRIME,
1871
0
                                    arena, &pubKey.u.dh.prime);
1872
0
            if (rv != SECSuccess) {
1873
0
                break;
1874
0
            }
1875
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_BASE,
1876
0
                                    arena, &pubKey.u.dh.base);
1877
0
            break;
1878
0
        case edKey:
1879
0
        case ecKey:
1880
0
            pubKey.u.ec.publicValue = *publicValue;
1881
0
            pubKey.u.ec.encoding = ECPoint_Undefined;
1882
0
            pubKey.u.ec.size = 0;
1883
0
            rv = PK11_ReadAttribute(slot, privKeyID, CKA_EC_PARAMS,
1884
0
                                    arena, &pubKey.u.ec.DEREncodedParams);
1885
0
            break;
1886
0
    }
1887
0
    if (rv == SECSuccess) {
1888
0
        rv = PK11_ImportPublicKey(slot, &pubKey, PR_TRUE);
1889
0
    }
1890
    /* Even though pubKey is stored on the stack, we've allocated
1891
     * some of it's data from the arena. SECKEY_DestroyPublicKey
1892
     * destroys keys by freeing the arena, so this will clean up all
1893
     * the data we allocated specifically for the key above. It will
1894
     * also free any slot references which we may have picked up in
1895
     * PK11_ImportPublicKey. It won't delete the underlying key if
1896
     * its a Token/Permanent key (which it will be if
1897
     * PK11_ImportPublicKey succeeds). */
1898
0
    SECKEY_DestroyPublicKey(&pubKey);
1899
1900
0
    return rv;
1901
0
}
1902
1903
/*
1904
 * NOTE: This function doesn't return a SECKEYPrivateKey struct to represent
1905
 * the new private key object.  If it were to create a session object that
1906
 * could later be looked up by its nickname, it would leak a SECKEYPrivateKey.
1907
 * So isPerm must be true.
1908
 */
1909
SECStatus
1910
PK11_ImportEncryptedPrivateKeyInfo(PK11SlotInfo *slot,
1911
                                   SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
1912
                                   SECItem *nickname, SECItem *publicValue, PRBool isPerm,
1913
                                   PRBool isPrivate, KeyType keyType,
1914
                                   unsigned int keyUsage, void *wincx)
1915
0
{
1916
0
    if (!isPerm) {
1917
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1918
0
        return SECFailure;
1919
0
    }
1920
0
    return PK11_ImportEncryptedPrivateKeyInfoAndReturnKey(slot, epki,
1921
0
                                                          pwitem, nickname, publicValue, isPerm, isPrivate, keyType,
1922
0
                                                          keyUsage, NULL, wincx);
1923
0
}
1924
1925
SECStatus
1926
PK11_ImportEncryptedPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
1927
                                               SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
1928
                                               SECItem *nickname, SECItem *publicValue, PRBool isPerm,
1929
                                               PRBool isPrivate, KeyType keyType,
1930
                                               unsigned int keyUsage, SECKEYPrivateKey **privk,
1931
                                               void *wincx)
1932
0
{
1933
0
    CK_MECHANISM_TYPE pbeMechType;
1934
0
    SECItem *crypto_param = NULL;
1935
0
    PK11SymKey *key = NULL;
1936
0
    SECStatus rv = SECSuccess;
1937
0
    CK_MECHANISM_TYPE cryptoMechType;
1938
0
    SECKEYPrivateKey *privKey = NULL;
1939
0
    PRBool faulty3DES = PR_FALSE;
1940
0
    int usageCount = 0;
1941
0
    CK_KEY_TYPE key_type;
1942
0
    CK_ATTRIBUTE_TYPE *usage = NULL;
1943
0
    CK_ATTRIBUTE_TYPE rsaUsage[] = {
1944
0
        CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER
1945
0
    };
1946
0
    CK_ATTRIBUTE_TYPE dsaUsage[] = { CKA_SIGN };
1947
0
    CK_ATTRIBUTE_TYPE dhUsage[] = { CKA_DERIVE };
1948
0
    CK_ATTRIBUTE_TYPE ecUsage[] = { CKA_SIGN, CKA_DERIVE };
1949
0
    CK_ATTRIBUTE_TYPE edUsage[] = { CKA_SIGN };
1950
0
    if ((epki == NULL) || (pwitem == NULL))
1951
0
        return SECFailure;
1952
1953
0
    pbeMechType = PK11_AlgtagToMechanism(SECOID_FindOIDTag(
1954
0
        &epki->algorithm.algorithm));
1955
1956
0
    switch (keyType) {
1957
0
        default:
1958
0
        case rsaKey:
1959
0
            key_type = CKK_RSA;
1960
0
            switch (keyUsage & (KU_KEY_ENCIPHERMENT | KU_DIGITAL_SIGNATURE)) {
1961
0
                case KU_KEY_ENCIPHERMENT:
1962
0
                    usage = rsaUsage;
1963
0
                    usageCount = 2;
1964
0
                    break;
1965
0
                case KU_DIGITAL_SIGNATURE:
1966
0
                    usage = &rsaUsage[2];
1967
0
                    usageCount = 2;
1968
0
                    break;
1969
0
                case KU_KEY_ENCIPHERMENT | KU_DIGITAL_SIGNATURE:
1970
0
                case 0: /* default to everything */
1971
0
                    usage = rsaUsage;
1972
0
                    usageCount = 4;
1973
0
                    break;
1974
0
            }
1975
0
            break;
1976
0
        case dhKey:
1977
0
            key_type = CKK_DH;
1978
0
            usage = dhUsage;
1979
0
            usageCount = sizeof(dhUsage) / sizeof(dhUsage[0]);
1980
0
            break;
1981
0
        case dsaKey:
1982
0
            key_type = CKK_DSA;
1983
0
            usage = dsaUsage;
1984
0
            usageCount = sizeof(dsaUsage) / sizeof(dsaUsage[0]);
1985
0
            break;
1986
0
        case ecKey:
1987
0
            key_type = CKK_EC;
1988
0
            switch (keyUsage & (KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT)) {
1989
0
                case KU_DIGITAL_SIGNATURE:
1990
0
                    usage = ecUsage;
1991
0
                    usageCount = 1;
1992
0
                    break;
1993
0
                case KU_KEY_AGREEMENT:
1994
0
                    usage = &ecUsage[1];
1995
0
                    usageCount = 1;
1996
0
                    break;
1997
0
                case KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT:
1998
0
                default: /* default to everything */
1999
0
                    usage = ecUsage;
2000
0
                    usageCount = 2;
2001
0
                    break;
2002
0
            }
2003
0
            break;
2004
0
        case edKey:
2005
0
            key_type = CKK_EC_EDWARDS;
2006
0
            usage = edUsage;
2007
0
            usageCount = 1;
2008
0
            break;
2009
0
    }
2010
2011
0
try_faulty_3des:
2012
2013
0
    key = PK11_PBEKeyGen(slot, &epki->algorithm, pwitem, faulty3DES, wincx);
2014
0
    if (key == NULL) {
2015
0
        rv = SECFailure;
2016
0
        goto done;
2017
0
    }
2018
0
    cryptoMechType = pk11_GetPBECryptoMechanism(&epki->algorithm,
2019
0
                                                &crypto_param, pwitem, faulty3DES);
2020
0
    if (cryptoMechType == CKM_INVALID_MECHANISM) {
2021
0
        rv = SECFailure;
2022
0
        goto done;
2023
0
    }
2024
2025
0
    cryptoMechType = PK11_GetPadMechanism(cryptoMechType);
2026
2027
0
    PORT_Assert(usage != NULL);
2028
0
    PORT_Assert(usageCount != 0);
2029
0
    privKey = PK11_UnwrapPrivKey(slot, key, cryptoMechType,
2030
0
                                 crypto_param, &epki->encryptedData,
2031
0
                                 nickname, publicValue, isPerm, isPrivate,
2032
0
                                 key_type, usage, usageCount, wincx);
2033
0
    if (privKey) {
2034
0
        rv = SECSuccess;
2035
0
        goto done;
2036
0
    }
2037
2038
    /* if we are unable to import the key and the pbeMechType is
2039
     * CKM_NSS_PBE_SHA1_TRIPLE_DES_CBC, then it is possible that
2040
     * the encrypted blob was created with a buggy key generation method
2041
     * which is described in the PKCS 12 implementation notes.  So we
2042
     * need to try importing via that method.
2043
     */
2044
0
    if ((pbeMechType == CKM_NSS_PBE_SHA1_TRIPLE_DES_CBC) && (!faulty3DES)) {
2045
        /* clean up after ourselves before redoing the key generation. */
2046
2047
0
        PK11_FreeSymKey(key);
2048
0
        key = NULL;
2049
2050
0
        if (crypto_param) {
2051
0
            SECITEM_ZfreeItem(crypto_param, PR_TRUE);
2052
0
            crypto_param = NULL;
2053
0
        }
2054
2055
0
        faulty3DES = PR_TRUE;
2056
0
        goto try_faulty_3des;
2057
0
    }
2058
2059
    /* key import really did fail */
2060
0
    rv = SECFailure;
2061
2062
0
done:
2063
0
    if ((rv == SECSuccess) && isPerm) {
2064
        /* If we are importing a token object,
2065
         * create the corresponding public key.
2066
         * If this fails, just continue as the target
2067
         * token simply might not support persistant
2068
         * public keys. Such tokens are usable, but
2069
         * need to be authenticated before searching
2070
         * for user certs. */
2071
0
        (void)SECKEY_SetPublicValue(privKey, publicValue);
2072
0
    }
2073
2074
0
    if (privKey) {
2075
0
        if (privk) {
2076
0
            *privk = privKey;
2077
0
        } else {
2078
0
            SECKEY_DestroyPrivateKey(privKey);
2079
0
        }
2080
0
        privKey = NULL;
2081
0
    }
2082
0
    if (crypto_param != NULL) {
2083
0
        SECITEM_ZfreeItem(crypto_param, PR_TRUE);
2084
0
    }
2085
2086
0
    if (key != NULL) {
2087
0
        PK11_FreeSymKey(key);
2088
0
    }
2089
2090
0
    return rv;
2091
0
}
2092
2093
SECKEYPrivateKeyInfo *
2094
PK11_ExportPrivateKeyInfo(CERTCertificate *cert, void *wincx)
2095
0
{
2096
0
    SECKEYPrivateKeyInfo *pki = NULL;
2097
0
    SECKEYPrivateKey *pk = PK11_FindKeyByAnyCert(cert, wincx);
2098
0
    if (pk != NULL) {
2099
0
        pki = PK11_ExportPrivKeyInfo(pk, wincx);
2100
0
        SECKEY_DestroyPrivateKey(pk);
2101
0
    }
2102
0
    return pki;
2103
0
}
2104
2105
/* V2 refers to PKCS #5 V2 here. If a PKCS #5 v1 or PKCS #12 pbe is passed
2106
 * for pbeTag, then encTag and hashTag are ignored. If pbe is an encryption
2107
 * algorithm, then PKCS #5 V2 is used with prfTag for the prf. If prfTag isn't
2108
 * supplied prf will be SEC_OID_HMAC_SHA1 */
2109
SECKEYEncryptedPrivateKeyInfo *
2110
PK11_ExportEncryptedPrivKeyInfoV2(
2111
    PK11SlotInfo *slot,   /* optional, encrypt key in this slot */
2112
    SECOidTag pbeAlg,     /* PBE algorithm to encrypt the with key */
2113
    SECOidTag encAlg,     /* Encryption algorithm to Encrypt the key with */
2114
    SECOidTag prfAlg,     /* Hash algorithm for PRF */
2115
    SECItem *pwitem,      /* password for PBE encryption */
2116
    SECKEYPrivateKey *pk, /* encrypt this private key */
2117
    int iteration,        /* interations for PBE alg */
2118
    void *pwArg)          /* context for password callback */
2119
0
{
2120
0
    SECKEYEncryptedPrivateKeyInfo *epki = NULL;
2121
0
    PLArenaPool *arena = NULL;
2122
0
    SECAlgorithmID *algid;
2123
0
    SECOidTag pbeAlgTag = SEC_OID_UNKNOWN;
2124
0
    SECItem *crypto_param = NULL;
2125
0
    PK11SymKey *key = NULL;
2126
0
    SECKEYPrivateKey *tmpPK = NULL;
2127
0
    SECStatus rv = SECSuccess;
2128
0
    CK_RV crv;
2129
0
    CK_ULONG encBufLen;
2130
0
    CK_MECHANISM_TYPE pbeMechType;
2131
0
    CK_MECHANISM_TYPE cryptoMechType;
2132
0
    CK_MECHANISM cryptoMech;
2133
2134
0
    if (!pwitem || !pk) {
2135
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2136
0
        return NULL;
2137
0
    }
2138
2139
0
    algid = sec_pkcs5CreateAlgorithmID(pbeAlg, encAlg, prfAlg,
2140
0
                                       &pbeAlgTag, 0, NULL, iteration);
2141
0
    if (algid == NULL) {
2142
0
        return NULL;
2143
0
    }
2144
2145
0
    arena = PORT_NewArena(2048);
2146
0
    if (arena)
2147
0
        epki = PORT_ArenaZNew(arena, SECKEYEncryptedPrivateKeyInfo);
2148
0
    if (epki == NULL) {
2149
0
        rv = SECFailure;
2150
0
        goto loser;
2151
0
    }
2152
0
    epki->arena = arena;
2153
2154
    /* if we didn't specify a slot, use the slot the private key was in */
2155
0
    if (!slot) {
2156
0
        slot = pk->pkcs11Slot;
2157
0
    }
2158
2159
    /* if we specified a different slot, and the private key slot can do the
2160
     * pbe key gen, generate the key in the private key slot so we don't have
2161
     * to move it later */
2162
0
    pbeMechType = PK11_AlgtagToMechanism(pbeAlgTag);
2163
0
    if (slot != pk->pkcs11Slot) {
2164
0
        if (PK11_DoesMechanism(pk->pkcs11Slot, pbeMechType)) {
2165
0
            slot = pk->pkcs11Slot;
2166
0
        }
2167
0
    }
2168
0
    key = PK11_PBEKeyGen(slot, algid, pwitem, PR_FALSE, pwArg);
2169
0
    if (key == NULL) {
2170
0
        rv = SECFailure;
2171
0
        goto loser;
2172
0
    }
2173
2174
0
    cryptoMechType = PK11_GetPBECryptoMechanism(algid, &crypto_param, pwitem);
2175
0
    if (cryptoMechType == CKM_INVALID_MECHANISM) {
2176
0
        rv = SECFailure;
2177
0
        goto loser;
2178
0
    }
2179
2180
0
    cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMechType);
2181
0
    cryptoMech.pParameter = crypto_param ? crypto_param->data : NULL;
2182
0
    cryptoMech.ulParameterLen = crypto_param ? crypto_param->len : 0;
2183
2184
    /* If the key isn't in the private key slot, move it */
2185
0
    if (key->slot != pk->pkcs11Slot) {
2186
0
        PK11SymKey *newkey = pk11_CopyToSlot(pk->pkcs11Slot,
2187
0
                                             key->type, CKA_WRAP, key);
2188
0
        if (newkey == NULL) {
2189
            /* couldn't import the wrapping key, try exporting the
2190
             * private key */
2191
0
            tmpPK = pk11_loadPrivKey(key->slot, pk, NULL, PR_FALSE, PR_TRUE);
2192
0
            if (tmpPK == NULL) {
2193
0
                rv = SECFailure;
2194
0
                goto loser;
2195
0
            }
2196
0
            pk = tmpPK;
2197
0
        } else {
2198
            /* free the old key and use the new key */
2199
0
            PK11_FreeSymKey(key);
2200
0
            key = newkey;
2201
0
        }
2202
0
    }
2203
2204
    /* we are extracting an encrypted privateKey structure.
2205
     * which needs to be freed along with the buffer into which it is
2206
     * returned.  eventually, we should retrieve an encrypted key using
2207
     * pkcs8/pkcs5.
2208
     */
2209
0
    encBufLen = 0;
2210
0
    PK11_EnterSlotMonitor(pk->pkcs11Slot);
2211
0
    crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session, &cryptoMech, key->objectID, pk->pkcs11ID, NULL, &encBufLen);
2212
0
    PK11_ExitSlotMonitor(pk->pkcs11Slot);
2213
0
    if (crv != CKR_OK) {
2214
0
        rv = SECFailure;
2215
0
        goto loser;
2216
0
    }
2217
0
    epki->encryptedData.data = PORT_ArenaAlloc(arena, encBufLen);
2218
0
    if (!epki->encryptedData.data) {
2219
0
        rv = SECFailure;
2220
0
        goto loser;
2221
0
    }
2222
0
    PK11_EnterSlotMonitor(pk->pkcs11Slot);
2223
0
    crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session, &cryptoMech, key->objectID, pk->pkcs11ID, epki->encryptedData.data, &encBufLen);
2224
0
    PK11_ExitSlotMonitor(pk->pkcs11Slot);
2225
0
    epki->encryptedData.len = (unsigned int)encBufLen;
2226
0
    if (crv != CKR_OK) {
2227
0
        rv = SECFailure;
2228
0
        goto loser;
2229
0
    }
2230
2231
0
    if (!epki->encryptedData.len) {
2232
0
        rv = SECFailure;
2233
0
        goto loser;
2234
0
    }
2235
2236
0
    rv = SECOID_CopyAlgorithmID(arena, &epki->algorithm, algid);
2237
2238
0
loser:
2239
0
    if (crypto_param != NULL) {
2240
0
        SECITEM_ZfreeItem(crypto_param, PR_TRUE);
2241
0
        crypto_param = NULL;
2242
0
    }
2243
2244
0
    if (key != NULL) {
2245
0
        PK11_FreeSymKey(key);
2246
0
    }
2247
0
    if (tmpPK != NULL) {
2248
0
        SECKEY_DestroyPrivateKey(tmpPK);
2249
0
    }
2250
0
    SECOID_DestroyAlgorithmID(algid, PR_TRUE);
2251
2252
0
    if (rv == SECFailure) {
2253
0
        if (arena != NULL) {
2254
0
            PORT_FreeArena(arena, PR_TRUE);
2255
0
        }
2256
0
        epki = NULL;
2257
0
    }
2258
2259
0
    return epki;
2260
0
}
2261
2262
SECKEYEncryptedPrivateKeyInfo *
2263
PK11_ExportEncryptedPrivKeyInfo(
2264
    PK11SlotInfo *slot,   /* optional, encrypt key in this slot */
2265
    SECOidTag algTag,     /* PBE algorithm to encrypt the with key */
2266
    SECItem *pwitem,      /* password for PBE encryption */
2267
    SECKEYPrivateKey *pk, /* encrypt this private key */
2268
    int iteration,        /* interations for PBE alg */
2269
    void *pwArg)          /* context for password callback */
2270
0
{
2271
0
    return PK11_ExportEncryptedPrivKeyInfoV2(slot, algTag, SEC_OID_UNKNOWN,
2272
0
                                             SEC_OID_UNKNOWN, pwitem, pk,
2273
0
                                             iteration, pwArg);
2274
0
}
2275
2276
/* V2 refers to PKCS #5 V2 here. If a PKCS #5 v1 or PKCS #12 pbe is passed
2277
 * for pbeTag, then encTag and hashTag are ignored. If pbe is an encryption
2278
 * algorithm, then PKCS #5 V2 is used with prfTag for the prf. If prfTag isn't
2279
 * supplied prf will be SEC_OID_HMAC_SHA1 */
2280
SECKEYEncryptedPrivateKeyInfo *
2281
PK11_ExportEncryptedPrivateKeyInfoV2(
2282
    PK11SlotInfo *slot,    /* optional, encrypt key in this slot */
2283
    SECOidTag pbeAlg,      /* PBE algorithm to encrypt the with key */
2284
    SECOidTag encAlg,      /* Encryption algorithm to Encrypt the key with */
2285
    SECOidTag prfAlg,      /* HMAC algorithm for PRF*/
2286
    SECItem *pwitem,       /* password for PBE encryption */
2287
    CERTCertificate *cert, /* wrap priv key for this user cert */
2288
    int iteration,         /* interations for PBE alg */
2289
    void *pwArg)           /* context for password callback */
2290
0
{
2291
0
    SECKEYEncryptedPrivateKeyInfo *epki = NULL;
2292
0
    SECKEYPrivateKey *pk = PK11_FindKeyByAnyCert(cert, pwArg);
2293
0
    if (pk != NULL) {
2294
0
        epki = PK11_ExportEncryptedPrivKeyInfoV2(slot, pbeAlg, encAlg, prfAlg,
2295
0
                                                 pwitem, pk, iteration,
2296
0
                                                 pwArg);
2297
0
        SECKEY_DestroyPrivateKey(pk);
2298
0
    }
2299
0
    return epki;
2300
0
}
2301
2302
SECKEYEncryptedPrivateKeyInfo *
2303
PK11_ExportEncryptedPrivateKeyInfo(
2304
    PK11SlotInfo *slot,    /* optional, encrypt key in this slot */
2305
    SECOidTag algTag,      /* encrypt key with this algorithm */
2306
    SECItem *pwitem,       /* password for PBE encryption */
2307
    CERTCertificate *cert, /* wrap priv key for this user cert */
2308
    int iteration,         /* interations for PBE alg */
2309
    void *pwArg)           /* context for password callback */
2310
0
{
2311
0
    return PK11_ExportEncryptedPrivateKeyInfoV2(slot, algTag, SEC_OID_UNKNOWN,
2312
0
                                                SEC_OID_UNKNOWN, pwitem, cert,
2313
0
                                                iteration, pwArg);
2314
0
}
2315
2316
SECItem *
2317
PK11_DEREncodePublicKey(const SECKEYPublicKey *pubk)
2318
0
{
2319
0
    return SECKEY_EncodeDERSubjectPublicKeyInfo(pubk);
2320
0
}
2321
2322
char *
2323
PK11_GetPrivateKeyNickname(SECKEYPrivateKey *privKey)
2324
0
{
2325
0
    return PK11_GetObjectNickname(privKey->pkcs11Slot, privKey->pkcs11ID);
2326
0
}
2327
2328
char *
2329
PK11_GetPublicKeyNickname(SECKEYPublicKey *pubKey)
2330
0
{
2331
0
    return PK11_GetObjectNickname(pubKey->pkcs11Slot, pubKey->pkcs11ID);
2332
0
}
2333
2334
SECStatus
2335
PK11_SetPrivateKeyNickname(SECKEYPrivateKey *privKey, const char *nickname)
2336
0
{
2337
0
    return PK11_SetObjectNickname(privKey->pkcs11Slot,
2338
0
                                  privKey->pkcs11ID, nickname);
2339
0
}
2340
2341
SECStatus
2342
PK11_SetPublicKeyNickname(SECKEYPublicKey *pubKey, const char *nickname)
2343
0
{
2344
0
    return PK11_SetObjectNickname(pubKey->pkcs11Slot,
2345
0
                                  pubKey->pkcs11ID, nickname);
2346
0
}
2347
2348
SECKEYPQGParams *
2349
PK11_GetPQGParamsFromPrivateKey(SECKEYPrivateKey *privKey)
2350
0
{
2351
0
    CK_ATTRIBUTE pTemplate[] = {
2352
0
        { CKA_PRIME, NULL, 0 },
2353
0
        { CKA_SUBPRIME, NULL, 0 },
2354
0
        { CKA_BASE, NULL, 0 },
2355
0
    };
2356
0
    int pTemplateLen = sizeof(pTemplate) / sizeof(pTemplate[0]);
2357
0
    PLArenaPool *arena = NULL;
2358
0
    SECKEYPQGParams *params;
2359
0
    CK_RV crv;
2360
2361
0
    arena = PORT_NewArena(2048);
2362
0
    if (arena == NULL) {
2363
0
        goto loser;
2364
0
    }
2365
0
    params = (SECKEYPQGParams *)PORT_ArenaZAlloc(arena, sizeof(SECKEYPQGParams));
2366
0
    if (params == NULL) {
2367
0
        goto loser;
2368
0
    }
2369
2370
0
    crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID,
2371
0
                             pTemplate, pTemplateLen);
2372
0
    if (crv != CKR_OK) {
2373
0
        PORT_SetError(PK11_MapError(crv));
2374
0
        goto loser;
2375
0
    }
2376
2377
0
    params->arena = arena;
2378
0
    params->prime.data = pTemplate[0].pValue;
2379
0
    params->prime.len = pTemplate[0].ulValueLen;
2380
0
    params->subPrime.data = pTemplate[1].pValue;
2381
0
    params->subPrime.len = pTemplate[1].ulValueLen;
2382
0
    params->base.data = pTemplate[2].pValue;
2383
0
    params->base.len = pTemplate[2].ulValueLen;
2384
2385
0
    return params;
2386
2387
0
loser:
2388
0
    if (arena != NULL) {
2389
0
        PORT_FreeArena(arena, PR_FALSE);
2390
0
    }
2391
0
    return NULL;
2392
0
}
2393
2394
SECKEYPrivateKey *
2395
PK11_CopyTokenPrivKeyToSessionPrivKey(PK11SlotInfo *destSlot,
2396
                                      SECKEYPrivateKey *privKey)
2397
0
{
2398
0
    CK_RV crv;
2399
0
    CK_OBJECT_HANDLE newKeyID;
2400
2401
0
    static const CK_BBOOL ckfalse = CK_FALSE;
2402
0
    static const CK_ATTRIBUTE template[1] = {
2403
0
        { CKA_TOKEN, (CK_BBOOL *)&ckfalse, sizeof ckfalse }
2404
0
    };
2405
2406
0
    if (destSlot && destSlot != privKey->pkcs11Slot) {
2407
0
        SECKEYPrivateKey *newKey =
2408
0
            pk11_loadPrivKey(destSlot,
2409
0
                             privKey,
2410
0
                             NULL,      /* pubKey    */
2411
0
                             PR_FALSE,  /* token     */
2412
0
                             PR_FALSE); /* sensitive */
2413
0
        if (newKey)
2414
0
            return newKey;
2415
0
    }
2416
0
    destSlot = privKey->pkcs11Slot;
2417
0
    PK11_Authenticate(destSlot, PR_TRUE, privKey->wincx);
2418
0
    PK11_EnterSlotMonitor(destSlot);
2419
0
    crv = PK11_GETTAB(destSlot)->C_CopyObject(destSlot->session,
2420
0
                                              privKey->pkcs11ID,
2421
0
                                              (CK_ATTRIBUTE *)template,
2422
0
                                              1, &newKeyID);
2423
0
    PK11_ExitSlotMonitor(destSlot);
2424
2425
0
    if (crv != CKR_OK) {
2426
0
        PORT_SetError(PK11_MapError(crv));
2427
0
        return NULL;
2428
0
    }
2429
2430
0
    return PK11_MakePrivKey(destSlot, privKey->keyType, PR_TRUE /*isTemp*/,
2431
0
                            newKeyID, privKey->wincx);
2432
0
}
2433
2434
SECKEYPrivateKey *
2435
PK11_ConvertSessionPrivKeyToTokenPrivKey(SECKEYPrivateKey *privk, void *wincx)
2436
0
{
2437
0
    PK11SlotInfo *slot = privk->pkcs11Slot;
2438
0
    CK_ATTRIBUTE template[1];
2439
0
    CK_ATTRIBUTE *attrs = template;
2440
0
    CK_BBOOL cktrue = CK_TRUE;
2441
0
    CK_RV crv;
2442
0
    CK_OBJECT_HANDLE newKeyID;
2443
0
    CK_SESSION_HANDLE rwsession;
2444
2445
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue));
2446
0
    attrs++;
2447
2448
0
    PK11_Authenticate(slot, PR_TRUE, wincx);
2449
0
    rwsession = PK11_GetRWSession(slot);
2450
0
    if (rwsession == CK_INVALID_HANDLE) {
2451
0
        PORT_SetError(SEC_ERROR_BAD_DATA);
2452
0
        return NULL;
2453
0
    }
2454
0
    crv = PK11_GETTAB(slot)->C_CopyObject(rwsession, privk->pkcs11ID,
2455
0
                                          template, 1, &newKeyID);
2456
0
    PK11_RestoreROSession(slot, rwsession);
2457
2458
0
    if (crv != CKR_OK) {
2459
0
        PORT_SetError(PK11_MapError(crv));
2460
0
        return NULL;
2461
0
    }
2462
2463
0
    return PK11_MakePrivKey(slot, nullKey /*KeyType*/, PR_FALSE /*isTemp*/,
2464
0
                            newKeyID, NULL /*wincx*/);
2465
0
}
2466
2467
/*
2468
 * destroy a private key if there are no matching certs.
2469
 * this function also frees the privKey structure.
2470
 */
2471
SECStatus
2472
PK11_DeleteTokenPrivateKey(SECKEYPrivateKey *privKey, PRBool force)
2473
0
{
2474
0
    CERTCertificate *cert = PK11_GetCertFromPrivateKey(privKey);
2475
0
    SECStatus rv = SECWouldBlock;
2476
2477
0
    if (!cert || force) {
2478
        /* now, then it's safe for the key to go away */
2479
0
        rv = PK11_DestroyTokenObject(privKey->pkcs11Slot, privKey->pkcs11ID);
2480
0
    }
2481
0
    if (cert) {
2482
0
        CERT_DestroyCertificate(cert);
2483
0
    }
2484
0
    SECKEY_DestroyPrivateKey(privKey);
2485
0
    return rv;
2486
0
}
2487
2488
/*
2489
 * destroy a private key if there are no matching certs.
2490
 * this function also frees the privKey structure.
2491
 */
2492
SECStatus
2493
PK11_DeleteTokenPublicKey(SECKEYPublicKey *pubKey)
2494
0
{
2495
    /* now, then it's safe for the key to go away */
2496
0
    if (pubKey->pkcs11Slot == NULL) {
2497
0
        return SECFailure;
2498
0
    }
2499
0
    PK11_DestroyTokenObject(pubKey->pkcs11Slot, pubKey->pkcs11ID);
2500
0
    SECKEY_DestroyPublicKey(pubKey);
2501
0
    return SECSuccess;
2502
0
}
2503
2504
/*
2505
 * key call back structure.
2506
 */
2507
typedef struct pk11KeyCallbackStr {
2508
    SECStatus (*callback)(SECKEYPrivateKey *, void *);
2509
    void *callbackArg;
2510
    void *wincx;
2511
} pk11KeyCallback;
2512
2513
/*
2514
 * callback to map Object Handles to Private Keys;
2515
 */
2516
SECStatus
2517
pk11_DoKeys(PK11SlotInfo *slot, CK_OBJECT_HANDLE keyHandle, void *arg)
2518
0
{
2519
0
    SECStatus rv = SECSuccess;
2520
0
    SECKEYPrivateKey *privKey;
2521
0
    pk11KeyCallback *keycb = (pk11KeyCallback *)arg;
2522
0
    if (!arg) {
2523
0
        return SECFailure;
2524
0
    }
2525
2526
0
    privKey = PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyHandle, keycb->wincx);
2527
2528
0
    if (privKey == NULL) {
2529
0
        return SECFailure;
2530
0
    }
2531
2532
0
    if (keycb->callback) {
2533
0
        rv = (*keycb->callback)(privKey, keycb->callbackArg);
2534
0
    }
2535
2536
0
    SECKEY_DestroyPrivateKey(privKey);
2537
0
    return rv;
2538
0
}
2539
2540
/***********************************************************************
2541
 * PK11_TraversePrivateKeysInSlot
2542
 *
2543
 * Traverses all the private keys on a slot.
2544
 *
2545
 * INPUTS
2546
 *      slot
2547
 *          The PKCS #11 slot whose private keys you want to traverse.
2548
 *      callback
2549
 *          A callback function that will be called for each key.
2550
 *      arg
2551
 *          An argument that will be passed to the callback function.
2552
 */
2553
SECStatus
2554
PK11_TraversePrivateKeysInSlot(PK11SlotInfo *slot,
2555
                               SECStatus (*callback)(SECKEYPrivateKey *, void *), void *arg)
2556
0
{
2557
0
    pk11KeyCallback perKeyCB;
2558
0
    pk11TraverseSlot perObjectCB;
2559
0
    CK_OBJECT_CLASS privkClass = CKO_PRIVATE_KEY;
2560
0
    CK_BBOOL ckTrue = CK_TRUE;
2561
0
    CK_ATTRIBUTE theTemplate[2];
2562
0
    int templateSize = 2;
2563
2564
0
    theTemplate[0].type = CKA_CLASS;
2565
0
    theTemplate[0].pValue = &privkClass;
2566
0
    theTemplate[0].ulValueLen = sizeof(privkClass);
2567
0
    theTemplate[1].type = CKA_TOKEN;
2568
0
    theTemplate[1].pValue = &ckTrue;
2569
0
    theTemplate[1].ulValueLen = sizeof(ckTrue);
2570
2571
0
    if (slot == NULL) {
2572
0
        return SECSuccess;
2573
0
    }
2574
2575
0
    perObjectCB.callback = pk11_DoKeys;
2576
0
    perObjectCB.callbackArg = &perKeyCB;
2577
0
    perObjectCB.findTemplate = theTemplate;
2578
0
    perObjectCB.templateCount = templateSize;
2579
0
    perKeyCB.callback = callback;
2580
0
    perKeyCB.callbackArg = arg;
2581
0
    perKeyCB.wincx = NULL;
2582
2583
0
    return PK11_TraverseSlot(slot, &perObjectCB);
2584
0
}
2585
2586
/*
2587
 * return the private key with the given ID
2588
 */
2589
CK_OBJECT_HANDLE
2590
pk11_FindPrivateKeyFromCertID(PK11SlotInfo *slot, SECItem *keyID)
2591
0
{
2592
0
    CK_OBJECT_CLASS privKey = CKO_PRIVATE_KEY;
2593
0
    CK_ATTRIBUTE theTemplate[] = {
2594
0
        { CKA_ID, NULL, 0 },
2595
0
        { CKA_CLASS, NULL, 0 },
2596
0
    };
2597
    /* if you change the array, change the variable below as well */
2598
0
    int tsize = sizeof(theTemplate) / sizeof(theTemplate[0]);
2599
0
    CK_ATTRIBUTE *attrs = theTemplate;
2600
2601
0
    PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len);
2602
0
    attrs++;
2603
0
    PK11_SETATTRS(attrs, CKA_CLASS, &privKey, sizeof(privKey));
2604
2605
0
    return pk11_FindObjectByTemplate(slot, theTemplate, tsize);
2606
0
}
2607
2608
SECKEYPrivateKey *
2609
PK11_FindKeyByKeyID(PK11SlotInfo *slot, SECItem *keyID, void *wincx)
2610
0
{
2611
0
    CK_OBJECT_HANDLE keyHandle;
2612
0
    SECKEYPrivateKey *privKey;
2613
2614
0
    keyHandle = pk11_FindPrivateKeyFromCertID(slot, keyID);
2615
0
    if (keyHandle == CK_INVALID_HANDLE) {
2616
0
        return NULL;
2617
0
    }
2618
0
    privKey = PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyHandle, wincx);
2619
0
    return privKey;
2620
0
}
2621
2622
/*
2623
 * Generate a CKA_ID from the relevant public key data. The CKA_ID is generated
2624
 * from the pubKeyData by SHA1_Hashing it to produce a smaller CKA_ID (to make
2625
 * smart cards happy.
2626
 */
2627
SECItem *
2628
PK11_MakeIDFromPubKey(SECItem *pubKeyData)
2629
0
{
2630
0
    PK11Context *context;
2631
0
    SECItem *certCKA_ID;
2632
0
    SECStatus rv;
2633
2634
0
    if (pubKeyData->len <= SHA1_LENGTH) {
2635
        /* probably an already hashed value. The strongest known public
2636
         * key values <= 160 bits would be less than 40 bit symetric in
2637
         * strength. Don't hash them, just return the value. There are
2638
         * none at the time of this writing supported by previous versions
2639
         * of NSS, so change is binary compatible safe */
2640
0
        return SECITEM_DupItem(pubKeyData);
2641
0
    }
2642
2643
0
    context = PK11_CreateDigestContext(SEC_OID_SHA1);
2644
0
    if (context == NULL) {
2645
0
        return NULL;
2646
0
    }
2647
2648
0
    rv = PK11_DigestBegin(context);
2649
0
    if (rv == SECSuccess) {
2650
0
        rv = PK11_DigestOp(context, pubKeyData->data, pubKeyData->len);
2651
0
    }
2652
0
    if (rv != SECSuccess) {
2653
0
        PK11_DestroyContext(context, PR_TRUE);
2654
0
        return NULL;
2655
0
    }
2656
2657
0
    certCKA_ID = (SECItem *)PORT_Alloc(sizeof(SECItem));
2658
0
    if (certCKA_ID == NULL) {
2659
0
        PK11_DestroyContext(context, PR_TRUE);
2660
0
        return NULL;
2661
0
    }
2662
2663
0
    certCKA_ID->len = SHA1_LENGTH;
2664
0
    certCKA_ID->data = (unsigned char *)PORT_Alloc(certCKA_ID->len);
2665
0
    if (certCKA_ID->data == NULL) {
2666
0
        PORT_Free(certCKA_ID);
2667
0
        PK11_DestroyContext(context, PR_TRUE);
2668
0
        return NULL;
2669
0
    }
2670
2671
0
    rv = PK11_DigestFinal(context, certCKA_ID->data, &certCKA_ID->len,
2672
0
                          SHA1_LENGTH);
2673
0
    PK11_DestroyContext(context, PR_TRUE);
2674
0
    if (rv != SECSuccess) {
2675
0
        SECITEM_FreeItem(certCKA_ID, PR_TRUE);
2676
0
        return NULL;
2677
0
    }
2678
2679
0
    return certCKA_ID;
2680
0
}
2681
2682
/* Looking for PK11_GetKeyIDFromPrivateKey?
2683
 * Call PK11_GetLowLevelKeyIDForPrivateKey instead.
2684
 */
2685
2686
SECItem *
2687
PK11_GetLowLevelKeyIDForPrivateKey(SECKEYPrivateKey *privKey)
2688
0
{
2689
0
    return pk11_GetLowLevelKeyFromHandle(privKey->pkcs11Slot, privKey->pkcs11ID);
2690
0
}
2691
2692
static SECStatus
2693
privateKeyListCallback(SECKEYPrivateKey *key, void *arg)
2694
0
{
2695
0
    SECKEYPrivateKeyList *list = (SECKEYPrivateKeyList *)arg;
2696
0
    return SECKEY_AddPrivateKeyToListTail(list, SECKEY_CopyPrivateKey(key));
2697
0
}
2698
2699
SECKEYPrivateKeyList *
2700
PK11_ListPrivateKeysInSlot(PK11SlotInfo *slot)
2701
0
{
2702
0
    SECStatus status;
2703
0
    SECKEYPrivateKeyList *keys;
2704
2705
0
    keys = SECKEY_NewPrivateKeyList();
2706
0
    if (keys == NULL)
2707
0
        return NULL;
2708
2709
0
    status = PK11_TraversePrivateKeysInSlot(slot, privateKeyListCallback,
2710
0
                                            (void *)keys);
2711
2712
0
    if (status != SECSuccess) {
2713
0
        SECKEY_DestroyPrivateKeyList(keys);
2714
0
        keys = NULL;
2715
0
    }
2716
2717
0
    return keys;
2718
0
}
2719
2720
SECKEYPublicKeyList *
2721
PK11_ListPublicKeysInSlot(PK11SlotInfo *slot, char *nickname)
2722
0
{
2723
0
    CK_ATTRIBUTE findTemp[4];
2724
0
    CK_ATTRIBUTE *attrs;
2725
0
    CK_BBOOL ckTrue = CK_TRUE;
2726
0
    CK_OBJECT_CLASS keyclass = CKO_PUBLIC_KEY;
2727
0
    size_t tsize = 0;
2728
0
    int objCount = 0;
2729
0
    CK_OBJECT_HANDLE *key_ids;
2730
0
    SECKEYPublicKeyList *keys;
2731
0
    int i, len;
2732
2733
0
    attrs = findTemp;
2734
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass));
2735
0
    attrs++;
2736
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue));
2737
0
    attrs++;
2738
0
    if (nickname) {
2739
0
        len = PORT_Strlen(nickname);
2740
0
        PK11_SETATTRS(attrs, CKA_LABEL, nickname, len);
2741
0
        attrs++;
2742
0
    }
2743
0
    tsize = attrs - findTemp;
2744
0
    PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE));
2745
2746
0
    key_ids = pk11_FindObjectsByTemplate(slot, findTemp, tsize, &objCount);
2747
0
    if (key_ids == NULL) {
2748
0
        return NULL;
2749
0
    }
2750
0
    keys = SECKEY_NewPublicKeyList();
2751
0
    if (keys == NULL) {
2752
0
        PORT_Free(key_ids);
2753
0
        return NULL;
2754
0
    }
2755
2756
0
    for (i = 0; i < objCount; i++) {
2757
0
        SECKEYPublicKey *pubKey =
2758
0
            PK11_ExtractPublicKey(slot, nullKey, key_ids[i]);
2759
0
        if (pubKey) {
2760
0
            SECKEY_AddPublicKeyToListTail(keys, pubKey);
2761
0
        }
2762
0
    }
2763
2764
0
    PORT_Free(key_ids);
2765
0
    return keys;
2766
0
}
2767
2768
SECKEYPrivateKeyList *
2769
PK11_ListPrivKeysInSlot(PK11SlotInfo *slot, char *nickname, void *wincx)
2770
0
{
2771
0
    CK_ATTRIBUTE findTemp[4];
2772
0
    CK_ATTRIBUTE *attrs;
2773
0
    CK_BBOOL ckTrue = CK_TRUE;
2774
0
    CK_OBJECT_CLASS keyclass = CKO_PRIVATE_KEY;
2775
0
    size_t tsize = 0;
2776
0
    int objCount = 0;
2777
0
    CK_OBJECT_HANDLE *key_ids;
2778
0
    SECKEYPrivateKeyList *keys;
2779
0
    int i, len;
2780
2781
0
    attrs = findTemp;
2782
0
    PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass));
2783
0
    attrs++;
2784
0
    PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue));
2785
0
    attrs++;
2786
0
    if (nickname) {
2787
0
        len = PORT_Strlen(nickname);
2788
0
        PK11_SETATTRS(attrs, CKA_LABEL, nickname, len);
2789
0
        attrs++;
2790
0
    }
2791
0
    tsize = attrs - findTemp;
2792
0
    PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE));
2793
2794
0
    key_ids = pk11_FindObjectsByTemplate(slot, findTemp, tsize, &objCount);
2795
0
    if (key_ids == NULL) {
2796
0
        return NULL;
2797
0
    }
2798
0
    keys = SECKEY_NewPrivateKeyList();
2799
0
    if (keys == NULL) {
2800
0
        PORT_Free(key_ids);
2801
0
        return NULL;
2802
0
    }
2803
2804
0
    for (i = 0; i < objCount; i++) {
2805
0
        SECKEYPrivateKey *privKey =
2806
0
            PK11_MakePrivKey(slot, nullKey, PR_TRUE, key_ids[i], wincx);
2807
0
        SECKEY_AddPrivateKeyToListTail(keys, privKey);
2808
0
    }
2809
2810
0
    PORT_Free(key_ids);
2811
0
    return keys;
2812
0
}