Coverage Report

Created: 2024-05-20 06:23

/src/nss/lib/pk11wrap/pk11cert.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 manages PKCS #11 instances of certificates.
6
 */
7
8
#include <stddef.h>
9
10
#include "secport.h"
11
#include "seccomon.h"
12
#include "secmod.h"
13
#include "secmodi.h"
14
#include "secmodti.h"
15
#include "pkcs11.h"
16
#include "pk11func.h"
17
#include "cert.h"
18
#include "certi.h"
19
#include "secitem.h"
20
#include "keyhi.h"
21
#include "secoid.h"
22
#include "pkcs7t.h"
23
#include "cmsreclist.h"
24
25
#include "certdb.h"
26
#include "secerr.h"
27
#include "sslerr.h"
28
29
#include "pki3hack.h"
30
#include "dev3hack.h"
31
32
#include "devm.h"
33
#include "nsspki.h"
34
#include "pki.h"
35
#include "pkim.h"
36
#include "pkitm.h"
37
#include "pkistore.h" /* to remove temp cert */
38
#include "devt.h"
39
#include "ckhelper.h"
40
#include "pkcs11uri.h"
41
42
extern const NSSError NSS_ERROR_NOT_FOUND;
43
extern const NSSError NSS_ERROR_INVALID_CERTIFICATE;
44
45
struct nss3_cert_cbstr {
46
    SECStatus (*callback)(CERTCertificate *, void *);
47
    nssList *cached;
48
    void *arg;
49
};
50
51
/* Translate from NSSCertificate to CERTCertificate, then pass the latter
52
 * to a callback.
53
 */
54
static PRStatus
55
convert_cert(NSSCertificate *c, void *arg)
56
0
{
57
0
    CERTCertificate *nss3cert;
58
0
    SECStatus secrv;
59
0
    struct nss3_cert_cbstr *nss3cb = (struct nss3_cert_cbstr *)arg;
60
    /* 'c' is not adopted. caller will free it */
61
0
    nss3cert = STAN_GetCERTCertificate(c);
62
0
    if (!nss3cert)
63
0
        return PR_FAILURE;
64
0
    secrv = (*nss3cb->callback)(nss3cert, nss3cb->arg);
65
0
    return (secrv) ? PR_FAILURE : PR_SUCCESS;
66
0
}
67
68
/*
69
 * build a cert nickname based on the token name and the label of the
70
 * certificate If the label in NULL, build a label based on the ID.
71
 */
72
static int
73
toHex(int x)
74
0
{
75
0
    return (x < 10) ? (x + '0') : (x + 'a' - 10);
76
0
}
77
0
#define MAX_CERT_ID 4
78
0
#define DEFAULT_STRING "Cert ID "
79
static char *
80
pk11_buildNickname(PK11SlotInfo *slot, CK_ATTRIBUTE *cert_label,
81
                   CK_ATTRIBUTE *key_label, CK_ATTRIBUTE *cert_id)
82
0
{
83
0
    int prefixLen = PORT_Strlen(slot->token_name);
84
0
    int suffixLen = 0;
85
0
    char *suffix = NULL;
86
0
    char buildNew[sizeof(DEFAULT_STRING) + MAX_CERT_ID * 2];
87
0
    char *next, *nickname;
88
89
0
    if (cert_label && (cert_label->ulValueLen)) {
90
0
        suffixLen = cert_label->ulValueLen;
91
0
        suffix = (char *)cert_label->pValue;
92
0
    } else if (key_label && (key_label->ulValueLen)) {
93
0
        suffixLen = key_label->ulValueLen;
94
0
        suffix = (char *)key_label->pValue;
95
0
    } else if (cert_id && cert_id->ulValueLen > 0) {
96
0
        int i, first = cert_id->ulValueLen - MAX_CERT_ID;
97
0
        int offset = sizeof(DEFAULT_STRING);
98
0
        char *idValue = (char *)cert_id->pValue;
99
100
0
        PORT_Memcpy(buildNew, DEFAULT_STRING, sizeof(DEFAULT_STRING) - 1);
101
0
        next = buildNew + offset;
102
0
        if (first < 0)
103
0
            first = 0;
104
0
        for (i = first; i < (int)cert_id->ulValueLen; i++) {
105
0
            *next++ = toHex((idValue[i] >> 4) & 0xf);
106
0
            *next++ = toHex(idValue[i] & 0xf);
107
0
        }
108
0
        *next++ = 0;
109
0
        suffix = buildNew;
110
0
        suffixLen = PORT_Strlen(buildNew);
111
0
    } else {
112
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
113
0
        return NULL;
114
0
    }
115
116
    /* if is internal key slot, add code to skip the prefix!! */
117
0
    next = nickname = (char *)PORT_Alloc(prefixLen + 1 + suffixLen + 1);
118
0
    if (nickname == NULL)
119
0
        return NULL;
120
121
0
    PORT_Memcpy(next, slot->token_name, prefixLen);
122
0
    next += prefixLen;
123
0
    *next++ = ':';
124
0
    PORT_Memcpy(next, suffix, suffixLen);
125
0
    next += suffixLen;
126
0
    *next++ = 0;
127
0
    return nickname;
128
0
}
129
130
PRBool
131
PK11_IsUserCert(PK11SlotInfo *slot, CERTCertificate *cert,
132
                CK_OBJECT_HANDLE certID)
133
0
{
134
0
    CK_OBJECT_CLASS theClass;
135
136
0
    if (slot == NULL)
137
0
        return PR_FALSE;
138
0
    if (cert == NULL)
139
0
        return PR_FALSE;
140
141
0
    theClass = CKO_PRIVATE_KEY;
142
0
    if (pk11_LoginStillRequired(slot, NULL)) {
143
0
        theClass = CKO_PUBLIC_KEY;
144
0
    }
145
0
    if (PK11_MatchItem(slot, certID, theClass) != CK_INVALID_HANDLE) {
146
0
        return PR_TRUE;
147
0
    }
148
149
0
    if (theClass == CKO_PUBLIC_KEY) {
150
0
        SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert);
151
0
        CK_ATTRIBUTE theTemplate;
152
153
0
        if (pubKey == NULL) {
154
0
            return PR_FALSE;
155
0
        }
156
157
0
        PK11_SETATTRS(&theTemplate, 0, NULL, 0);
158
0
        switch (pubKey->keyType) {
159
0
            case rsaKey:
160
0
            case rsaPssKey:
161
0
            case rsaOaepKey:
162
0
                PK11_SETATTRS(&theTemplate, CKA_MODULUS, pubKey->u.rsa.modulus.data,
163
0
                              pubKey->u.rsa.modulus.len);
164
0
                break;
165
0
            case dsaKey:
166
0
                PK11_SETATTRS(&theTemplate, CKA_VALUE, pubKey->u.dsa.publicValue.data,
167
0
                              pubKey->u.dsa.publicValue.len);
168
0
                break;
169
0
            case dhKey:
170
0
                PK11_SETATTRS(&theTemplate, CKA_VALUE, pubKey->u.dh.publicValue.data,
171
0
                              pubKey->u.dh.publicValue.len);
172
0
                break;
173
0
            case ecKey:
174
0
            case edKey:
175
0
                PK11_SETATTRS(&theTemplate, CKA_EC_POINT,
176
0
                              pubKey->u.ec.publicValue.data,
177
0
                              pubKey->u.ec.publicValue.len);
178
0
                break;
179
0
            case keaKey:
180
0
            case fortezzaKey:
181
0
            case kyberKey:
182
0
            case nullKey:
183
                /* fall through and return false */
184
0
                break;
185
0
        }
186
187
0
        if (theTemplate.ulValueLen == 0) {
188
0
            SECKEY_DestroyPublicKey(pubKey);
189
0
            return PR_FALSE;
190
0
        }
191
0
        if (pubKey->keyType != ecKey && pubKey->keyType != edKey) {
192
0
            pk11_SignedToUnsigned(&theTemplate);
193
0
        }
194
0
        if (pk11_FindObjectByTemplate(slot, &theTemplate, 1) != CK_INVALID_HANDLE) {
195
0
            SECKEY_DestroyPublicKey(pubKey);
196
0
            return PR_TRUE;
197
0
        }
198
0
        SECKEY_DestroyPublicKey(pubKey);
199
0
    }
200
0
    return PR_FALSE;
201
0
}
202
203
/*
204
 * Check out if a cert has ID of zero. This is a magic ID that tells
205
 * NSS that this cert may be an automagically trusted cert.
206
 * The Cert has to be self signed as well. That check is done elsewhere.
207
 *
208
 */
209
PRBool
210
pk11_isID0(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID)
211
0
{
212
0
    CK_ATTRIBUTE keyID = { CKA_ID, NULL, 0 };
213
0
    PRBool isZero = PR_FALSE;
214
0
    int i;
215
0
    CK_RV crv;
216
217
0
    crv = PK11_GetAttributes(NULL, slot, certID, &keyID, 1);
218
0
    if (crv != CKR_OK) {
219
0
        return isZero;
220
0
    }
221
222
0
    if (keyID.ulValueLen != 0) {
223
0
        char *value = (char *)keyID.pValue;
224
0
        isZero = PR_TRUE; /* ID exists, may be zero */
225
0
        for (i = 0; i < (int)keyID.ulValueLen; i++) {
226
0
            if (value[i] != 0) {
227
0
                isZero = PR_FALSE; /* nope */
228
0
                break;
229
0
            }
230
0
        }
231
0
    }
232
0
    PORT_Free(keyID.pValue);
233
0
    return isZero;
234
0
}
235
236
/*
237
 * Create an NSSCertificate from a slot/certID pair, return it as a
238
 * CERTCertificate.  Optionally, output the nickname string.
239
 */
240
static CERTCertificate *
241
pk11_fastCert(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID,
242
              CK_ATTRIBUTE *privateLabel, char **nickptr)
243
0
{
244
0
    NSSCertificate *c;
245
0
    nssCryptokiObject *co = NULL;
246
0
    nssPKIObject *pkio;
247
0
    NSSTrustDomain *td = STAN_GetDefaultTrustDomain();
248
249
    /* Get the cryptoki object from the handle */
250
0
    NSSToken *token = PK11Slot_GetNSSToken(slot);
251
0
    if (!token || !token->defaultSession) {
252
0
        (void)nssToken_Destroy(token); /* null token is ok */
253
0
        PORT_SetError(SEC_ERROR_NO_TOKEN);
254
0
        return NULL;
255
0
    }
256
0
    co = nssCryptokiObject_Create(token, token->defaultSession, certID);
257
0
    (void)nssToken_Destroy(token);
258
0
    if (!co) {
259
0
        return NULL;
260
0
    }
261
262
    /* Create a PKI object from the cryptoki instance */
263
0
    pkio = nssPKIObject_Create(NULL, co, td, NULL, nssPKIMonitor);
264
0
    if (!pkio) {
265
0
        nssCryptokiObject_Destroy(co);
266
0
        return NULL;
267
0
    }
268
269
    /* Create a certificate */
270
0
    c = nssCertificate_Create(pkio);
271
0
    if (!c) {
272
0
        nssPKIObject_Destroy(pkio);
273
0
        return NULL;
274
0
    }
275
276
    /* Build and output a nickname, if desired.
277
     * This must be done before calling nssTrustDomain_AddCertsToCache
278
     * because that function may destroy c, pkio and co!
279
     */
280
0
    if ((nickptr) && (co->label)) {
281
0
        CK_ATTRIBUTE label, id;
282
283
0
        label.type = CKA_LABEL;
284
0
        label.pValue = co->label;
285
0
        label.ulValueLen = PORT_Strlen(co->label);
286
287
0
        id.type = CKA_ID;
288
0
        id.pValue = c->id.data;
289
0
        id.ulValueLen = c->id.size;
290
291
0
        *nickptr = pk11_buildNickname(slot, &label, privateLabel, &id);
292
0
    }
293
294
    /* This function may destroy the cert in "c" and all its subordinate
295
     * structures, and replace the value in "c" with the address of a
296
     * different NSSCertificate that it found in the cache.
297
     * Presumably, the nickname which we just output above remains valid. :)
298
     */
299
0
    (void)nssTrustDomain_AddCertsToCache(td, &c, 1);
300
0
    return STAN_GetCERTCertificateOrRelease(c);
301
0
}
302
303
/*
304
 * Build an CERTCertificate structure from a PKCS#11 object ID.... certID
305
 * Must be a CertObject. This code does not explicitly checks that.
306
 */
307
CERTCertificate *
308
PK11_MakeCertFromHandle(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID,
309
                        CK_ATTRIBUTE *privateLabel)
310
0
{
311
0
    char *nickname = NULL;
312
0
    CERTCertificate *cert = NULL;
313
0
    CERTCertTrust *trust;
314
315
0
    if (slot == NULL || certID == CK_INVALID_HANDLE) {
316
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
317
0
        return NULL;
318
0
    }
319
320
0
    cert = pk11_fastCert(slot, certID, privateLabel, &nickname);
321
0
    if (cert == NULL) {
322
0
        goto loser;
323
0
    }
324
325
0
    if (nickname) {
326
0
        if (cert->nickname != NULL) {
327
0
            cert->dbnickname = cert->nickname;
328
0
        }
329
0
        cert->nickname = PORT_ArenaStrdup(cert->arena, nickname);
330
0
        PORT_Free(nickname);
331
0
        nickname = NULL;
332
0
    }
333
334
    /* remember where this cert came from.... If we have just looked
335
     * it up from the database and it already has a slot, don't add a new
336
     * one. */
337
0
    if (cert->slot == NULL) {
338
0
        cert->slot = PK11_ReferenceSlot(slot);
339
0
        cert->pkcs11ID = certID;
340
0
        cert->ownSlot = PR_TRUE;
341
0
        cert->series = slot->series;
342
0
    }
343
344
0
    trust = (CERTCertTrust *)PORT_ArenaAlloc(cert->arena, sizeof(CERTCertTrust));
345
0
    if (trust == NULL)
346
0
        goto loser;
347
0
    PORT_Memset(trust, 0, sizeof(CERTCertTrust));
348
349
0
    if (!pk11_HandleTrustObject(slot, cert, trust)) {
350
0
        unsigned int type;
351
352
        /* build some cert trust flags */
353
0
        if (CERT_IsCACert(cert, &type)) {
354
0
            unsigned int trustflags = CERTDB_VALID_CA;
355
356
            /* Allow PKCS #11 modules to give us trusted CA's. We only accept
357
             * valid CA's which are self-signed here. They must have an object
358
             * ID of '0'.  */
359
0
            if (pk11_isID0(slot, certID) &&
360
0
                cert->isRoot) {
361
0
                trustflags |= CERTDB_TRUSTED_CA;
362
                /* is the slot a fortezza card? allow the user or
363
                 * admin to turn on objectSigning, but don't turn
364
                 * full trust on explicitly */
365
0
                if (PK11_DoesMechanism(slot, CKM_KEA_KEY_DERIVE)) {
366
0
                    trust->objectSigningFlags |= CERTDB_VALID_CA;
367
0
                }
368
0
            }
369
0
            if ((type & NS_CERT_TYPE_SSL_CA) == NS_CERT_TYPE_SSL_CA) {
370
0
                trust->sslFlags |= trustflags;
371
0
            }
372
0
            if ((type & NS_CERT_TYPE_EMAIL_CA) == NS_CERT_TYPE_EMAIL_CA) {
373
0
                trust->emailFlags |= trustflags;
374
0
            }
375
0
            if ((type & NS_CERT_TYPE_OBJECT_SIGNING_CA) == NS_CERT_TYPE_OBJECT_SIGNING_CA) {
376
0
                trust->objectSigningFlags |= trustflags;
377
0
            }
378
0
        }
379
0
    }
380
381
0
    if (PK11_IsUserCert(slot, cert, certID)) {
382
0
        trust->sslFlags |= CERTDB_USER;
383
0
        trust->emailFlags |= CERTDB_USER;
384
        /*    trust->objectSigningFlags |= CERTDB_USER; */
385
0
    }
386
0
    CERT_LockCertTrust(cert);
387
0
    cert->trust = trust;
388
0
    CERT_UnlockCertTrust(cert);
389
390
0
    return cert;
391
392
0
loser:
393
0
    if (nickname)
394
0
        PORT_Free(nickname);
395
0
    if (cert)
396
0
        CERT_DestroyCertificate(cert);
397
0
    return NULL;
398
0
}
399
400
/*
401
 * Build get a certificate from a private key
402
 */
