Coverage Report

Created: 2025-06-24 06:49

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