Coverage Report

Created: 2018-09-25 14:53

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