403
CERTCertificate *
404
PK11_GetCertFromPrivateKey(SECKEYPrivateKey *privKey)
405
0
{
406
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
407
0
    CK_OBJECT_HANDLE handle = privKey->pkcs11ID;
408
0
    CK_OBJECT_HANDLE certID =
409
0
        PK11_MatchItem(slot, handle, CKO_CERTIFICATE);
410
0
    CERTCertificate *cert;
411
412
0
    if (certID == CK_INVALID_HANDLE) {
413
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
414
0
        return NULL;
415
0
    }
416
0
    cert = PK11_MakeCertFromHandle(slot, certID, NULL);
417
0
    return (cert);
418
0
}
419
420
CK_OBJECT_HANDLE *
421
PK11_FindCertHandlesForKeyHandle(PK11SlotInfo *slot, CK_OBJECT_HANDLE keyHandle,
422
                                 int *certHandleCountOut)
423
0
{
424
0
    if (!slot || !certHandleCountOut || keyHandle == CK_INVALID_HANDLE) {
425
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
426
0
        return NULL;
427
0
    }
428
429
0
    PORTCheapArenaPool arena;
430
0
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
431
0
    CK_ATTRIBUTE idTemplate[] = {
432
0
        { CKA_ID, NULL, 0 },
433
0
    };
434
0
    const int idAttrCount = sizeof(idTemplate) / sizeof(idTemplate[0]);
435
0
    CK_RV crv = PK11_GetAttributes(&arena.arena, slot, keyHandle, idTemplate, idAttrCount);
436
0
    if (crv != CKR_OK) {
437
0
        PORT_DestroyCheapArena(&arena);
438
0
        PORT_SetError(PK11_MapError(crv));
439
0
        return NULL;
440
0
    }
441
442
0
    if ((idTemplate[0].ulValueLen == 0) || (idTemplate[0].ulValueLen == -1)) {
443
0
        PORT_DestroyCheapArena(&arena);
444
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
445
0
        return NULL;
446
0
    }
447
448
0
    CK_OBJECT_CLASS searchClass = CKO_CERTIFICATE;
449
0
    CK_ATTRIBUTE searchTemplate[] = {
450
0
        idTemplate[0],
451
0
        { CKA_CLASS, &searchClass, sizeof(searchClass) }
452
0
    };
453
0
    const size_t searchAttrCount = sizeof(searchTemplate) / sizeof(searchTemplate[0]);
454
0
    CK_OBJECT_HANDLE *ids = pk11_FindObjectsByTemplate(slot, searchTemplate, searchAttrCount, certHandleCountOut);
455
456
0
    PORT_DestroyCheapArena(&arena);
457
0
    return ids;
458
0
}
459
460
CERTCertList *
461
PK11_GetCertsMatchingPrivateKey(SECKEYPrivateKey *privKey)
462
0
{
463
0
    if (!privKey) {
464
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
465
0
        return NULL;
466
0
    }
467
0
    CERTCertList *certs = CERT_NewCertList();
468
0
    if (!certs) {
469
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
470
0
        return NULL;
471
0
    }
472
0
    PK11SlotInfo *slot = privKey->pkcs11Slot;
473
0
    CK_OBJECT_HANDLE handle = privKey->pkcs11ID;
474
0
    CK_OBJECT_HANDLE certID = PK11_MatchItem(slot, handle, CKO_CERTIFICATE);
475
    /* If we can't get a matching certID, there are no matching certificates,
476
     * which is not an error. */
477
0
    if (certID == CK_INVALID_HANDLE) {
478
0
        return certs;
479
0
    }
480
0
    int certHandleCount = 0;
481
0
    CK_OBJECT_HANDLE *certHandles = PK11_FindCertHandlesForKeyHandle(slot, handle, &certHandleCount);
482
0
    if (!certHandles) {
483
        /* If certHandleCount is 0, there are no matching certificates, which is
484
         * not an error. */
485
0
        if (certHandleCount == 0) {
486
0
            return certs;
487
0
        }
488
0
        CERT_DestroyCertList(certs);
489
0
        return NULL;
490
0
    }
491
0
    int i;
492
0
    for (i = 0; i < certHandleCount; i++) {
493
0
        CERTCertificate *cert = PK11_MakeCertFromHandle(slot, certHandles[i], NULL);
494
        /* If PK11_MakeCertFromHandle fails for one handle, optimistically
495
           assume other handles may succeed (i.e. this is best-effort). */
496
0
        if (!cert) {
497
0
            continue;
498
0
        }
499
0
        if (CERT_AddCertToListTail(certs, cert) != SECSuccess) {
500
0
            CERT_DestroyCertificate(cert);
501
0
        }
502
0
    }
503
0
    PORT_Free(certHandles);
504
0
    return certs;
505
0
}
506
507
/*
508
 * delete a cert and it's private key (if no other certs are pointing to the
509
 * private key.
510
 */
511
SECStatus
512
PK11_DeleteTokenCertAndKey(CERTCertificate *cert, void *wincx)
513
0
{
514
0
    SECKEYPrivateKey *privKey = PK11_FindKeyByAnyCert(cert, wincx);
515
0
    CK_OBJECT_HANDLE pubKey;
516
0
    PK11SlotInfo *slot = NULL;
517
518
0
    pubKey = pk11_FindPubKeyByAnyCert(cert, &slot, wincx);
519
0
    if (privKey) {
520
        /* For 3.4, utilize the generic cert delete function */
521
0
        SEC_DeletePermCertificate(cert);
522
0
        PK11_DeleteTokenPrivateKey(privKey, PR_FALSE);
523
0
    }
524
0
    if ((pubKey != CK_INVALID_HANDLE) && (slot != NULL)) {
525
0
        PK11_DestroyTokenObject(slot, pubKey);
526
0
        PK11_FreeSlot(slot);
527
0
    }
528
0
    return SECSuccess;
529
0
}
530
531
/*
532
 * cert callback structure
533
 */
534
typedef struct pk11DoCertCallbackStr {
535
    SECStatus (*callback)(PK11SlotInfo *slot, CERTCertificate *, void *);
536
    SECStatus (*noslotcallback)(CERTCertificate *, void *);
537
    SECStatus (*itemcallback)(CERTCertificate *, SECItem *, void *);
538
    void *callbackArg;
539
} pk11DoCertCallback;
540
541
typedef struct pk11CertCallbackStr {
542
    SECStatus (*callback)(CERTCertificate *, SECItem *, void *);
543
    void *callbackArg;
544
} pk11CertCallback;
545
546
struct fake_der_cb_argstr {
547
    SECStatus (*callback)(CERTCertificate *, SECItem *, void *);
548
    void *arg;
549
};
550
551
static SECStatus
552
fake_der_cb(CERTCertificate *c, void *a)
553
0
{
554
0
    struct fake_der_cb_argstr *fda = (struct fake_der_cb_argstr *)a;
555
0
    return (*fda->callback)(c, &c->derCert, fda->arg);
556
0
}
557
558
/*
559
 * Extract all the certs on a card from a slot.
560
 */
561
SECStatus
562
PK11_TraverseSlotCerts(SECStatus (*callback)(CERTCertificate *, SECItem *, void *),
563
                       void *arg, void *wincx)
564
1
{
565
1
    NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
566
1
    struct fake_der_cb_argstr fda;
567
1
    struct nss3_cert_cbstr pk11cb;
568
569
    /* authenticate to the tokens first */
570
1
    (void)pk11_TraverseAllSlots(NULL, NULL, PR_TRUE, wincx);
571
572
1
    fda.callback = callback;
573
1
    fda.arg = arg;
574
1
    pk11cb.callback = fake_der_cb;
575
1
    pk11cb.arg = &fda;
576
1
    NSSTrustDomain_TraverseCertificates(defaultTD, convert_cert, &pk11cb);
577
1
    return SECSuccess;
578
1
}
579
580
static void
581
transfer_token_certs_to_collection(nssList *certList, NSSToken *token,
582
                                   nssPKIObjectCollection *collection)
583
0
{
584
0
    NSSCertificate **certs;
585
0
    PRUint32 i, count;
586
0
    NSSToken **tokens, **tp;
587
0
    count = nssList_Count(certList);
588
0
    if (count == 0) {
589
0
        return;
590
0
    }
591
0
    certs = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
592
0
    if (!certs) {
593
0
        return;
594
0
    }
595
0
    nssList_GetArray(certList, (void **)certs, count);
596
0
    for (i = 0; i < count; i++) {
597
0
        tokens = nssPKIObject_GetTokens(&certs[i]->object, NULL);
598
0
        if (tokens) {
599
0
            for (tp = tokens; *tp; tp++) {
600
0
                if (*tp == token) {
601
0
                    nssPKIObjectCollection_AddObject(collection,
602
0
                                                     (nssPKIObject *)certs[i]);
603
0
                }
604
0
            }
605
0
            nssTokenArray_Destroy(tokens);
606
0
        }
607
0
        CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(certs[i]));
608
0
    }
609
0
    nss_ZFreeIf(certs);
610
0
}
611
612
static void
613
transfer_uri_certs_to_collection(nssList *certList, PK11URI *uri,
614
                                 nssPKIObjectCollection *collection)
615
0
{
616
617
0
    NSSCertificate **certs;
618
0
    PRUint32 i, count;
619
0
    NSSToken **tokens, **tp;
620
0
    PK11SlotInfo *slot;
621
0
    const SECItem *id;
622
623
0
    count = nssList_Count(certList);
624
0
    if (count == 0) {
625
0
        return;
626
0
    }
627
0
    certs = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
628
0
    if (!certs) {
629
0
        return;
630
0
    }
631
0
    id = PK11URI_GetPathAttributeItem(uri, PK11URI_PATTR_ID);
632
0
    nssList_GetArray(certList, (void **)certs, count);
633
0
    for (i = 0; i < count; i++) {
634
        /*
635
         * Filter the subject matched certs based on the
636
         * CKA_ID from the URI
637
         */
638
0
        if (id && (id->len != certs[i]->id.size ||
639
0
                   memcmp(id, certs[i]->id.data, certs[i]->id.size)))
640
0
            continue;
641
0
        tokens = nssPKIObject_GetTokens(&certs[i]->object, NULL);
642
0
        if (tokens) {
643
0
            for (tp = tokens; *tp; tp++) {
644
0
                const char *value;
645
0
                slot = (*tp)->pk11slot;
646
647
0
                value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_TOKEN);
648
0
                if (value &&
649
0
                    !pk11_MatchString(value,
650
0
                                      (char *)slot->tokenInfo.label,
651
0
                                      sizeof(slot->tokenInfo.label))) {
652
0
                    continue;
653
0
                }
654
655
0
                value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_MANUFACTURER);
656
0
                if (value &&
657
0
                    !pk11_MatchString(value,
658
0
                                      (char *)slot->tokenInfo.manufacturerID,
659
0
                                      sizeof(slot->tokenInfo.manufacturerID))) {
660
0
                    continue;
661
0
                }
662
663
0
                value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_MODEL);
664
0
                if (value &&
665
0
                    !pk11_MatchString(value,
666
0
                                      (char *)slot->tokenInfo.model,
667
0
                                      sizeof(slot->tokenInfo.model))) {
668
0
                    continue;
669
0
                }
670
671
0
                value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_SERIAL);
672
0
                if (value &&
673
0
                    !pk11_MatchString(value,
674
0
                                      (char *)slot->tokenInfo.serialNumber,
675
0
                                      sizeof(slot->tokenInfo.serialNumber))) {
676
0
                    continue;
677
0
                }
678
679
0
                nssPKIObjectCollection_AddObject(collection,
680
0
                                                 (nssPKIObject *)certs[i]);
681
0
                break;
682
0
            }
683
0
            nssTokenArray_Destroy(tokens);
684
0
        }
685
0
        CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(certs[i]));
686
0
    }
687
0
    nss_ZFreeIf(certs);
688
0
}
689
690
static NSSCertificate **
691
find_certs_from_uri(const char *uriString, void *wincx)
692
0
{
693
0
    PK11URI *uri = NULL;
694
0
    CK_ATTRIBUTE attributes[10];
695
0
    CK_ULONG nattributes = 0;
696
0
    const SECItem *id;
697
0
    const char *label, *type;
698
0
    PK11SlotInfo *slotinfo;
699
0
    nssCryptokiObject **instances;
700
0
    PRStatus status;
701
0
    nssPKIObjectCollection *collection = NULL;
702
0
    NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
703
0
    NSSCertificate **certs = NULL;
704
0
    nssList *certList = NULL;
705
0
    SECStatus rv;
706
0
    CK_OBJECT_CLASS s_class = CKO_CERTIFICATE;
707
0
    static const CK_BBOOL s_true = CK_TRUE;
708
0
    NSSToken **tokens, **tok;
709
710
0
    uri = PK11URI_ParseURI(uriString);
711
0
    if (uri == NULL) {
712
0
        goto loser;
713
0
    }
714
715
0
    collection = nssCertificateCollection_Create(defaultTD, NULL);
716
0
    if (!collection) {
717
0
        goto loser;
718
0
    }
719
0
    certList = nssList_Create(NULL, PR_FALSE);
720
0
    if (!certList) {
721
0
        goto loser;
722
0
    }
723
724
    /* if the "type" attribute is specified its value must be "cert" */
725
0
    type = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_TYPE);
726
0
    if (type && strcmp(type, "cert")) {
727
0
        goto loser;
728
0
    }
729
730
0
    label = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_OBJECT);
731
0
    if (label) {
732
0
        (void)nssTrustDomain_GetCertsForNicknameFromCache(defaultTD,
733
0
                                                          label,
734
0
                                                          certList);
735
0
    } else {
736
0
        (void)nssTrustDomain_GetCertsFromCache(defaultTD, certList);
737
0
    }
738
739
0
    transfer_uri_certs_to_collection(certList, uri, collection);
740
741
    /* add the CKA_CLASS and CKA_TOKEN attributes manually */
742
0
    attributes[nattributes].type = CKA_CLASS;
743
0
    attributes[nattributes].pValue = (void *)&s_class;
744
0
    attributes[nattributes].ulValueLen = sizeof(s_class);
745
0
    nattributes++;
746
747
0
    attributes[nattributes].type = CKA_TOKEN;
748
0
    attributes[nattributes].pValue = (void *)&s_true;
749
0
    attributes[nattributes].ulValueLen = sizeof(s_true);
750
0
    nattributes++;
751
752
0
    if (label) {
753
0
        attributes[nattributes].type = CKA_LABEL;
754
0
        attributes[nattributes].pValue = (void *)label;
755
0
        attributes[nattributes].ulValueLen = strlen(label);
756
0
        nattributes++;
757
0
    }
758
759
0
    id = PK11URI_GetPathAttributeItem(uri, PK11URI_PATTR_ID);
760
0
    if (id) {
761
0
        attributes[nattributes].type = CKA_ID;
762
0
        attributes[nattributes].pValue = (void *)id->data;
763
0
        attributes[nattributes].ulValueLen = id->len;
764
0
        nattributes++;
765
0
    }
766
767
0
    tokens = NSSTrustDomain_FindTokensByURI(defaultTD, uri);
768
0
    for (tok = tokens; tok && *tok; tok++) {
769
0
        if (nssToken_IsPresent(*tok)) {
770
0
            slotinfo = (*tok)->pk11slot;
771
772
0
            rv = pk11_AuthenticateUnfriendly(slotinfo, PR_TRUE, wincx);
773
0
            if (rv != SECSuccess) {
774
0
                continue;
775
0
            }
776
0
            instances = nssToken_FindObjectsByTemplate(*tok, NULL,
777
0
                                                       attributes,
778
0
                                                       nattributes,
779
0
                                                       0, &status);
780
0
            nssPKIObjectCollection_AddInstances(collection, instances, 0);
781
0
            nss_ZFreeIf(instances);
782
0
        }
783
0
        (void)nssToken_Destroy(*tok);
784
0
    }
785
0
    nss_ZFreeIf(tokens);
786
0
    nssList_Destroy(certList);
787
0
    certs = nssPKIObjectCollection_GetCertificates(collection, NULL, 0, NULL);
788
789
0
loser:
790
0
    if (collection) {
791
0
        nssPKIObjectCollection_Destroy(collection);
792
0
    }
793
0
    if (uri) {
794
0
        PK11URI_DestroyURI(uri);
795
0
    }
796
0
    return certs;
797
0
}
798
799
CERTCertificate *
800
PK11_FindCertFromURI(const char *uri, void *wincx)
801
0
{
802
0
    static const NSSUsage usage = { PR_TRUE /* ... */ };
803
0
    NSSCertificate *cert = NULL;
804
0
    NSSCertificate **certs = NULL;
805
0
    CERTCertificate *rvCert = NULL;
806
807
0
    certs = find_certs_from_uri(uri, wincx);
808
0
    if (certs) {
809
0
        cert = nssCertificateArray_FindBestCertificate(certs, NULL,
810
0
                                                       &usage, NULL);
811
0
        if (cert) {
812
0
            rvCert = STAN_GetCERTCertificateOrRelease(cert);
813
0
        }
814
0
        nssCertificateArray_Destroy(certs);
815
0
    }
816
0
    return rvCert;
817
0
}
818
819
CERTCertList *
820
PK11_FindCertsFromURI(const char *uri, void *wincx)
821
0
{
822
0
    int i;
823
0
    CERTCertList *certList = NULL;
824
0
    NSSCertificate **foundCerts;
825
0
    NSSCertificate *c;
826
827
0
    foundCerts = find_certs_from_uri(uri, wincx);
828
0
    if (foundCerts) {
829
0
        PRTime now = PR_Now();
830
0
        certList = CERT_NewCertList();
831
0
        for (i = 0, c = *foundCerts; c; c = foundCerts[++i]) {
832
0
            if (certList) {
833
0
                CERTCertificate *certCert = STAN_GetCERTCertificateOrRelease(c);
834
                /* c may be invalid after this, don't reference it */
835
0
                if (certCert) {
836
                    /* CERT_AddCertToListSorted adopts certCert  */
837
0
                    CERT_AddCertToListSorted(certList, certCert,
838
0
                                             CERT_SortCBValidity, &now);
839
0
                }
840
0
            } else {
841
0
                nssCertificate_Destroy(c);
842
0
            }
843
0
        }
844
0
        if (certList && CERT_LIST_HEAD(certList) == NULL) {
845
0
            CERT_DestroyCertList(certList);
846
0
            certList = NULL;
847
0
        }
848
        /* all the certs have been adopted or freed, free the  raw array */
849
0
        nss_ZFreeIf(foundCerts);
850
0
    }
851
0
    return certList;
852
0
}
853
854
static NSSCertificate **
855
find_certs_from_nickname(const char *nickname, void *wincx)
856
0
{
857
0
    PRStatus status;
858
0
    NSSCertificate **certs = NULL;
859
0
    NSSToken *token = NULL;
860
0
    NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
861
0
    PK11SlotInfo *slot = NULL;
862
0
    SECStatus rv;
863
0
    char *nickCopy;
864
0
    char *delimit = NULL;
865
0
    char *tokenName;
866
867
0
    if (!PORT_Strncasecmp(nickname, "pkcs11:", strlen("pkcs11:"))) {
868
0
        certs = find_certs_from_uri(nickname, wincx);
869
0
        if (certs)
870
0
            return certs;
871
0
    }
872
0
    nickCopy = PORT_Strdup(nickname);
873
0
    if (!nickCopy) {
874
        /* error code is set */
875
0
        return NULL;
876
0
    }
877
0
    if ((delimit = PORT_Strchr(nickCopy, ':')) != NULL) {
878
0
        tokenName = nickCopy;
879
0
        nickname = delimit + 1;
880
0
        *delimit = '\0';
881
        /* find token by name */
882
0
        token = NSSTrustDomain_FindTokenByName(defaultTD, (NSSUTF8 *)tokenName);
883
0
        if (token) {
884
0
            slot = PK11_ReferenceSlot(token->pk11slot);
885
0
        } else {
886
0
            PORT_SetError(SEC_ERROR_NO_TOKEN);
887
0
        }
888
0
        *delimit = ':';
889
0
    } else {
890
0
        slot = PK11_GetInternalKeySlot();
891
0
        token = PK11Slot_GetNSSToken(slot);
892
0
        if (!token) {
893
0
            PORT_SetError(SEC_ERROR_NO_TOKEN);
894
0
        }
895
0
    }
896
0
    if (token) {
897
0
        nssList *certList;
898
0
        nssCryptokiObject **instances;
899
0
        nssPKIObjectCollection *collection;
900
0
        nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
901
0
        if (!PK11_IsPresent(slot)) {
902
0
            goto loser;
903
0
        }
904
0
        rv = pk11_AuthenticateUnfriendly(slot, PR_TRUE, wincx);
905
0
        if (rv != SECSuccess) {
906
0
            goto loser;
907
0
        }
908
0
        collection = nssCertificateCollection_Create(defaultTD, NULL);
909
0
        if (!collection) {
910
0
            goto loser;
911
0
        }
912
0
        certList = nssList_Create(NULL, PR_FALSE);
913
0
        if (!certList) {
914
0
            nssPKIObjectCollection_Destroy(collection);
915
0
            goto loser;
916
0
        }
917
0
        (void)nssTrustDomain_GetCertsForNicknameFromCache(defaultTD,
918
0
                                                          nickname,
919
0
                                                          certList);
920
0
        transfer_token_certs_to_collection(certList, token, collection);
921
0
        instances = nssToken_FindCertificatesByNickname(token,
922
0
                                                        NULL,
923
0
                                                        nickname,
924
0
                                                        tokenOnly,
925
0
                                                        0,
926
0
                                                        &status);
927
0
        nssPKIObjectCollection_AddInstances(collection, instances, 0);
928
0
        nss_ZFreeIf(instances);
929
        /* if it wasn't found, repeat the process for email address */
930
0
        if (nssPKIObjectCollection_Count(collection) == 0 &&
931
0
            PORT_Strchr(nickname, '@') != NULL) {
932
0
            char *lowercaseName = CERT_FixupEmailAddr(nickname);
933
0
            if (lowercaseName) {
934
0
                (void)nssTrustDomain_GetCertsForEmailAddressFromCache(defaultTD,
935
0
                                                                      lowercaseName,
936
0
                                                                      certList);
937
0
                transfer_token_certs_to_collection(certList, token, collection);
938
0
                instances = nssToken_FindCertificatesByEmail(token,
939
0
                                                             NULL,
940
0
                                                             lowercaseName,
941
0
                                                             tokenOnly,
942
0
                                                             0,
943
0
                                                             &status);
944
0
                nssPKIObjectCollection_AddInstances(collection, instances, 0);
945
0
                nss_ZFreeIf(instances);
946
0
                PORT_Free(lowercaseName);
947
0
            }
948
0
        }
949
0
        certs = nssPKIObjectCollection_GetCertificates(collection,
950
0
                                                       NULL, 0, NULL);
951
0
        nssPKIObjectCollection_Destroy(collection);
952
0
        nssList_Destroy(certList);
953
0
    }
954
0
loser:
955
0
    if (token) {
956
0
        (void)nssToken_Destroy(token);
957
0
    }
958
0
    if (slot) {
959
0
        PK11_FreeSlot(slot);
960
0
    }
961
0
    if (nickCopy)
962
0
        PORT_Free(nickCopy);
963
0
    return certs;
964
0
}
965
966
CERTCertificate *
967
PK11_FindCertFromNickname(const char *nickname, void *wincx)
968
0
{
969
0
    CERTCertificate *rvCert = NULL;
970
0
    NSSCertificate *cert = NULL;
971
0
    NSSCertificate **certs = NULL;
972
0
    static const NSSUsage usage = { PR_TRUE /* ... */ };
973
974
0
    certs = find_certs_from_nickname(nickname, wincx);
975
0
    if (certs) {
976
0
        cert = nssCertificateArray_FindBestCertificate(certs, NULL,
977
0
                                                       &usage, NULL);
978
0
        if (cert) {
979
0
            rvCert = STAN_GetCERTCertificateOrRelease(cert);
980
0
        }
981
0
        nssCertificateArray_Destroy(certs);
982
0
    }
983
0
    return rvCert;
984
0
}
985
986
/* Traverse slots callback */
987
typedef struct FindCertsEmailArgStr {
988
    char *email;
989
    CERTCertList *certList;
990
} FindCertsEmailArg;
991
992
SECStatus
993
FindCertsEmailCallback(CERTCertificate *cert, SECItem *item, void *arg)
994
0
{
995
0
    FindCertsEmailArg *cbparam = (FindCertsEmailArg *)arg;
996
0
    const char *cert_email = CERT_GetFirstEmailAddress(cert);
997
0
    PRBool found = PR_FALSE;
998
999
    /* Email address present in certificate? */
1000
0
    if (cert_email == NULL) {
1001
0
        return SECSuccess;
1002
0
    }
1003
1004
    /* Parameter correctly set? */
1005
0
    if (cbparam->email == NULL) {
1006
0
        return SECFailure;
1007
0
    }
1008
1009
    /* Loop over all email addresses */
1010
0
    do {
1011
0
        if (!strcmp(cert_email, cbparam->email)) {
1012
            /* found one matching email address */
1013
0
            PRTime now = PR_Now();
1014
0
            found = PR_TRUE;
1015
0
            CERT_AddCertToListSorted(cbparam->certList,
1016
0
                                     CERT_DupCertificate(cert),
1017
0
                                     CERT_SortCBValidity, &now);
1018
0
        }
1019
0
        cert_email = CERT_GetNextEmailAddress(cert, cert_email);
1020
0
    } while (cert_email && !found);
1021
1022
0
    return SECSuccess;
1023
0
}
1024
1025
/* Find all certificates with matching email address */
1026
CERTCertList *
1027
PK11_FindCertsFromEmailAddress(const char *email, void *wincx)
1028
0
{
1029
0
    FindCertsEmailArg cbparam;
1030
0
    SECStatus rv;
1031
1032
0
    cbparam.certList = CERT_NewCertList();
1033
0
    if (cbparam.certList == NULL) {
1034
0
        return NULL;
1035
0
    }
1036
1037
0
    cbparam.email = CERT_FixupEmailAddr(email);
1038
0
    if (cbparam.email == NULL) {
1039
0
        CERT_DestroyCertList(cbparam.certList);
1040
0
        return NULL;
1041
0
    }
1042
1043
0
    rv = PK11_TraverseSlotCerts(FindCertsEmailCallback, &cbparam, NULL);
1044
0
    if (rv != SECSuccess) {
1045
0
        CERT_DestroyCertList(cbparam.certList);
1046
0
        PORT_Free(cbparam.email);
1047
0
        return NULL;
1048
0
    }
1049
1050
    /* empty list? */
1051
0
    if (CERT_LIST_EMPTY(cbparam.certList)) {
1052
0
        CERT_DestroyCertList(cbparam.certList);
1053
0
        cbparam.certList = NULL;
1054
0
    }
1055
1056
0
    PORT_Free(cbparam.email);
1057
0
    return cbparam.certList;
1058
0
}
1059
1060
CERTCertList *
1061
PK11_FindCertsFromNickname(const char *nickname, void *wincx)
1062
0
{
1063
0
    int i;
1064
0
    CERTCertList *certList = NULL;
1065
0
    NSSCertificate **foundCerts = NULL;
1066
0
    NSSCertificate *c;
1067
1068
0
    foundCerts = find_certs_from_nickname(nickname, wincx);
1069
0
    if (foundCerts) {
1070
0
        PRTime now = PR_Now();
1071
0
        certList = CERT_NewCertList();
1072
0
        for (i = 0, c = *foundCerts; c; c = foundCerts[++i]) {
1073
0
            if (certList) {
1074
0
                CERTCertificate *certCert = STAN_GetCERTCertificateOrRelease(c);
1075
                /* c may be invalid after this, don't reference it */
1076
0
                if (certCert) {
1077
                    /* CERT_AddCertToListSorted adopts certCert  */
1078
0
                    CERT_AddCertToListSorted(certList, certCert,
1079
0
                                             CERT_SortCBValidity, &now);
1080
0
                }
1081
0
            } else {
1082
0
                nssCertificate_Destroy(c);
1083
0
            }
1084
0
        }
1085
        /* all the certs have been adopted or freed, free the  raw array */
1086
0
        nss_ZFreeIf(foundCerts);
1087
0
    }
1088
0
    return certList;
1089
0
}
1090
1091
/*
1092
 * extract a key ID for a certificate...
1093
 * NOTE: We call this function from PKCS11.c If we ever use
1094
 * pkcs11 to extract the public key (we currently do not), this will break.
1095
 */
1096
SECItem *
1097
PK11_GetPubIndexKeyID(CERTCertificate *cert)
1098
0
{
1099
0
    SECKEYPublicKey *pubk;
1100
0
    SECItem *newItem = NULL;
1101
1102
0
    pubk = CERT_ExtractPublicKey(cert);
1103
0
    if (pubk == NULL)
1104
0
        return NULL;
1105
1106
0
    switch (pubk->keyType) {
1107
0
        case rsaKey:
1108
0
            newItem = SECITEM_DupItem(&pubk->u.rsa.modulus);
1109
0
            break;
1110
0
        case dsaKey:
1111
0
            newItem = SECITEM_DupItem(&pubk->u.dsa.publicValue);
1112
0
            break;
1113
0
        case dhKey:
1114
0
            newItem = SECITEM_DupItem(&pubk->u.dh.publicValue);
1115
0
            break;
1116
0
        case ecKey:
1117
0
        case edKey:
1118
0
            newItem = SECITEM_DupItem(&pubk->u.ec.publicValue);
1119
0
            break;
1120
0
        case fortezzaKey:
1121
0
        default:
1122
0
            newItem = NULL; /* Fortezza Fix later... */
1123
0
    }
1124
0
    SECKEY_DestroyPublicKey(pubk);
1125
    /* make hash of it */
1126
0
    return newItem;
1127
0
}
1128
1129
/*
1130
 * generate a CKA_ID from a certificate.
1131
 */
1132
SECItem *
1133
pk11_mkcertKeyID(CERTCertificate *cert)
1134
0
{
1135
0
    SECItem *pubKeyData = PK11_GetPubIndexKeyID(cert);
1136
0
    SECItem *certCKA_ID;
1137
1138
0
    if (pubKeyData == NULL)
1139
0
        return NULL;
1140
1141
0
    certCKA_ID = PK11_MakeIDFromPubKey(pubKeyData);
1142
0
    SECITEM_FreeItem(pubKeyData, PR_TRUE);
1143
0
    return certCKA_ID;
1144
0
}
1145
1146
/*
1147
 * Write the cert into the token.
1148
 */
1149
SECStatus
1150
PK11_ImportCert(PK11SlotInfo *slot, CERTCertificate *cert,
1151
                CK_OBJECT_HANDLE key, const char *nickname,
1152
                PRBool includeTrust)
1153
0
{
1154
0
    PRStatus status;
1155
0
    NSSCertificate *c;
1156
0
    nssCryptokiObject *keyobj, *certobj;
1157
0
    NSSToken *token = NULL;
1158
0
    char *emailAddr = NULL;
1159
0
    nssCertificateStoreTrace lockTrace = { NULL, NULL, PR_FALSE, PR_FALSE };
1160
0
    nssCertificateStoreTrace unlockTrace = { NULL, NULL, PR_FALSE, PR_FALSE };
1161
0
    SECItem *keyID = pk11_mkcertKeyID(cert);
1162
0
    if (keyID == NULL) {
1163
0
        goto loser; /* error code should be set already */
1164
0
    }
1165
0
    token = PK11Slot_GetNSSToken(slot);
1166
0
    if (!token) {
1167
0
        PORT_SetError(SEC_ERROR_NO_TOKEN);
1168
0
        goto loser;
1169
0
    }
1170
1171
0
    if (PK11_IsInternal(slot) && cert->emailAddr && cert->emailAddr[0]) {
1172
0
        emailAddr = cert->emailAddr;
1173
0
    }
1174
1175
    /* need to get the cert as a stan cert */
1176
0
    CERT_LockCertTempPerm(cert);
1177
0
    NSSCertificate *nssCert = cert->nssCertificate;
1178
0
    CERT_UnlockCertTempPerm(cert);
1179
0
    if (nssCert) {
1180
0
        c = nssCert;
1181
0
    } else {
1182
0
        c = STAN_GetNSSCertificate(cert);
1183
0
        if (c == NULL) {
1184
0
            goto loser;
1185
0
        }
1186
0
    }
1187
1188
    /* set the id for the cert */
1189
0
    nssItem_Create(c->object.arena, &c->id, keyID->len, keyID->data);
1190
0
    if (!c->id.data) {
1191
0
        goto loser;
1192
0
    }
1193
1194
0
    if (key != CK_INVALID_HANDLE) {
1195
        /* create an object for the key, ... */
1196
0
        keyobj = nss_ZNEW(NULL, nssCryptokiObject);
1197
0
        if (!keyobj) {
1198
0
            goto loser;
1199
0
        }
1200
0
        keyobj->token = nssToken_AddRef(token);
1201
0
        keyobj->handle = key;
1202
0
        keyobj->isTokenObject = PR_TRUE;
1203
1204
        /* ... in order to set matching attributes for the key */
1205
0
        status = nssCryptokiPrivateKey_SetCertificate(keyobj, NULL, nickname,
1206
0
                                                      &c->id, &c->subject);
1207
0
        nssCryptokiObject_Destroy(keyobj);
1208
0
        if (status != PR_SUCCESS) {
1209
0
            goto loser;
1210
0
        }
1211
0
    }
1212
1213
    /* do the token import */
1214
0
    certobj = nssToken_ImportCertificate(token, NULL,
1215
0
                                         NSSCertificateType_PKIX,
1216
0
                                         &c->id,
1217
0
                                         nickname,
1218
0
                                         &c->encoding,
1219
0
                                         &c->issuer,
1220
0
                                         &c->subject,
1221
0
                                         &c->serial,
1222
0
                                         emailAddr,
1223
0
                                         PR_TRUE);
1224
0
    if (!certobj) {
1225
0
        if (NSS_GetError() == NSS_ERROR_INVALID_CERTIFICATE) {
1226
0
            PORT_SetError(SEC_ERROR_REUSED_ISSUER_AND_SERIAL);
1227
0
            SECITEM_FreeItem(keyID, PR_TRUE);
1228
0
            return SECFailure;
1229
0
        }
1230
0
        goto loser;
1231
0
    }
1232
1233
0
    if (c->object.cryptoContext) {
1234
        /* Delete the temp instance */
1235
0
        NSSCryptoContext *cc = c->object.cryptoContext;
1236
0
        nssCertificateStore_Lock(cc->certStore, &lockTrace);
1237
0
        nssCertificateStore_RemoveCertLOCKED(cc->certStore, c);
1238
0
        nssCertificateStore_Unlock(cc->certStore, &lockTrace, &unlockTrace);
1239
0
        c->object.cryptoContext = NULL;
1240
0
        CERT_LockCertTempPerm(cert);
1241
0
        cert->istemp = PR_FALSE;
1242
0
        cert->isperm = PR_TRUE;
1243
0
        CERT_UnlockCertTempPerm(cert);
1244
0
    }
1245
1246
    /* add the new instance to the cert, force an update of the
1247
     * CERTCertificate, and finish
1248
     */
1249
0
    nssPKIObject_AddInstance(&c->object, certobj);
1250
    /* nssTrustDomain_AddCertsToCache may release a reference to 'c' and
1251
     * replace 'c' with a different value. So we add a reference to 'c' to
1252
     * prevent 'c' from being destroyed. */
1253
0
    nssCertificate_AddRef(c);
1254
0
    nssTrustDomain_AddCertsToCache(STAN_GetDefaultTrustDomain(), &c, 1);
1255
0
    (void)STAN_ForceCERTCertificateUpdate(c);
1256
0
    nssCertificate_Destroy(c);
1257
0
    SECITEM_FreeItem(keyID, PR_TRUE);
1258
0
    (void)nssToken_Destroy(token);
1259
0
    return SECSuccess;
1260
0
loser:
1261
0
    if (token) {
1262
0
        (void)nssToken_Destroy(token);
1263
0
    }
1264
0
    CERT_MapStanError();
1265
0
    SECITEM_FreeItem(keyID, PR_TRUE);
1266
0
    if (PORT_GetError() != SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
1267
0
        PORT_SetError(SEC_ERROR_ADDING_CERT);
1268
0
    }
1269
0
    return SECFailure;
1270
0
}
1271
1272
SECStatus
1273
PK11_ImportDERCert(PK11SlotInfo *slot, SECItem *derCert,
1274
                   CK_OBJECT_HANDLE key, char *nickname, PRBool includeTrust)
1275
0
{
1276
0
    CERTCertificate *cert;
1277
0
    SECStatus rv;
1278
1279
0
    cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
1280
0
                                   derCert, NULL, PR_FALSE, PR_TRUE);
1281
0
    if (cert == NULL)
1282
0
        return SECFailure;
1283
1284
0
    rv = PK11_ImportCert(slot, cert, key, nickname, includeTrust);
1285
0
    CERT_DestroyCertificate(cert);
1286
0
    return rv;
1287
0
}
1288
1289
/*
1290
 * return the private key From a given Cert
1291
 */
1292
SECKEYPrivateKey *
1293
PK11_FindPrivateKeyFromCert(PK11SlotInfo *slot, CERTCertificate *cert,
1294
                            void *wincx)
1295
0
{
1296
0
    int err;
1297
0
    CK_OBJECT_HANDLE certh;
1298
0
    CK_OBJECT_HANDLE keyh;
1299
0
    PRBool needLogin;
1300
0
    SECStatus rv;
1301
1302
0
    certh = PK11_FindCertInSlot(slot, cert, wincx);
1303
0
    if (certh == CK_INVALID_HANDLE) {
1304
0
        return NULL;
1305
0
    }
1306
    /*
1307
     * prevent a login race condition. If slot is logged in between
1308
     * our call to pk11_LoginStillRequired and the
1309
     * PK11_MatchItem. The matchItem call will either succeed, or
1310
     * we will call it one more time after calling PK11_Authenticate
1311
     * (which is a noop on an authenticated token).
1312
     */
1313
0
    needLogin = pk11_LoginStillRequired(slot, wincx);
1314
0
    keyh = PK11_MatchItem(slot, certh, CKO_PRIVATE_KEY);
1315
0
    if ((keyh == CK_INVALID_HANDLE) && needLogin &&
1316
0
        (SSL_ERROR_NO_CERTIFICATE == (err = PORT_GetError()) ||
1317
0
         SEC_ERROR_TOKEN_NOT_LOGGED_IN == err)) {
1318
        /* try it again authenticated */
1319
0
        rv = PK11_Authenticate(slot, PR_TRUE, wincx);
1320
0
        if (rv != SECSuccess) {
1321
0
            return NULL;
1322
0
        }
1323
0
        keyh = PK11_MatchItem(slot, certh, CKO_PRIVATE_KEY);
1324
0
    }
1325
0
    if (keyh == CK_INVALID_HANDLE) {
1326
0
        return NULL;
1327
0
    }
1328
0
    return PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyh, wincx);
1329
0
}
1330
1331
/*
1332
 * import a cert for a private key we have already generated. Set the label
1333
 * on both to be the nickname. This is for the Key Gen, orphaned key case.
1334
 */
1335
PK11SlotInfo *
1336
PK11_KeyForCertExists(CERTCertificate *cert, CK_OBJECT_HANDLE *keyPtr,
1337
                      void *wincx)
1338
0
{
1339
0
    PK11SlotList *list;
1340
0
    PK11SlotListElement *le;
1341
0
    SECItem *keyID;
1342
0
    CK_OBJECT_HANDLE key;
1343
0
    PK11SlotInfo *slot = NULL;
1344
0
    SECStatus rv;
1345
0
    int err;
1346
1347
0
    keyID = pk11_mkcertKeyID(cert);
1348
    /* get them all! */
1349
0
    list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, wincx);
1350
0
    if ((keyID == NULL) || (list == NULL)) {
1351
0
        if (keyID)
1352
0
            SECITEM_FreeItem(keyID, PR_TRUE);
1353
0
        if (list)
1354
0
            PK11_FreeSlotList(list);
1355
0
        return NULL;
1356
0
    }
1357
1358
    /* Look for the slot that holds the Key */
1359
0
    for (le = list->head; le; le = le->next) {
1360
        /*
1361
         * prevent a login race condition. If le->slot is logged in between
1362
         * our call to pk11_LoginStillRequired and the
1363
         * pk11_FindPrivateKeyFromCertID, the find will either succeed, or
1364
         * we will call it one more time after calling PK11_Authenticate
1365
         * (which is a noop on an authenticated token).
1366
         */
1367
0
        PRBool needLogin = pk11_LoginStillRequired(le->slot, wincx);
1368
0
        key = pk11_FindPrivateKeyFromCertID(le->slot, keyID);
1369
0
        if ((key == CK_INVALID_HANDLE) && needLogin &&
1370
0
            (SSL_ERROR_NO_CERTIFICATE == (err = PORT_GetError()) ||
1371
0
             SEC_ERROR_TOKEN_NOT_LOGGED_IN == err)) {
1372
            /* authenticate and try again */
1373
0
            rv = PK11_Authenticate(le->slot, PR_TRUE, wincx);
1374
0
            if (rv != SECSuccess)
1375
0
                continue;
1376
0
            key = pk11_FindPrivateKeyFromCertID(le->slot, keyID);
1377
0
        }
1378
0
        if (key != CK_INVALID_HANDLE) {
1379
0
            slot = PK11_ReferenceSlot(le->slot);
1380
0
            if (keyPtr)
1381
0
                *keyPtr = key;
1382
0
            break;
1383
0
        }
1384
0
    }
1385
1386
0
    SECITEM_FreeItem(keyID, PR_TRUE);
1387
0
    PK11_FreeSlotList(list);
1388
0
    return slot;
1389
0
}
1390
/*
1391
 * import a cert for a private key we have already generated. Set the label
1392
 * on both to be the nickname. This is for the Key Gen, orphaned key case.
1393
 */
1394
PK11SlotInfo *
1395
PK11_KeyForDERCertExists(SECItem *derCert, CK_OBJECT_HANDLE *keyPtr,
1396
                         void *wincx)
1397
0
{
1398
0
    CERTCertificate *cert;
1399
0
    PK11SlotInfo *slot = NULL;
1400
1401
    /* letting this use go -- the only thing that the cert is used for is
1402
     * to get the ID attribute.
1403
     */
1404
0
    cert = CERT_DecodeDERCertificate(derCert, PR_FALSE, NULL);
1405
0
    if (cert == NULL)
1406
0
        return NULL;
1407
1408
0
    slot = PK11_KeyForCertExists(cert, keyPtr, wincx);
1409
0
    CERT_DestroyCertificate(cert);
1410
0
    return slot;
1411
0
}
1412
1413
PK11SlotInfo *
1414
PK11_ImportCertForKey(CERTCertificate *cert, const char *nickname,
1415
                      void *wincx)
1416
0
{
1417
0
    PK11SlotInfo *slot = NULL;
1418
0
    CK_OBJECT_HANDLE key;
1419
1420
0
    slot = PK11_KeyForCertExists(cert, &key, wincx);
1421
1422
0
    if (slot) {
1423
0
        if (PK11_ImportCert(slot, cert, key, nickname, PR_FALSE) != SECSuccess) {
1424
0
            PK11_FreeSlot(slot);
1425
0
            slot = NULL;
1426
0
        }
1427
0
    } else {
1428
0
        PORT_SetError(SEC_ERROR_ADDING_CERT);
1429
0
    }
1430
1431
0
    return slot;
1432
0
}
1433
1434
PK11SlotInfo *
1435
PK11_ImportDERCertForKey(SECItem *derCert, char *nickname, void *wincx)
1436
0
{
1437
0
    CERTCertificate *cert;
1438
0
    PK11SlotInfo *slot = NULL;
1439
1440
0
    cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
1441
0
                                   derCert, NULL, PR_FALSE, PR_TRUE);
1442
0
    if (cert == NULL)
1443
0
        return NULL;
1444
1445
0
    slot = PK11_ImportCertForKey(cert, nickname, wincx);
1446
0
    CERT_DestroyCertificate(cert);
1447
0
    return slot;
1448
0
}
1449
1450
static CK_OBJECT_HANDLE
1451
pk11_FindCertObjectByTemplate(PK11SlotInfo **slotPtr,
1452
                              CK_ATTRIBUTE *searchTemplate, size_t count, void *wincx)
1453
0
{
1454
0
    PK11SlotList *list;
1455
0
    PK11SlotListElement *le;
1456
0
    CK_OBJECT_HANDLE certHandle = CK_INVALID_HANDLE;
1457
0
    PK11SlotInfo *slot = NULL;
1458
0
    SECStatus rv;
1459
1460
0
    *slotPtr = NULL;
1461
1462
    /* get them all! */
1463
0
    list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, wincx);
1464
0
    if (list == NULL) {
1465
0
        return CK_INVALID_HANDLE;
1466
0
    }
1467
1468
    /* Look for the slot that holds the Key */
1469
0
    for (le = list->head; le; le = le->next) {
1470
0
        rv = pk11_AuthenticateUnfriendly(le->slot, PR_TRUE, wincx);
1471
0
        if (rv != SECSuccess)
1472
0
            continue;
1473
1474
0
        certHandle = pk11_FindObjectByTemplate(le->slot, searchTemplate, count);
1475
0
        if (certHandle != CK_INVALID_HANDLE) {
1476
0
            slot = PK11_ReferenceSlot(le->slot);
1477
0
            break;
1478
0
        }
1479
0
    }
1480
1481
0
    PK11_FreeSlotList(list);
1482
1483
0
    if (slot == NULL) {
1484
0
        return CK_INVALID_HANDLE;
1485
0
    }
1486
0
    *slotPtr = slot;
1487
0
    return certHandle;
1488
0
}
1489
1490
CERTCertificate *
1491
PK11_FindCertByIssuerAndSNOnToken(PK11SlotInfo *slot,
1492
                                  CERTIssuerAndSN *issuerSN, void *wincx)
1493
0
{
1494
0
    CERTCertificate *rvCert = NULL;
1495
0
    NSSCertificate *cert = NULL;
1496
0
    NSSDER issuer, serial;
1497
0
    NSSTrustDomain *td = STAN_GetDefaultTrustDomain();
1498
0
    NSSToken *token = NULL;
1499
0
    nssSession *session;
1500
0
    nssCryptokiObject *instance = NULL;
1501
0
    nssPKIObject *object = NULL;
1502
0
    SECItem *derSerial;
1503
0
    PRStatus status;
1504
1505
0
    if (!issuerSN || !issuerSN->derIssuer.data || !issuerSN->derIssuer.len ||
1506
0
        !issuerSN->serialNumber.data || !issuerSN->serialNumber.len ||
1507
0
        issuerSN->derIssuer.len > CERT_MAX_DN_BYTES ||
1508
0
        issuerSN->serialNumber.len > CERT_MAX_SERIAL_NUMBER_BYTES) {
1509
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1510
0
        return NULL;
1511
0
    }
1512
1513
0
    token = PK11Slot_GetNSSToken(slot);
1514
0
    if (!token) {
1515
0
        PORT_SetError(SEC_ERROR_NO_TOKEN);
1516
0
        return NULL;
1517
0
    }
1518
1519
0
    session = nssToken_GetDefaultSession(token); /* non-owning */
1520
0
    if (!session) {
1521
0
        (void)nssToken_Destroy(token);
1522
0
        return NULL;
1523
0
    }
1524
1525
    /* PKCS#11 needs to use DER-encoded serial numbers.  Create a
1526
     * CERTIssuerAndSN that actually has the encoded value and pass that
1527
     * to PKCS#11 (and the crypto context).
1528
     */
1529
0
    derSerial = SEC_ASN1EncodeItem(NULL, NULL,
1530
0
                                   &issuerSN->serialNumber,
1531
0
                                   SEC_ASN1_GET(SEC_IntegerTemplate));
1532
0
    if (!derSerial) {
1533
0
        (void)nssToken_Destroy(token);
1534
0
        return NULL;
1535
0
    }
1536
1537
0
    NSSITEM_FROM_SECITEM(&issuer, &issuerSN->derIssuer);
1538
0
    NSSITEM_FROM_SECITEM(&serial, derSerial);
1539
1540
0
    instance = nssToken_FindCertificateByIssuerAndSerialNumber(token, session,
1541
0
                                                               &issuer, &serial, nssTokenSearchType_TokenForced, &status);
1542
1543
0
    (void)nssToken_Destroy(token);
1544
0
    SECITEM_FreeItem(derSerial, PR_TRUE);
1545
1546
0
    if (!instance) {
1547
0
        goto loser;
1548
0
    }
1549
0
    object = nssPKIObject_Create(NULL, instance, td, NULL, nssPKIMonitor);
1550
0
    if (!object) {
1551
0
        goto loser;
1552
0
    }
1553
0
    instance = NULL; /* adopted by the previous call */
1554
0
    cert = nssCertificate_Create(object);
1555
0
    if (!cert) {
1556
0
        goto loser;
1557
0
    }
1558
0
    object = NULL; /* adopted by the previous call */
1559
0
    nssTrustDomain_AddCertsToCache(td, &cert, 1);
1560
    /* on failure, cert is freed below */
1561
0
    rvCert = STAN_GetCERTCertificate(cert);
1562
0
    if (!rvCert) {
1563
0
        goto loser;
1564
0
    }
1565
0
    return rvCert;
1566
1567
0
loser:
1568
0
    if (instance) {
1569
0
        nssCryptokiObject_Destroy(instance);
1570
0
    }
1571
0
    if (object) {
1572
0
        nssPKIObject_Destroy(object);
1573
0
    }
1574
0
    if (cert) {
1575
0
        nssCertificate_Destroy(cert);
1576
0
    }
1577
0
    return NULL;
1578
0
}
1579
1580
static PRCallOnceType keyIDHashCallOnce;
1581
1582
static PRStatus PR_CALLBACK
1583
pk11_keyIDHash_populate(void *wincx)
1584
0
{
1585
0
    CERTCertList *certList;
1586
0
    CERTCertListNode *node = NULL;
1587
0
    SECItem subjKeyID = { siBuffer, NULL, 0 };
1588
0
    SECItem *slotid = NULL;
1589
0
    SECMODModuleList *modules, *mlp;
1590
0
    SECMODListLock *moduleLock;
1591
0
    int i;
1592
1593
0
    certList = PK11_ListCerts(PK11CertListUser, wincx);
1594
0
    if (!certList) {
1595
0
        return PR_FAILURE;
1596
0
    }
1597
1598
0
    for (node = CERT_LIST_HEAD(certList);
1599
0
         !CERT_LIST_END(node, certList);
1600
0
         node = CERT_LIST_NEXT(node)) {
1601
0
        if (CERT_FindSubjectKeyIDExtension(node->cert,
1602
0
                                           &subjKeyID) == SECSuccess &&
1603
0
            subjKeyID.data != NULL) {
1604
0
            cert_AddSubjectKeyIDMapping(&subjKeyID, node->cert);
1605
0
            SECITEM_FreeItem(&subjKeyID, PR_FALSE);
1606
0
        }
1607
0
    }
1608
0
    CERT_DestroyCertList(certList);
1609
1610
    /*
1611
     * Record the state of each slot in a hash. The concatenation of slotID
1612
     * and moduleID is used as its key, with the slot series as its value.
1613
     */
1614
0
    slotid = SECITEM_AllocItem(NULL, NULL,
1615
0
                               sizeof(CK_SLOT_ID) + sizeof(SECMODModuleID));
1616
0
    if (!slotid) {
1617
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
1618
0
        return PR_FAILURE;
1619
0
    }
1620
0
    moduleLock = SECMOD_GetDefaultModuleListLock();
1621
0
    if (!moduleLock) {
1622
0
        SECITEM_FreeItem(slotid, PR_TRUE);
1623
0
        PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
1624
0
        return PR_FAILURE;
1625
0
    }
1626
0
    SECMOD_GetReadLock(moduleLock);
1627
0
    modules = SECMOD_GetDefaultModuleList();
1628
0
    for (mlp = modules; mlp; mlp = mlp->next) {
1629
0
        for (i = 0; i < mlp->module->slotCount; i++) {
1630
0
            memcpy(slotid->data, &mlp->module->slots[i]->slotID,
1631
0
                   sizeof(CK_SLOT_ID));
1632
0
            memcpy(&slotid->data[sizeof(CK_SLOT_ID)], &mlp->module->moduleID,
1633
0
                   sizeof(SECMODModuleID));
1634
0
            cert_UpdateSubjectKeyIDSlotCheck(slotid,
1635
0
                                             mlp->module->slots[i]->series);
1636
0
        }
1637
0
    }
1638
0
    SECMOD_ReleaseReadLock(moduleLock);
1639
0
    SECITEM_FreeItem(slotid, PR_TRUE);
1640
1641
0
    return PR_SUCCESS;
1642
0
}
1643
1644
/*
1645
 * We're looking for a cert which we have the private key for that's on the
1646
 * list of recipients. This searches one slot.
1647
 * this is the new version for NSS SMIME code
1648
 * this stuff should REALLY be in the SMIME code, but some things in here are not public
1649
 * (they should be!)
1650
 */
1651
static CERTCertificate *
1652
pk11_FindCertObjectByRecipientNew(PK11SlotInfo *slot, NSSCMSRecipient **recipientlist,
1653
                                  int *rlIndex, void *pwarg)
1654
0
{
1655
0
    NSSCMSRecipient *ri = NULL;
1656
0
    int i;
1657
0
    PRBool tokenRescanDone = PR_FALSE;
1658
0
    CERTCertTrust trust;
1659
1660
0
    for (i = 0; (ri = recipientlist[i]) != NULL; i++) {
1661
0
        CERTCertificate *cert = NULL;
1662
0
        if (ri->kind == RLSubjKeyID) {
1663
0
            SECItem *derCert = cert_FindDERCertBySubjectKeyID(ri->id.subjectKeyID);
1664
0
            if (!derCert && !tokenRescanDone) {
1665
                /*
1666
                 * We didn't find the cert by its key ID. If we have slots
1667
                 * with removable tokens, a failure from
1668
                 * cert_FindDERCertBySubjectKeyID doesn't necessarily imply
1669
                 * that the cert is unavailable - the token might simply
1670
                 * have been inserted after the initial run of
1671
                 * pk11_keyIDHash_populate (wrapped by PR_CallOnceWithArg),
1672
                 * or a different token might have been present in that
1673
                 * slot, initially. Let's check for new tokens...
1674
                 */
1675
0
                PK11SlotList *sl = PK11_GetAllTokens(CKM_INVALID_MECHANISM,
1676
0
                                                     PR_FALSE, PR_FALSE, pwarg);
1677
0
                if (sl) {
1678
0
                    PK11SlotListElement *le;
1679
0
                    SECItem *slotid = SECITEM_AllocItem(NULL, NULL,
1680
0
                                                        sizeof(CK_SLOT_ID) + sizeof(SECMODModuleID));
1681
0
                    if (!slotid) {
1682
0
                        PORT_SetError(SEC_ERROR_NO_MEMORY);
1683
0
                        PK11_FreeSlotList(sl);
1684
0
                        return NULL;
1685
0
                    }
1686
0
                    for (le = sl->head; le; le = le->next) {
1687
0
                        memcpy(slotid->data, &le->slot->slotID,
1688
0
                               sizeof(CK_SLOT_ID));
1689
0
                        memcpy(&slotid->data[sizeof(CK_SLOT_ID)],
1690
0
                               &le->slot->module->moduleID,
1691
0
                               sizeof(SECMODModuleID));
1692
                        /*
1693
                         * Any changes with the slot since our last check?
1694
                         * If so, re-read the certs in that specific slot.
1695
                         */
1696
0
                        if (cert_SubjectKeyIDSlotCheckSeries(slotid) != PK11_GetSlotSeries(le->slot)) {
1697
0
                            CERTCertListNode *node = NULL;
1698
0
                            SECItem subjKeyID = { siBuffer, NULL, 0 };
1699
0
                            CERTCertList *cl = PK11_ListCertsInSlot(le->slot);
1700
0
                            if (!cl) {
1701
0
                                continue;
1702
0
                            }
1703
0
                            for (node = CERT_LIST_HEAD(cl);
1704
0
                                 !CERT_LIST_END(node, cl);
1705
0
                                 node = CERT_LIST_NEXT(node)) {
1706
0
                                if (CERT_IsUserCert(node->cert) &&
1707
0
                                    CERT_FindSubjectKeyIDExtension(node->cert,
1708
0
                                                                   &subjKeyID) == SECSuccess) {
1709
0
                                    if (subjKeyID.data) {
1710
0
                                        cert_AddSubjectKeyIDMapping(&subjKeyID,
1711
0
                                                                    node->cert);
1712
0
                                        cert_UpdateSubjectKeyIDSlotCheck(slotid,
1713
0
                                                                         PK11_GetSlotSeries(le->slot));
1714
0
                                    }
1715
0
                                    SECITEM_FreeItem(&subjKeyID, PR_FALSE);
1716
0
                                }
1717
0
                            }
1718
0
                            CERT_DestroyCertList(cl);
1719
0
                        }
1720
0
                    }
1721
0
                    PK11_FreeSlotList(sl);
1722
0
                    SECITEM_FreeItem(slotid, PR_TRUE);
1723
0
                }
1724
                /* only check once per message/recipientlist */
1725
0
                tokenRescanDone = PR_TRUE;
1726
                /* do another lookup (hopefully we found that cert...) */
1727
0
                derCert = cert_FindDERCertBySubjectKeyID(ri->id.subjectKeyID);
1728
0
            }
1729
0
            if (derCert) {
1730
0
                cert = PK11_FindCertFromDERCertItem(slot, derCert, pwarg);
1731
0
                SECITEM_FreeItem(derCert, PR_TRUE);
1732
0
            }
1733
0
        } else {
1734
0
            cert = PK11_FindCertByIssuerAndSNOnToken(slot, ri->id.issuerAndSN,
1735
0
                                                     pwarg);
1736
0
        }
1737
0
        if (cert) {
1738
            /* this isn't our cert */
1739
0
            if (CERT_GetCertTrust(cert, &trust) != SECSuccess ||
1740
0
                ((trust.emailFlags & CERTDB_USER) != CERTDB_USER)) {
1741
0
                CERT_DestroyCertificate(cert);
1742
0
                continue;
1743
0
            }
1744
0
            ri->slot = PK11_ReferenceSlot(slot);
1745
0
            *rlIndex = i;
1746
0
            return cert;
1747
0
        }
1748
0
    }
1749
0
    *rlIndex = -1;
1750
0
    return NULL;
1751
0
}
1752
1753
/*
1754
 * This function is the same as above, but it searches all the slots.
1755
 * this is the new version for NSS SMIME code
1756
 * this stuff should REALLY be in the SMIME code, but some things in here are not public
1757
 * (they should be!)
1758
 */
1759
static CERTCertificate *
1760
pk11_AllFindCertObjectByRecipientNew(NSSCMSRecipient **recipientlist, void *wincx, int *rlIndex)
1761
0
{
1762
0
    PK11SlotList *list;
1763
0
    PK11SlotListElement *le;
1764
0
    CERTCertificate *cert = NULL;
1765
0
    SECStatus rv;
1766
1767
    /* get them all! */
1768
0
    list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, wincx);
1769
0
    if (list == NULL) {
1770
0
        return CK_INVALID_HANDLE;
1771
0
    }
1772
1773
    /* Look for the slot that holds the Key */
1774
0
    for (le = list->head; le; le = le->next) {
1775
0
        rv = pk11_AuthenticateUnfriendly(le->slot, PR_TRUE, wincx);
1776
0
        if (rv != SECSuccess)
1777
0
            continue;
1778
1779
0
        cert = pk11_FindCertObjectByRecipientNew(le->slot,
1780
0
                                                 recipientlist, rlIndex, wincx);
1781
0
        if (cert)
1782
0
            break;
1783
0
    }
1784
1785
0
    PK11_FreeSlotList(list);
1786
1787
0
    return cert;
1788
0
}
1789
1790
/*
1791
 * We're looking for a cert which we have the private key for that's on the
1792
 * list of recipients. This searches one slot.
1793
 */
1794
static CERTCertificate *
1795
pk11_FindCertObjectByRecipient(PK11SlotInfo *slot,
1796
                               SEC_PKCS7RecipientInfo **recipientArray,
1797
                               SEC_PKCS7RecipientInfo **rip, void *pwarg)
1798
0
{
1799
0
    SEC_PKCS7RecipientInfo *ri = NULL;
1800
0
    CERTCertTrust trust;
1801
0
    int i;
1802
1803
0
    for (i = 0; (ri = recipientArray[i]) != NULL; i++) {
1804
0
        CERTCertificate *cert;
1805
1806
0
        cert = PK11_FindCertByIssuerAndSNOnToken(slot, ri->issuerAndSN,
1807
0
                                                 pwarg);
1808
0
        if (cert) {
1809
            /* this isn't our cert */
1810
0
            if (CERT_GetCertTrust(cert, &trust) != SECSuccess ||
1811
0
                ((trust.emailFlags & CERTDB_USER) != CERTDB_USER)) {
1812
0
                CERT_DestroyCertificate(cert);
1813
0
                continue;
1814
0
            }
1815
0
            *rip = ri;
1816
0
            return cert;
1817
0
        }
1818
0
    }
1819
0
    *rip = NULL;
1820
0
    return NULL;
1821
0
}
1822
1823
/*
1824
 * This function is the same as above, but it searches all the slots.
1825
 */
1826
static CERTCertificate *
1827
pk11_AllFindCertObjectByRecipient(PK11SlotInfo **slotPtr,
1828
                                  SEC_PKCS7RecipientInfo **recipientArray,
1829
                                  SEC_PKCS7RecipientInfo **rip,
1830
                                  void *wincx)
1831
0
{
1832
0
    PK11SlotList *list;
1833
0
    PK11SlotListElement *le;
1834
0
    CERTCertificate *cert = NULL;
1835
0
    PK11SlotInfo *slot = NULL;
1836
0
    SECStatus rv;
1837
1838
0
    *slotPtr = NULL;
1839
1840
    /* get them all! */
1841
0
    list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, wincx);
1842
0
    if (list == NULL) {
1843
0
        return CK_INVALID_HANDLE;
1844
0
    }
1845
1846
0
    *rip = NULL;
1847
1848
    /* Look for the slot that holds the Key */
1849
0
    for (le = list->head; le; le = le->next) {
1850
0
        rv = pk11_AuthenticateUnfriendly(le->slot, PR_TRUE, wincx);
1851
0
        if (rv != SECSuccess)
1852
0
            continue;
1853
1854
0
        cert = pk11_FindCertObjectByRecipient(le->slot, recipientArray,
1855
0
                                              rip, wincx);
1856
0
        if (cert) {
1857
0
            slot = PK11_ReferenceSlot(le->slot);
1858
0
            break;
1859
0
        }
1860
0
    }
1861
1862
0
    PK11_FreeSlotList(list);
1863
1864
0
    if (slot == NULL) {
1865
0
        return NULL;
1866
0
    }
1867
0
    *slotPtr = slot;
1868
0
    PORT_Assert(cert != NULL);
1869
0
    return cert;
1870
0
}
1871
1872
/*
1873
 * We need to invert the search logic for PKCS 7 because if we search for
1874
 * each cert on the list over all the slots, we wind up with lots of spurious
1875
 * password prompts. This way we get only one password prompt per slot, at
1876
 * the max, and most of the time we can find the cert, and only prompt for
1877
 * the key...
1878
 */
1879
CERTCertificate *
1880
PK11_FindCertAndKeyByRecipientList(PK11SlotInfo **slotPtr,
1881
                                   SEC_PKCS7RecipientInfo **array,
1882
                                   SEC_PKCS7RecipientInfo **rip,
1883
                                   SECKEYPrivateKey **privKey, void *wincx)
1884
0
{
1885
0
    CERTCertificate *cert = NULL;
1886
1887
0
    *privKey = NULL;
1888
0
    *slotPtr = NULL;
1889
0
    cert = pk11_AllFindCertObjectByRecipient(slotPtr, array, rip, wincx);
1890
0
    if (!cert) {
1891
0
        return NULL;
1892
0
    }
1893
1894
0
    *privKey = PK11_FindKeyByAnyCert(cert, wincx);
1895
0
    if (*privKey == NULL) {
1896
0
        goto loser;
1897
0
    }
1898
1899
0
    return cert;
1900
0
loser:
1901
0
    if (cert)
1902
0
        CERT_DestroyCertificate(cert);
1903
0
    if (*slotPtr)
1904
0
        PK11_FreeSlot(*slotPtr);
1905
0
    *slotPtr = NULL;
1906
0
    return NULL;
1907
0
}
1908
1909
/*
1910
 * This is the new version of the above function for NSS SMIME code
1911
 * this stuff should REALLY be in the SMIME code, but some things in here are not public
1912
 * (they should be!)
1913
 */
1914
int
1915
PK11_FindCertAndKeyByRecipientListNew(NSSCMSRecipient **recipientlist, void *wincx)
1916
0
{
1917
0
    CERTCertificate *cert;
1918
0
    NSSCMSRecipient *rl;
1919
0
    PRStatus rv;
1920
0
    int rlIndex;
1921
1922
0
    rv = PR_CallOnceWithArg(&keyIDHashCallOnce, pk11_keyIDHash_populate, wincx);
1923
0
    if (rv != PR_SUCCESS)
1924
0
        return -1;
1925
1926
0
    cert = pk11_AllFindCertObjectByRecipientNew(recipientlist, wincx, &rlIndex);
1927
0
    if (!cert) {
1928
0
        return -1;
1929
0
    }
1930
1931
0
    rl = recipientlist[rlIndex];
1932
1933
    /* at this point, rl->slot is set */
1934
1935
0
    rl->privkey = PK11_FindKeyByAnyCert(cert, wincx);
1936
0
    if (rl->privkey == NULL) {
1937
0
        goto loser;
1938
0
    }
1939
1940
    /* make a cert from the cert handle */
1941
0
    rl->cert = cert;
1942
0
    return rlIndex;
1943
1944
0
loser:
1945
0
    if (cert)
1946
0
        CERT_DestroyCertificate(cert);
1947
0
    if (rl->slot)
1948
0
        PK11_FreeSlot(rl->slot);
1949
0
    rl->slot = NULL;
1950
0
    return -1;
1951
0
}
1952
1953
CERTCertificate *
1954
PK11_FindCertByIssuerAndSN(PK11SlotInfo **slotPtr, CERTIssuerAndSN *issuerSN,
1955
                           void *wincx)
1956
0
{
1957
0
    CERTCertificate *rvCert = NULL;
1958
0
    NSSCertificate *cert;
1959
0
    NSSDER issuer, serial;
1960
0
    NSSCryptoContext *cc;
1961
0
    SECItem *derSerial;
1962
1963
0
    if (!issuerSN || !issuerSN->derIssuer.data || !issuerSN->derIssuer.len ||
1964
0
        !issuerSN->serialNumber.data || !issuerSN->serialNumber.len ||
1965
0
        issuerSN->derIssuer.len > CERT_MAX_DN_BYTES ||
1966
0
        issuerSN->serialNumber.len > CERT_MAX_SERIAL_NUMBER_BYTES) {
1967
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1968
0
        return NULL;
1969
0
    }
1970
1971
0
    if (slotPtr)
1972
0
        *slotPtr = NULL;
1973
1974
    /* PKCS#11 needs to use DER-encoded serial numbers.  Create a
1975
     * CERTIssuerAndSN that actually has the encoded value and pass that
1976
     * to PKCS#11 (and the crypto context).
1977
     */
1978
0
    derSerial = SEC_ASN1EncodeItem(NULL, NULL,
1979
0
                                   &issuerSN->serialNumber,
1980
0
                                   SEC_ASN1_GET(SEC_IntegerTemplate));
1981
0
    if (!derSerial) {
1982
0
        return NULL;
1983
0
    }
1984
1985
0
    NSSITEM_FROM_SECITEM(&issuer, &issuerSN->derIssuer);
1986
0
    NSSITEM_FROM_SECITEM(&serial, derSerial);
1987
1988
0
    cc = STAN_GetDefaultCryptoContext();
1989
0
    cert = NSSCryptoContext_FindCertificateByIssuerAndSerialNumber(cc,
1990
0
                                                                   &issuer,
1991
0
                                                                   &serial);
1992
0
    if (cert) {
1993
0
        SECITEM_FreeItem(derSerial, PR_TRUE);
1994
0
        return STAN_GetCERTCertificateOrRelease(cert);
1995
0
    }
1996
1997
0
    do {
1998
        /* free the old cert on retry. Associated slot was not present */
1999
0
        if (rvCert) {
2000
0
            CERT_DestroyCertificate(rvCert);
2001
0
            rvCert = NULL;
2002
0
        }
2003
2004
0
        cert = NSSTrustDomain_FindCertificateByIssuerAndSerialNumber(
2005
0
            STAN_GetDefaultTrustDomain(),
2006
0
            &issuer,
2007
0
            &serial);
2008
0
        if (!cert) {
2009
0
            break;
2010
0
        }
2011
2012
0
        rvCert = STAN_GetCERTCertificateOrRelease(cert);
2013
0
        if (rvCert == NULL) {
2014
0
            break;
2015
0
        }
2016
2017
        /* Check to see if the cert's token is still there */
2018
0
    } while (!PK11_IsPresent(rvCert->slot));
2019
2020
0
    if (rvCert && slotPtr)
2021
0
        *slotPtr = PK11_ReferenceSlot(rvCert->slot);
2022
2023
0
    SECITEM_FreeItem(derSerial, PR_TRUE);
2024
0
    return rvCert;
2025
0
}
2026
2027
CK_OBJECT_HANDLE
2028
PK11_FindObjectForCert(CERTCertificate *cert, void *wincx, PK11SlotInfo **pSlot)
2029
0
{
2030
0
    CK_OBJECT_HANDLE certHandle;
2031
0
    CK_OBJECT_CLASS certClass = CKO_CERTIFICATE;
2032
0
    CK_ATTRIBUTE *attr;
2033
0
    CK_ATTRIBUTE searchTemplate[] = {
2034
0
        { CKA_CLASS, NULL, 0 },
2035
0
        { CKA_VALUE, NULL, 0 },
2036
0
    };
2037
0
    const size_t templateSize = sizeof(searchTemplate) / sizeof(searchTemplate[0]);
2038
2039
0
    attr = searchTemplate;
2040
0
    PK11_SETATTRS(attr, CKA_CLASS, &certClass, sizeof(certClass));
2041
0
    attr++;
2042
0
    PK11_SETATTRS(attr, CKA_VALUE, cert->derCert.data, cert->derCert.len);
2043
2044
0
    if (cert->slot) {
2045
0
        certHandle = PK11_FindCertInSlot(cert->slot, cert, wincx);
2046
0
        if (certHandle != CK_INVALID_HANDLE) {
2047
0
            *pSlot = PK11_ReferenceSlot(cert->slot);
2048
0
            return certHandle;
2049
0
        }
2050
0
    }
2051
2052
0
    certHandle = pk11_FindCertObjectByTemplate(pSlot, searchTemplate,
2053
0
                                               templateSize, wincx);
2054
0
    if (certHandle != CK_INVALID_HANDLE) {
2055
0
        if (cert->slot == NULL) {
2056
0
            cert->slot = PK11_ReferenceSlot(*pSlot);
2057
0
            cert->pkcs11ID = certHandle;
2058
0
            cert->ownSlot = PR_TRUE;
2059
0
            cert->series = cert->slot->series;
2060
0
        }
2061
0
    }
2062
2063
0
    return (certHandle);
2064
0
}
2065
2066
SECKEYPrivateKey *
2067
PK11_FindKeyByAnyCert(CERTCertificate *cert, void *wincx)
2068
0
{
2069
0
    CK_OBJECT_HANDLE certHandle;
2070
0
    CK_OBJECT_HANDLE keyHandle;
2071
0
    PK11SlotInfo *slot = NULL;
2072
0
    SECKEYPrivateKey *privKey = NULL;
2073
0
    PRBool needLogin;
2074
0
    SECStatus rv;
2075
0
    int err;
2076
2077
0
    certHandle = PK11_FindObjectForCert(cert, wincx, &slot);
2078
0
    if (certHandle == CK_INVALID_HANDLE) {
2079
0
        return NULL;
2080
0
    }
2081
    /*
2082
     * prevent a login race condition. If slot is logged in between
2083
     * our call to pk11_LoginStillRequired and the
2084
     * PK11_MatchItem. The matchItem call will either succeed, or
2085
     * we will call it one more time after calling PK11_Authenticate
2086
     * (which is a noop on an authenticated token).
2087
     */
2088
0
    needLogin = pk11_LoginStillRequired(slot, wincx);
2089
0
    keyHandle = PK11_MatchItem(slot, certHandle, CKO_PRIVATE_KEY);
2090
0
    if ((keyHandle == CK_INVALID_HANDLE) && needLogin &&
2091
0
        (SSL_ERROR_NO_CERTIFICATE == (err = PORT_GetError()) ||
2092
0
         SEC_ERROR_TOKEN_NOT_LOGGED_IN == err)) {
2093
        /* authenticate and try again */
2094
0
        rv = PK11_Authenticate(slot, PR_TRUE, wincx);
2095
0
        if (rv == SECSuccess) {
2096
0
            keyHandle = PK11_MatchItem(slot, certHandle, CKO_PRIVATE_KEY);
2097
0
        }
2098
0
    }
2099
0
    if (keyHandle != CK_INVALID_HANDLE) {
2100
0
        privKey = PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyHandle, wincx);
2101
0
    }
2102
0
    if (slot) {
2103
0
        PK11_FreeSlot(slot);
2104
0
    }
2105
0
    return privKey;
2106
0
}
2107
2108
CK_OBJECT_HANDLE
2109
pk11_FindPubKeyByAnyCert(CERTCertificate *cert, PK11SlotInfo **slot, void *wincx)
2110
0
{
2111
0
    CK_OBJECT_HANDLE certHandle;
2112
0
    CK_OBJECT_HANDLE keyHandle;
2113
2114
0
    certHandle = PK11_FindObjectForCert(cert, wincx, slot);
2115
0
    if (certHandle == CK_INVALID_HANDLE) {
2116
0
        return CK_INVALID_HANDLE;
2117
0
    }
2118
0
    keyHandle = PK11_MatchItem(*slot, certHandle, CKO_PUBLIC_KEY);
2119
0
    if (keyHandle == CK_INVALID_HANDLE) {
2120
0
        PK11_FreeSlot(*slot);
2121
0
        return CK_INVALID_HANDLE;
2122
0
    }
2123
0
    return keyHandle;
2124
0
}
2125
2126
/*
2127
 * find the number of certs in the slot with the same subject name
2128
 */
2129
int
2130
PK11_NumberCertsForCertSubject(CERTCertificate *cert)
2131
0
{
2132
0
    CK_OBJECT_CLASS certClass = CKO_CERTIFICATE;
2133
0
    CK_ATTRIBUTE theTemplate[] = {
2134
0
        { CKA_CLASS, NULL, 0 },
2135
0
        { CKA_SUBJECT, NULL, 0 },
2136
0
    };
2137
0
    CK_ATTRIBUTE *attr = theTemplate;
2138
0
    int templateSize = sizeof(theTemplate) / sizeof(theTemplate[0]);
2139
2140
0
    PK11_SETATTRS(attr, CKA_CLASS, &certClass, sizeof(certClass));
2141
0
    attr++;
2142
0
    PK11_SETATTRS(attr, CKA_SUBJECT, cert->derSubject.data, cert->derSubject.len);
2143
2144
0
    if (cert->slot == NULL) {
2145
0
        PK11SlotList *list = PK11_GetAllTokens(CKM_INVALID_MECHANISM,
2146
0
                                               PR_FALSE, PR_TRUE, NULL);
2147
0
        PK11SlotListElement *le;
2148
0
        int count = 0;
2149
2150
0
        if (!list) {
2151
            /* error code is set */
2152
0
            return 0;
2153
0
        }
2154
2155
        /* loop through all the fortezza tokens */
2156
0
        for (le = list->head; le; le = le->next) {
2157
0
            count += PK11_NumberObjectsFor(le->slot, theTemplate, templateSize);
2158
0
        }
2159
0
        PK11_FreeSlotList(list);
2160
0
        return count;
2161
0
    }
2162
2163
0
    return PK11_NumberObjectsFor(cert->slot, theTemplate, templateSize);
2164
0
}
2165
2166
/*
2167
 *  Walk all the certs with the same subject
2168
 */
2169
SECStatus
2170
PK11_TraverseCertsForSubject(CERTCertificate *cert,
2171
                             SECStatus (*callback)(CERTCertificate *, void *), void *arg)
2172
0
{
2173
0
    if (!cert) {
2174
0
        return SECFailure;
2175
0
    }
2176
0
    if (cert->slot == NULL) {
2177
0
        PK11SlotList *list = PK11_GetAllTokens(CKM_INVALID_MECHANISM,
2178
0
                                               PR_FALSE, PR_TRUE, NULL);
2179
0
        PK11SlotListElement *le;
2180
2181
0
        if (!list) {
2182
            /* error code is set */
2183
0
            return SECFailure;
2184
0
        }
2185
        /* loop through all the tokens */
2186
0
        for (le = list->head; le; le = le->next) {
2187
0
            PK11_TraverseCertsForSubjectInSlot(cert, le->slot, callback, arg);
2188
0
        }
2189
0
        PK11_FreeSlotList(list);
2190
0
        return SECSuccess;
2191
0
    }
2192
2193
0
    return PK11_TraverseCertsForSubjectInSlot(cert, cert->slot, callback, arg);
2194
0
}
2195
2196
SECStatus
2197
PK11_TraverseCertsForSubjectInSlot(CERTCertificate *cert, PK11SlotInfo *slot,
2198
                                   SECStatus (*callback)(CERTCertificate *, void *), void *arg)
2199
0
{
2200
0
    PRStatus nssrv = PR_SUCCESS;
2201
0
    NSSToken *token;
2202
0
    NSSDER subject;
2203
0
    NSSTrustDomain *td;
2204
0
    nssList *subjectList;
2205
0
    nssPKIObjectCollection *collection;
2206
0
    nssCryptokiObject **instances;
2207
0
    NSSCertificate **certs;
2208
0
    nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
2209
0
    td = STAN_GetDefaultTrustDomain();
2210
0
    NSSITEM_FROM_SECITEM(&subject, &cert->derSubject);
2211
0
    token = PK11Slot_GetNSSToken(slot);
2212
0
    if (!token) {
2213
0
        return SECSuccess;
2214
0
    }
2215
0
    if (!nssToken_IsPresent(token)) {
2216
0
        (void)nssToken_Destroy(token);
2217
0
        return SECSuccess;
2218
0
    }
2219
0
    collection = nssCertificateCollection_Create(td, NULL);
2220
0
    if (!collection) {
2221
0
        (void)nssToken_Destroy(token);
2222
0
        return SECFailure;
2223
0
    }
2224
0
    subjectList = nssList_Create(NULL, PR_FALSE);
2225
0
    if (!subjectList) {
2226
0
        nssPKIObjectCollection_Destroy(collection);
2227
0
        (void)nssToken_Destroy(token);
2228
0
        return SECFailure;
2229
0
    }
2230
0
    (void)nssTrustDomain_GetCertsForSubjectFromCache(td, &subject,
2231
0
                                                     subjectList);
2232
0
    transfer_token_certs_to_collection(subjectList, token, collection);
2233
0
    instances = nssToken_FindCertificatesBySubject(token, NULL,
2234
0
                                                   &subject,
2235
0
                                                   tokenOnly, 0, &nssrv);
2236
0
    nssPKIObjectCollection_AddInstances(collection, instances, 0);
2237
0
    nss_ZFreeIf(instances);
2238
0
    nssList_Destroy(subjectList);
2239
0
    certs = nssPKIObjectCollection_GetCertificates(collection,
2240
0
                                                   NULL, 0, NULL);
2241
0
    nssPKIObjectCollection_Destroy(collection);
2242
0
    (void)nssToken_Destroy(token);
2243
0
    if (certs) {
2244
0
        CERTCertificate *oldie;
2245
0
        NSSCertificate **cp;
2246
0
        for (cp = certs; *cp; cp++) {
2247
0
            oldie = STAN_GetCERTCertificate(*cp);
2248
0
            if (!oldie) {
2249
0
                continue;
2250
0
            }
2251
0
            if ((*callback)(oldie, arg) != SECSuccess) {
2252
0
                nssrv = PR_FAILURE;
2253
0
                break;
2254
0
            }
2255
0
        }
2256
0
        nssCertificateArray_Destroy(certs);
2257
0
    }
2258
0
    return (nssrv == PR_SUCCESS) ? SECSuccess : SECFailure;
2259
0
}
2260
2261
SECStatus
2262
PK11_TraverseCertsForNicknameInSlot(SECItem *nickname, PK11SlotInfo *slot,
2263
                                    SECStatus (*callback)(CERTCertificate *, void *), void *arg)
2264
0
{
2265
0
    PRStatus nssrv = PR_SUCCESS;
2266
0
    NSSToken *token;
2267
0
    NSSTrustDomain *td;
2268
0
    NSSUTF8 *nick;
2269
0
    PRBool created = PR_FALSE;
2270
0
    nssCryptokiObject **instances;
2271
0
    nssPKIObjectCollection *collection = NULL;
2272
0
    NSSCertificate **certs;
2273
0
    nssList *nameList = NULL;
2274
0
    nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
2275
0
    token = PK11Slot_GetNSSToken(slot);
2276
0
    if (!token || !nssToken_IsPresent(token)) {
2277
0
        (void)nssToken_Destroy(token);
2278
0
        return SECSuccess;
2279
0
    }
2280
0
    if (nickname->data[nickname->len - 1] != '\0') {
2281
0
        nick = nssUTF8_Create(NULL, nssStringType_UTF8String,
2282
0
                              nickname->data, nickname->len);
2283
0
        created = PR_TRUE;
2284
0
    } else {
2285
0
        nick = (NSSUTF8 *)nickname->data;
2286
0
    }
2287
0
    td = STAN_GetDefaultTrustDomain();
2288
0
    collection = nssCertificateCollection_Create(td, NULL);
2289
0
    if (!collection) {
2290
0
        goto loser;
2291
0
    }
2292
0
    nameList = nssList_Create(NULL, PR_FALSE);
2293
0
    if (!nameList) {
2294
0
        goto loser;
2295
0
    }
2296
0
    (void)nssTrustDomain_GetCertsForNicknameFromCache(td, nick, nameList);
2297
0
    transfer_token_certs_to_collection(nameList, token, collection);
2298
0
    instances = nssToken_FindCertificatesByNickname(token, NULL,
2299
0
                                                    nick,
2300
0
                                                    tokenOnly, 0, &nssrv);
2301
0
    nssPKIObjectCollection_AddInstances(collection, instances, 0);
2302
0
    nss_ZFreeIf(instances);
2303
0
    nssList_Destroy(nameList);
2304
0
    certs = nssPKIObjectCollection_GetCertificates(collection,
2305
0
                                                   NULL, 0, NULL);
2306
0
    nssPKIObjectCollection_Destroy(collection);
2307
0
    (void)nssToken_Destroy(token);
2308
0
    if (certs) {
2309
0
        CERTCertificate *oldie;
2310
0
        NSSCertificate **cp;
2311
0
        for (cp = certs; *cp; cp++) {
2312
0
            oldie = STAN_GetCERTCertificate(*cp);
2313
0
            if (!oldie) {
2314
0
                continue;
2315
0
            }
2316
0
            if ((*callback)(oldie, arg) != SECSuccess) {
2317
0
                nssrv = PR_FAILURE;
2318
0
                break;
2319
0
            }
2320
0
        }
2321
0
        nssCertificateArray_Destroy(certs);
2322
0
    }
2323
0
    if (created)
2324
0
        nss_ZFreeIf(nick);
2325
0
    return (nssrv == PR_SUCCESS) ? SECSuccess : SECFailure;
2326
0
loser:
2327
0
    (void)nssToken_Destroy(token);
2328
0
    if (created) {
2329
0
        nss_ZFreeIf(nick);
2330
0
    }
2331
0
    if (collection) {
2332
0
        nssPKIObjectCollection_Destroy(collection);
2333
0
    }
2334
0
    if (nameList) {
2335
0
        nssList_Destroy(nameList);
2336
0
    }
2337
0
    return SECFailure;
2338
0
}
2339
2340
SECStatus
2341
PK11_TraverseCertsInSlot(PK11SlotInfo *slot,
2342
                         SECStatus (*callback)(CERTCertificate *, void *), void *arg)
2343
0
{
2344
0
    PRStatus nssrv;
2345
0
    NSSTrustDomain *td = STAN_GetDefaultTrustDomain();
2346
0
    NSSToken *tok;
2347
0
    nssList *certList = NULL;
2348
0
    nssCryptokiObject **instances;
2349
0
    nssPKIObjectCollection *collection;
2350
0
    NSSCertificate **certs;
2351
0
    nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
2352
0
    tok = PK11Slot_GetNSSToken(slot);
2353
0
    if (!tok) {
2354
0
        return SECSuccess;
2355
0
    }
2356
0
    if (!nssToken_IsPresent(tok)) {
2357
0
        (void)nssToken_Destroy(tok);
2358
0
        return SECSuccess;
2359
0
    }
2360
0
    collection = nssCertificateCollection_Create(td, NULL);
2361
0
    if (!collection) {
2362
0
        (void)nssToken_Destroy(tok);
2363
0
        return SECFailure;
2364
0
    }
2365
0
    certList = nssList_Create(NULL, PR_FALSE);
2366
0
    if (!certList) {
2367
0
        nssPKIObjectCollection_Destroy(collection);
2368
0
        (void)nssToken_Destroy(tok);
2369
0
        return SECFailure;
2370
0
    }
2371
0
    (void)nssTrustDomain_GetCertsFromCache(td, certList);
2372
0
    transfer_token_certs_to_collection(certList, tok, collection);
2373
0
    instances = nssToken_FindObjects(tok, NULL, CKO_CERTIFICATE,
2374
0
                                     tokenOnly, 0, &nssrv);
2375
0
    nssPKIObjectCollection_AddInstances(collection, instances, 0);
2376
0
    nss_ZFreeIf(instances);
2377
0
    nssList_Destroy(certList);
2378
0
    certs = nssPKIObjectCollection_GetCertificates(collection,
2379
0
                                                   NULL, 0, NULL);
2380
0
    nssPKIObjectCollection_Destroy(collection);
2381
0
    (void)nssToken_Destroy(tok);
2382
0
    if (certs) {
2383
0
        CERTCertificate *oldie;
2384
0
        NSSCertificate **cp;
2385
0
        for (cp = certs; *cp; cp++) {
2386
0
            oldie = STAN_GetCERTCertificate(*cp);
2387
0
            if (!oldie) {
2388
0
                continue;
2389
0
            }
2390
0
            if ((*callback)(oldie, arg) != SECSuccess) {
2391
0
                nssrv = PR_FAILURE;
2392
0
                break;
2393
0
            }
2394
0
        }
2395
0
        nssCertificateArray_Destroy(certs);
2396
0
    }
2397
0
    return (nssrv == PR_SUCCESS) ? SECSuccess : SECFailure;
2398
0
}
2399
2400
/*
2401
 * return the certificate associated with a derCert
2402
 */
2403
CERTCertificate *
2404
PK11_FindCertFromDERCert(PK11SlotInfo *slot, CERTCertificate *cert,
2405
                         void *wincx)
2406
0
{
2407
0
    return PK11_FindCertFromDERCertItem(slot, &cert->derCert, wincx);
2408
0
}
2409
2410
CERTCertificate *
2411
PK11_FindCertFromDERCertItem(PK11SlotInfo *slot, const SECItem *inDerCert,
2412
                             void *wincx)
2413
2414
0
{
2415
0
    NSSDER derCert;
2416
0
    NSSToken *tok;
2417
0
    nssCryptokiObject *co = NULL;
2418
0
    SECStatus rv;
2419
0
    CERTCertificate *cert = NULL;
2420
2421
0
    NSSITEM_FROM_SECITEM(&derCert, inDerCert);
2422
0
    rv = pk11_AuthenticateUnfriendly(slot, PR_TRUE, wincx);
2423
0
    if (rv != SECSuccess) {
2424
0
        PK11_FreeSlot(slot);
2425
0
        return NULL;
2426
0
    }
2427
2428
0
    tok = PK11Slot_GetNSSToken(slot);
2429
0
    if (!tok) {
2430
0
        PK11_FreeSlot(slot);
2431
0
        return NULL;
2432
0
    }
2433
0
    co = nssToken_FindCertificateByEncodedCertificate(tok, NULL, &derCert,
2434
0
                                                      nssTokenSearchType_TokenOnly, NULL);
2435
0
    (void)nssToken_Destroy(tok);
2436
2437
0
    if (co) {
2438
0
        cert = PK11_MakeCertFromHandle(slot, co->handle, NULL);
2439
0
        nssCryptokiObject_Destroy(co);
2440
0
    }
2441
2442
0
    return cert;
2443
0
}
2444
2445
/*
2446
 * import a cert for a private key we have already generated. Set the label
2447
 * on both to be the nickname.
2448
 */
2449
static CK_OBJECT_HANDLE
2450
pk11_findKeyObjectByDERCert(PK11SlotInfo *slot, CERTCertificate *cert,
2451
                            void *wincx)
2452
0
{
2453
0
    SECItem *keyID;
2454
0
    CK_OBJECT_HANDLE key;
2455
0
    SECStatus rv;
2456
0
    PRBool needLogin;
2457
0
    int err;
2458
2459
0
    if ((slot == NULL) || (cert == NULL)) {
2460
0
        return CK_INVALID_HANDLE;
2461
0
    }
2462
2463
0
    keyID = pk11_mkcertKeyID(cert);
2464
0
    if (keyID == NULL) {
2465
0
        return CK_INVALID_HANDLE;
2466
0
    }
2467
2468
    /*
2469
     * prevent a login race condition. If slot is logged in between
2470
     * our call to pk11_LoginStillRequired and the
2471
     * pk11_FindPrivateKeyFromCerID. The matchItem call will either succeed, or
2472
     * we will call it one more time after calling PK11_Authenticate
2473
     * (which is a noop on an authenticated token).
2474
     */
2475
0
    needLogin = pk11_LoginStillRequired(slot, wincx);
2476
0
    key = pk11_FindPrivateKeyFromCertID(slot, keyID);
2477
0
    if ((key == CK_INVALID_HANDLE) && needLogin &&
2478
0
        (SSL_ERROR_NO_CERTIFICATE == (err = PORT_GetError()) ||
2479
0
         SEC_ERROR_TOKEN_NOT_LOGGED_IN == err)) {
2480
        /* authenticate and try again */
2481
0
        rv = PK11_Authenticate(slot, PR_TRUE, wincx);
2482
0
        if (rv != SECSuccess)
2483
0
            goto loser;
2484
0
        key = pk11_FindPrivateKeyFromCertID(slot, keyID);
2485
0
    }
2486
2487
0
loser:
2488
0
    SECITEM_ZfreeItem(keyID, PR_TRUE);
2489
0
    return key;
2490
0
}
2491
2492
SECKEYPrivateKey *
2493
PK11_FindKeyByDERCert(PK11SlotInfo *slot, CERTCertificate *cert,
2494
                      void *wincx)
2495
0
{
2496
0
    CK_OBJECT_HANDLE keyHandle;
2497
2498
0
    if ((slot == NULL) || (cert == NULL)) {
2499
0
        return NULL;
2500
0
    }
2501
2502
0
    keyHandle = pk11_findKeyObjectByDERCert(slot, cert, wincx);
2503
0
    if (keyHandle == CK_INVALID_HANDLE) {
2504
0
        return NULL;
2505
0
    }
2506
2507
0
    return PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyHandle, wincx);
2508
0
}
2509
2510
SECStatus
2511
PK11_ImportCertForKeyToSlot(PK11SlotInfo *slot, CERTCertificate *cert,
2512
                            char *nickname,
2513
                            PRBool addCertUsage, void *wincx)
2514
0
{
2515
0
    CK_OBJECT_HANDLE keyHandle;
2516
2517
0
    if ((slot == NULL) || (cert == NULL) || (nickname == NULL)) {
2518
0
        return SECFailure;
2519
0
    }
2520
2521
0
    keyHandle = pk11_findKeyObjectByDERCert(slot, cert, wincx);
2522
0
    if (keyHandle == CK_INVALID_HANDLE) {
2523
0
        return SECFailure;
2524
0
    }
2525
2526
0
    return PK11_ImportCert(slot, cert, keyHandle, nickname, addCertUsage);
2527
0
}
2528
2529
/* remove when the real version comes out */
2530
0
#define SEC_OID_MISSI_KEA 300 /* until we have v3 stuff merged */
2531
PRBool
2532
KEAPQGCompare(CERTCertificate *server, CERTCertificate *cert)
2533
0
{
2534
2535
    /* not implemented */
2536
0
    return PR_FALSE;
2537
0
}
2538
2539
PRBool
2540
PK11_FortezzaHasKEA(CERTCertificate *cert)
2541
0
{
2542
    /* look at the subject and see if it is a KEA for MISSI key */
2543
0
    SECOidData *oid;
2544
0
    CERTCertTrust trust;
2545
2546
0
    if (CERT_GetCertTrust(cert, &trust) != SECSuccess ||
2547
0
        ((trust.sslFlags & CERTDB_USER) != CERTDB_USER)) {
2548
0
        return PR_FALSE;
2549
0
    }
2550
2551
0
    oid = SECOID_FindOID(&cert->subjectPublicKeyInfo.algorithm.algorithm);
2552
0
    if (!oid) {
2553
0
        return PR_FALSE;
2554
0
    }
2555
2556
0
    return (PRBool)((oid->offset == SEC_OID_MISSI_KEA_DSS_OLD) ||
2557
0
                    (oid->offset == SEC_OID_MISSI_KEA_DSS) ||
2558
0
                    (oid->offset == SEC_OID_MISSI_KEA));
2559
0
}
2560
2561
/*
2562
 * Find a kea cert on this slot that matches the domain of it's peer
2563
 */
2564
static CERTCertificate
2565
    *
2566
    pk11_GetKEAMate(PK11SlotInfo *slot, CERTCertificate *peer)
2567
0
{
2568
0
    int i;
2569
0
    CERTCertificate *returnedCert = NULL;
2570
2571
0
    for (i = 0; i < slot->cert_count; i++) {
2572
0
        CERTCertificate *cert = slot->cert_array[i];
2573
2574
0
        if (PK11_FortezzaHasKEA(cert) && KEAPQGCompare(peer, cert)) {
2575
0
            returnedCert = CERT_DupCertificate(cert);
2576
0
            break;
2577
0
        }
2578
0
    }
2579
0
    return returnedCert;
2580
0
}
2581
2582
/*
2583
 * The following is a FORTEZZA only Certificate request. We call this when we
2584
 * are doing a non-client auth SSL connection. We are only interested in the
2585
 * fortezza slots, and we are only interested in certs that share the same root
2586
 * key as the server.
2587
 */
2588
CERTCertificate *
2589
PK11_FindBestKEAMatch(CERTCertificate *server, void *wincx)
2590
0
{
2591
0
    PK11SlotList *keaList = PK11_GetAllTokens(CKM_KEA_KEY_DERIVE,
2592
0
                                              PR_FALSE, PR_TRUE, wincx);
2593
0
    PK11SlotListElement *le;
2594
0
    CERTCertificate *returnedCert = NULL;
2595
0
    SECStatus rv;
2596
2597
0
    if (!keaList) {
2598
        /* error code is set */
2599
0
        return NULL;
2600
0
    }
2601
2602
    /* loop through all the fortezza tokens */
2603
0
    for (le = keaList->head; le; le = le->next) {
2604
0
        rv = PK11_Authenticate(le->slot, PR_TRUE, wincx);
2605
0
        if (rv != SECSuccess)
2606
0
            continue;
2607
0
        if (le->slot->session == CK_INVALID_HANDLE) {
2608
0
            continue;
2609
0
        }
2610
0
        returnedCert = pk11_GetKEAMate(le->slot, server);
2611
0
        if (returnedCert)
2612
0
            break;
2613
0
    }
2614
0
    PK11_FreeSlotList(keaList);
2615
2616
0
    return returnedCert;
2617
0
}
2618
2619
/*
2620
 * find a matched pair of kea certs to key exchange parameters from one
2621
 * fortezza card to another as necessary.
2622
 */
2623
SECStatus
2624
PK11_GetKEAMatchedCerts(PK11SlotInfo *slot1, PK11SlotInfo *slot2,
2625
                        CERTCertificate **cert1, CERTCertificate **cert2)
2626
0
{
2627
0
    CERTCertificate *returnedCert = NULL;
2628
0
    int i;
2629
2630
0
    for (i = 0; i < slot1->cert_count; i++) {
2631
0
        CERTCertificate *cert = slot1->cert_array[i];
2632
2633
0
        if (PK11_FortezzaHasKEA(cert)) {
2634
0
            returnedCert = pk11_GetKEAMate(slot2, cert);
2635
0
            if (returnedCert != NULL) {
2636
0
                *cert2 = returnedCert;
2637
0
                *cert1 = CERT_DupCertificate(cert);
2638
0
                return SECSuccess;
2639
0
            }
2640
0
        }
2641
0
    }
2642
0
    return SECFailure;
2643
0
}
2644
2645
CK_OBJECT_HANDLE
2646
PK11_FindEncodedCertInSlot(PK11SlotInfo *slot, SECItem *derCert, void *wincx)
2647
0
{
2648
0
    if (!slot || !derCert) {
2649
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2650
0
        return SECFailure;
2651
0
    }
2652
2653
0
    CK_OBJECT_CLASS certClass = CKO_CERTIFICATE;
2654
0
    CK_ATTRIBUTE theTemplate[] = {
2655
0
        { CKA_VALUE, NULL, 0 },
2656
0
        { CKA_CLASS, NULL, 0 }
2657
0
    };
2658
0
    const size_t tsize = sizeof(theTemplate) / sizeof(theTemplate[0]);
2659
0
    CK_ATTRIBUTE *attrs = theTemplate;
2660
2661
0
    PK11_SETATTRS(attrs, CKA_VALUE, derCert->data, derCert->len);
2662
0
    attrs++;
2663
0
    PK11_SETATTRS(attrs, CKA_CLASS, &certClass, sizeof(certClass));
2664
2665
0
    SECStatus rv = pk11_AuthenticateUnfriendly(slot, PR_TRUE, wincx);
2666
0
    if (rv != SECSuccess) {
2667
0
        return CK_INVALID_HANDLE;
2668
0
    }
2669
2670
0
    return pk11_FindObjectByTemplate(slot, theTemplate, tsize);
2671
0
}
2672
2673
CK_OBJECT_HANDLE
2674
PK11_FindCertInSlot(PK11SlotInfo *slot, CERTCertificate *cert, void *wincx)
2675
0
{
2676
0
    CK_OBJECT_HANDLE certh;
2677
2678
0
    if (cert->slot == slot) {
2679
0
        certh = cert->pkcs11ID;
2680
0
        if ((certh == CK_INVALID_HANDLE) ||
2681
0
            (cert->series != slot->series)) {
2682
0
            certh = PK11_FindEncodedCertInSlot(slot, &cert->derCert, wincx);
2683
0
            cert->pkcs11ID = certh;
2684
0
            cert->series = slot->series;
2685
0
        }
2686
0
    } else {
2687
0
        certh = PK11_FindEncodedCertInSlot(slot, &cert->derCert, wincx);
2688
0
    }
2689
0
    return certh;
2690
0
}
2691
2692
/* Looking for PK11_GetKeyIDFromCert?
2693
 * Use PK11_GetLowLevelKeyIDForCert instead.
2694
 */
2695
2696
struct listCertsStr {
2697
    PK11CertListType type;
2698
    CERTCertList *certList;
2699
};
2700
2701
static PRStatus
2702
pk11ListCertCallback(NSSCertificate *c, void *arg)
2703
0
{
2704
0
    struct listCertsStr *listCertP = (struct listCertsStr *)arg;
2705
0
    CERTCertificate *newCert = NULL;
2706
0
    PK11CertListType type = listCertP->type;
2707
0
    CERTCertList *certList = listCertP->certList;
2708
0
    PRBool isUnique = PR_FALSE;
2709
0
    PRBool isCA = PR_FALSE;
2710
0
    char *nickname = NULL;
2711
0
    unsigned int certType;
2712
0
    SECStatus rv;
2713
2714
0
    if ((type == PK11CertListUnique) || (type == PK11CertListRootUnique) ||
2715
0
        (type == PK11CertListCAUnique) || (type == PK11CertListUserUnique)) {
2716
        /* only list one instance of each certificate, even if several exist */
2717
0
        isUnique = PR_TRUE;
2718
0
    }
2719
0
    if ((type == PK11CertListCA) || (type == PK11CertListRootUnique) ||
2720
0
        (type == PK11CertListCAUnique)) {
2721
0
        isCA = PR_TRUE;
2722
0
    }
2723
2724
    /* if we want user certs and we don't have one skip this cert */
2725
0
    if (((type == PK11CertListUser) || (type == PK11CertListUserUnique)) &&
2726
0
        !NSSCertificate_IsPrivateKeyAvailable(c, NULL, NULL)) {
2727
0
        return PR_SUCCESS;
2728
0
    }
2729
2730
    /* PK11CertListRootUnique means we want CA certs without a private key.
2731
     * This is for legacy app support . PK11CertListCAUnique should be used
2732
     * instead to get all CA certs, regardless of private key
2733
     */
2734
0
    if ((type == PK11CertListRootUnique) &&
2735
0
        NSSCertificate_IsPrivateKeyAvailable(c, NULL, NULL)) {
2736
0
        return PR_SUCCESS;
2737
0
    }
2738
2739
    /* caller still owns the reference to 'c' */
2740
0
    newCert = STAN_GetCERTCertificate(c);
2741
0
    if (!newCert) {
2742
0
        return PR_SUCCESS;
2743
0
    }
2744
    /* if we want CA certs and it ain't one, skip it */
2745
0
    if (isCA && (!CERT_IsCACert(newCert, &certType))) {
2746
0
        return PR_SUCCESS;
2747
0
    }
2748
0
    if (isUnique) {
2749
0
        CERT_DupCertificate(newCert);
2750
2751
0
        nickname = STAN_GetCERTCertificateName(certList->arena, c);
2752
2753
        /* put slot certs at the end */
2754
0
        if (newCert->slot && !PK11_IsInternal(newCert->slot)) {
2755
0
            rv = CERT_AddCertToListTailWithData(certList, newCert, nickname);
2756
0
        } else {
2757
0
            rv = CERT_AddCertToListHeadWithData(certList, newCert, nickname);
2758
0
        }
2759
        /* if we didn't add the cert to the list, don't leak it */
2760
0
        if (rv != SECSuccess) {
2761
0
            CERT_DestroyCertificate(newCert);
2762
0
        }
2763
0
    } else {
2764
        /* add multiple instances to the cert list */
2765
0
        nssCryptokiObject **ip;
2766
0
        nssCryptokiObject **instances = nssPKIObject_GetInstances(&c->object);
2767
0
        if (!instances) {
2768
0
            return PR_SUCCESS;
2769
0
        }
2770
0
        for (ip = instances; *ip; ip++) {
2771
0
            nssCryptokiObject *instance = *ip;
2772
0
            PK11SlotInfo *slot = instance->token->pk11slot;
2773
2774
            /* put the same CERTCertificate in the list for all instances */
2775
0
            CERT_DupCertificate(newCert);
2776
2777
0
            nickname = STAN_GetCERTCertificateNameForInstance(
2778
0
                certList->arena, c, instance);
2779
2780
            /* put slot certs at the end */
2781
0
            if (slot && !PK11_IsInternal(slot)) {
2782
0
                rv = CERT_AddCertToListTailWithData(certList, newCert, nickname);
2783
0
            } else {
2784
0
                rv = CERT_AddCertToListHeadWithData(certList, newCert, nickname);
2785
0
            }
2786
            /* if we didn't add the cert to the list, don't leak it */
2787
0
            if (rv != SECSuccess) {
2788
0
                CERT_DestroyCertificate(newCert);
2789
0
            }
2790
0
        }
2791
0
        nssCryptokiObjectArray_Destroy(instances);
2792
0
    }
2793
0
    return PR_SUCCESS;
2794
0
}
2795
2796
CERTCertList *
2797
PK11_ListCerts(PK11CertListType type, void *pwarg)
2798
0
{
2799
0
    NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
2800
0
    CERTCertList *certList = NULL;
2801
0
    struct listCertsStr listCerts;
2802
0
    certList = CERT_NewCertList();
2803
0
    listCerts.type = type;
2804
0
    listCerts.certList = certList;
2805
2806
    /* authenticate to the slots */
2807
0
    (void)pk11_TraverseAllSlots(NULL, NULL, PR_TRUE, pwarg);
2808
0
    NSSTrustDomain_TraverseCertificates(defaultTD, pk11ListCertCallback,
2809
0
                                        &listCerts);
2810
0
    return certList;
2811
0
}
2812
2813
SECItem *
2814
PK11_GetLowLevelKeyIDForCert(PK11SlotInfo *slot,
2815
                             CERTCertificate *cert, void *wincx)
2816
0
{
2817
0
    CK_OBJECT_HANDLE certHandle;
2818
0
    PK11SlotInfo *slotRef = NULL;
2819
0
    SECItem *item;
2820
2821
0
    if (slot) {
2822
0
        certHandle = PK11_FindCertInSlot(slot, cert, wincx);
2823
0
    } else {
2824
0
        certHandle = PK11_FindObjectForCert(cert, wincx, &slotRef);
2825
0
        if (certHandle == CK_INVALID_HANDLE) {
2826
0
            return pk11_mkcertKeyID(cert);
2827
0
        }
2828
0
        slot = slotRef;
2829
0
    }
2830
2831
0
    if (certHandle == CK_INVALID_HANDLE) {
2832
0
        return NULL;
2833
0
    }
2834
2835
0
    item = pk11_GetLowLevelKeyFromHandle(slot, certHandle);
2836
0
    if (slotRef)
2837
0
        PK11_FreeSlot(slotRef);
2838
0
    return item;
2839
0
}
2840
2841
/* argument type for listCertsCallback */
2842
typedef struct {
2843
    CERTCertList *list;
2844
    PK11SlotInfo *slot;
2845
} ListCertsArg;
2846
2847
static SECStatus
2848
listCertsCallback(CERTCertificate *cert, void *arg)
2849
0
{
2850
0
    ListCertsArg *cdata = (ListCertsArg *)arg;
2851
0
    char *nickname = NULL;
2852
0
    nssCryptokiObject *instance, **ci;
2853
0
    nssCryptokiObject **instances;
2854
0
    NSSCertificate *c = STAN_GetNSSCertificate(cert);
2855
0
    SECStatus rv;
2856
2857
0
    if (c == NULL) {
2858
0
        return SECFailure;
2859
0
    }
2860
0
    instances = nssPKIObject_GetInstances(&c->object);
2861
0
    if (!instances) {
2862
0
        return SECFailure;
2863
0
    }
2864
0
    instance = NULL;
2865
0
    for (ci = instances; *ci; ci++) {
2866
0
        if ((*ci)->token->pk11slot == cdata->slot) {
2867
0
            instance = *ci;
2868
0
            break;
2869
0
        }
2870
0
    }
2871
0
    PORT_Assert(instance != NULL);
2872
0
    if (!instance) {
2873
0
        nssCryptokiObjectArray_Destroy(instances);
2874
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2875
0
        return SECFailure;
2876
0
    }
2877
0
    nickname = STAN_GetCERTCertificateNameForInstance(cdata->list->arena,
2878
0
                                                      c, instance);
2879
0
    nssCryptokiObjectArray_Destroy(instances);
2880
2881
0
    CERT_DupCertificate(cert);
2882
0
    rv = CERT_AddCertToListTailWithData(cdata->list, cert, nickname);
2883
0
    if (rv != SECSuccess) {
2884
0
        CERT_DestroyCertificate(cert);
2885
0
    }
2886
0
    return rv;
2887
0
}
2888
2889
CERTCertList *
2890
PK11_ListCertsInSlot(PK11SlotInfo *slot)
2891
0
{
2892
0
    SECStatus status;
2893
0
    CERTCertList *certs;
2894
0
    ListCertsArg cdata;
2895
2896
0
    certs = CERT_NewCertList();
2897
0
    if (certs == NULL)
2898
0
        return NULL;
2899
0
    cdata.list = certs;
2900
0
    cdata.slot = slot;
2901
2902
0
    status = PK11_TraverseCertsInSlot(slot, listCertsCallback,
2903
0
                                      &cdata);
2904
2905
0
    if (status != SECSuccess) {
2906
0
        CERT_DestroyCertList(certs);
2907
0
        certs = NULL;
2908
0
    }
2909
2910
0
    return certs;
2911
0
}
2912
2913
PK11SlotList *
2914
PK11_GetAllSlotsForCert(CERTCertificate *cert, void *arg)
2915
0
{
2916
0
    nssCryptokiObject **ip;
2917
0
    PK11SlotList *slotList;
2918
0
    NSSCertificate *c;
2919
0
    nssCryptokiObject **instances;
2920
0
    PRBool found = PR_FALSE;
2921
2922
0
    if (!cert) {
2923
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2924
0
        return NULL;
2925
0
    }
2926
2927
0
    c = STAN_GetNSSCertificate(cert);
2928
0
    if (!c) {
2929
0
        CERT_MapStanError();
2930
0
        return NULL;
2931
0
    }
2932
2933
    /* add multiple instances to the cert list */
2934
0
    instances = nssPKIObject_GetInstances(&c->object);
2935
0
    if (!instances) {
2936
0
        PORT_SetError(SEC_ERROR_NO_TOKEN);
2937
0
        return NULL;
2938
0
    }
2939
2940
0
    slotList = PK11_NewSlotList();
2941
0
    if (!slotList) {
2942
0
        nssCryptokiObjectArray_Destroy(instances);
2943
0
        return NULL;
2944
0
    }
2945
2946
0
    for (ip = instances; *ip; ip++) {
2947
0
        nssCryptokiObject *instance = *ip;
2948
0
        PK11SlotInfo *slot = instance->token->pk11slot;
2949
0
        if (slot) {
2950
0
            PK11_AddSlotToList(slotList, slot, PR_TRUE);
2951
0
            found = PR_TRUE;
2952
0
        }
2953
0
    }
2954
0
    if (!found) {
2955
0
        PK11_FreeSlotList(slotList);
2956
0
        PORT_SetError(SEC_ERROR_NO_TOKEN);
2957
0
        slotList = NULL;
2958
0
    }
2959
2960
0
    nssCryptokiObjectArray_Destroy(instances);
2961
0
    return slotList;
2962
0
}
2963
2964
/*
2965
 * Using __PK11_SetCertificateNickname is *DANGEROUS*.
2966
 *
2967
 * The API will update the NSS database, but it *will NOT* update the in-memory data.
2968
 * As a result, after calling this API, there will be INCONSISTENCY between
2969
 * in-memory data and the database.
2970
 *
2971
 * Use of the API should be limited to short-lived tools, which will exit immediately
2972
 * after using this API.
2973
 *
2974
 * If you ignore this warning, your process is TAINTED and will most likely misbehave.
2975
 */
2976
SECStatus
2977
__PK11_SetCertificateNickname(CERTCertificate *cert, const char *nickname)
2978
0
{
2979
    /* Can't set nickname of temp cert. */
2980
0
    if (!cert->slot || cert->pkcs11ID == CK_INVALID_HANDLE) {
2981
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2982
0
        return SECFailure;
2983
0
    }
2984
0
    return PK11_SetObjectNickname(cert->slot, cert->pkcs11ID, nickname);
2985
0
}