/
pk11cert.c
2931 lines (2630 loc) · 90.3 KB
/
pk11cert.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* This file manages PKCS #11 instances of certificates.
*/
#include <stddef.h>
#include "secport.h"
#include "seccomon.h"
#include "secmod.h"
#include "secmodi.h"
#include "secmodti.h"
#include "pkcs11.h"
#include "pk11func.h"
#include "cert.h"
#include "certi.h"
#include "secitem.h"
#include "keyhi.h"
#include "secoid.h"
#include "pkcs7t.h"
#include "cmsreclist.h"
#include "certdb.h"
#include "secerr.h"
#include "sslerr.h"
#include "pki3hack.h"
#include "dev3hack.h"
#include "devm.h"
#include "nsspki.h"
#include "pki.h"
#include "pkim.h"
#include "pkitm.h"
#include "pkistore.h" /* to remove temp cert */
#include "devt.h"
#include "ckhelper.h"
#include "pkcs11uri.h"
extern const NSSError NSS_ERROR_NOT_FOUND;
extern const NSSError NSS_ERROR_INVALID_CERTIFICATE;
struct nss3_cert_cbstr {
SECStatus (*callback)(CERTCertificate *, void *);
nssList *cached;
void *arg;
};
/* Translate from NSSCertificate to CERTCertificate, then pass the latter
* to a callback.
*/
static PRStatus
convert_cert(NSSCertificate *c, void *arg)
{
CERTCertificate *nss3cert;
SECStatus secrv;
struct nss3_cert_cbstr *nss3cb = (struct nss3_cert_cbstr *)arg;
/* 'c' is not adopted. caller will free it */
nss3cert = STAN_GetCERTCertificate(c);
if (!nss3cert)
return PR_FAILURE;
secrv = (*nss3cb->callback)(nss3cert, nss3cb->arg);
return (secrv) ? PR_FAILURE : PR_SUCCESS;
}
/*
* build a cert nickname based on the token name and the label of the
* certificate If the label in NULL, build a label based on the ID.
*/
static int
toHex(int x)
{
return (x < 10) ? (x + '0') : (x + 'a' - 10);
}
#define MAX_CERT_ID 4
#define DEFAULT_STRING "Cert ID "
static char *
pk11_buildNickname(PK11SlotInfo *slot, CK_ATTRIBUTE *cert_label,
CK_ATTRIBUTE *key_label, CK_ATTRIBUTE *cert_id)
{
int prefixLen = PORT_Strlen(slot->token_name);
int suffixLen = 0;
char *suffix = NULL;
char buildNew[sizeof(DEFAULT_STRING) + MAX_CERT_ID * 2];
char *next, *nickname;
if (cert_label && (cert_label->ulValueLen)) {
suffixLen = cert_label->ulValueLen;
suffix = (char *)cert_label->pValue;
} else if (key_label && (key_label->ulValueLen)) {
suffixLen = key_label->ulValueLen;
suffix = (char *)key_label->pValue;
} else if (cert_id && cert_id->ulValueLen > 0) {
int i, first = cert_id->ulValueLen - MAX_CERT_ID;
int offset = sizeof(DEFAULT_STRING);
char *idValue = (char *)cert_id->pValue;
PORT_Memcpy(buildNew, DEFAULT_STRING, sizeof(DEFAULT_STRING) - 1);
next = buildNew + offset;
if (first < 0)
first = 0;
for (i = first; i < (int)cert_id->ulValueLen; i++) {
*next++ = toHex((idValue[i] >> 4) & 0xf);
*next++ = toHex(idValue[i] & 0xf);
}
*next++ = 0;
suffix = buildNew;
suffixLen = PORT_Strlen(buildNew);
} else {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return NULL;
}
/* if is internal key slot, add code to skip the prefix!! */
next = nickname = (char *)PORT_Alloc(prefixLen + 1 + suffixLen + 1);
if (nickname == NULL)
return NULL;
PORT_Memcpy(next, slot->token_name, prefixLen);
next += prefixLen;
*next++ = ':';
PORT_Memcpy(next, suffix, suffixLen);
next += suffixLen;
*next++ = 0;
return nickname;
}
PRBool
PK11_IsUserCert(PK11SlotInfo *slot, CERTCertificate *cert,
CK_OBJECT_HANDLE certID)
{
CK_OBJECT_CLASS theClass;
if (slot == NULL)
return PR_FALSE;
if (cert == NULL)
return PR_FALSE;
theClass = CKO_PRIVATE_KEY;
if (pk11_LoginStillRequired(slot, NULL)) {
theClass = CKO_PUBLIC_KEY;
}
if (PK11_MatchItem(slot, certID, theClass) != CK_INVALID_HANDLE) {
return PR_TRUE;
}
if (theClass == CKO_PUBLIC_KEY) {
SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert);
CK_ATTRIBUTE theTemplate;
if (pubKey == NULL) {
return PR_FALSE;
}
PK11_SETATTRS(&theTemplate, 0, NULL, 0);
switch (pubKey->keyType) {
case rsaKey:
case rsaPssKey:
case rsaOaepKey:
PK11_SETATTRS(&theTemplate, CKA_MODULUS, pubKey->u.rsa.modulus.data,
pubKey->u.rsa.modulus.len);
break;
case dsaKey:
PK11_SETATTRS(&theTemplate, CKA_VALUE, pubKey->u.dsa.publicValue.data,
pubKey->u.dsa.publicValue.len);
break;
case dhKey:
PK11_SETATTRS(&theTemplate, CKA_VALUE, pubKey->u.dh.publicValue.data,
pubKey->u.dh.publicValue.len);
break;
case ecKey:
PK11_SETATTRS(&theTemplate, CKA_EC_POINT,
pubKey->u.ec.publicValue.data,
pubKey->u.ec.publicValue.len);
break;
case keaKey:
case fortezzaKey:
case nullKey:
/* fall through and return false */
break;
}
if (theTemplate.ulValueLen == 0) {
SECKEY_DestroyPublicKey(pubKey);
return PR_FALSE;
}
if (pubKey->keyType != ecKey) {
pk11_SignedToUnsigned(&theTemplate);
}
if (pk11_FindObjectByTemplate(slot, &theTemplate, 1) != CK_INVALID_HANDLE) {
SECKEY_DestroyPublicKey(pubKey);
return PR_TRUE;
}
SECKEY_DestroyPublicKey(pubKey);
}
return PR_FALSE;
}
/*
* Check out if a cert has ID of zero. This is a magic ID that tells
* NSS that this cert may be an automagically trusted cert.
* The Cert has to be self signed as well. That check is done elsewhere.
*
*/
PRBool
pk11_isID0(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID)
{
CK_ATTRIBUTE keyID = { CKA_ID, NULL, 0 };
PRBool isZero = PR_FALSE;
int i;
CK_RV crv;
crv = PK11_GetAttributes(NULL, slot, certID, &keyID, 1);
if (crv != CKR_OK) {
return isZero;
}
if (keyID.ulValueLen != 0) {
char *value = (char *)keyID.pValue;
isZero = PR_TRUE; /* ID exists, may be zero */
for (i = 0; i < (int)keyID.ulValueLen; i++) {
if (value[i] != 0) {
isZero = PR_FALSE; /* nope */
break;
}
}
}
PORT_Free(keyID.pValue);
return isZero;
}
/*
* Create an NSSCertificate from a slot/certID pair, return it as a
* CERTCertificate. Optionally, output the nickname string.
*/
static CERTCertificate *
pk11_fastCert(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID,
CK_ATTRIBUTE *privateLabel, char **nickptr)
{
NSSCertificate *c;
nssCryptokiObject *co = NULL;
nssPKIObject *pkio;
NSSToken *token;
NSSTrustDomain *td = STAN_GetDefaultTrustDomain();
/* Get the cryptoki object from the handle */
token = PK11Slot_GetNSSToken(slot);
if (token && token->defaultSession) {
co = nssCryptokiObject_Create(token, token->defaultSession, certID);
} else {
PORT_SetError(SEC_ERROR_NO_TOKEN);
}
if (!co) {
return NULL;
}
/* Create a PKI object from the cryptoki instance */
pkio = nssPKIObject_Create(NULL, co, td, NULL, nssPKIMonitor);
if (!pkio) {
nssCryptokiObject_Destroy(co);
return NULL;
}
/* Create a certificate */
c = nssCertificate_Create(pkio);
if (!c) {
nssPKIObject_Destroy(pkio);
return NULL;
}
/* Build and output a nickname, if desired.
* This must be done before calling nssTrustDomain_AddCertsToCache
* because that function may destroy c, pkio and co!
*/
if ((nickptr) && (co->label)) {
CK_ATTRIBUTE label, id;
label.type = CKA_LABEL;
label.pValue = co->label;
label.ulValueLen = PORT_Strlen(co->label);
id.type = CKA_ID;
id.pValue = c->id.data;
id.ulValueLen = c->id.size;
*nickptr = pk11_buildNickname(slot, &label, privateLabel, &id);
}
/* This function may destroy the cert in "c" and all its subordinate
* structures, and replace the value in "c" with the address of a
* different NSSCertificate that it found in the cache.
* Presumably, the nickname which we just output above remains valid. :)
*/
(void)nssTrustDomain_AddCertsToCache(td, &c, 1);
return STAN_GetCERTCertificateOrRelease(c);
}
/*
* Build an CERTCertificate structure from a PKCS#11 object ID.... certID
* Must be a CertObject. This code does not explicitly checks that.
*/
CERTCertificate *
PK11_MakeCertFromHandle(PK11SlotInfo *slot, CK_OBJECT_HANDLE certID,
CK_ATTRIBUTE *privateLabel)
{
char *nickname = NULL;
CERTCertificate *cert = NULL;
CERTCertTrust *trust;
if (slot == NULL || certID == CK_INVALID_HANDLE) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
cert = pk11_fastCert(slot, certID, privateLabel, &nickname);
if (cert == NULL) {
goto loser;
}
if (nickname) {
if (cert->nickname != NULL) {
cert->dbnickname = cert->nickname;
}
cert->nickname = PORT_ArenaStrdup(cert->arena, nickname);
PORT_Free(nickname);
nickname = NULL;
}
/* remember where this cert came from.... If we have just looked
* it up from the database and it already has a slot, don't add a new
* one. */
if (cert->slot == NULL) {
cert->slot = PK11_ReferenceSlot(slot);
cert->pkcs11ID = certID;
cert->ownSlot = PR_TRUE;
cert->series = slot->series;
}
trust = (CERTCertTrust *)PORT_ArenaAlloc(cert->arena, sizeof(CERTCertTrust));
if (trust == NULL)
goto loser;
PORT_Memset(trust, 0, sizeof(CERTCertTrust));
if (!pk11_HandleTrustObject(slot, cert, trust)) {
unsigned int type;
/* build some cert trust flags */
if (CERT_IsCACert(cert, &type)) {
unsigned int trustflags = CERTDB_VALID_CA;
/* Allow PKCS #11 modules to give us trusted CA's. We only accept
* valid CA's which are self-signed here. They must have an object
* ID of '0'. */
if (pk11_isID0(slot, certID) &&
cert->isRoot) {
trustflags |= CERTDB_TRUSTED_CA;
/* is the slot a fortezza card? allow the user or
* admin to turn on objectSigning, but don't turn
* full trust on explicitly */
if (PK11_DoesMechanism(slot, CKM_KEA_KEY_DERIVE)) {
trust->objectSigningFlags |= CERTDB_VALID_CA;
}
}
if ((type & NS_CERT_TYPE_SSL_CA) == NS_CERT_TYPE_SSL_CA) {
trust->sslFlags |= trustflags;
}
if ((type & NS_CERT_TYPE_EMAIL_CA) == NS_CERT_TYPE_EMAIL_CA) {
trust->emailFlags |= trustflags;
}
if ((type & NS_CERT_TYPE_OBJECT_SIGNING_CA) == NS_CERT_TYPE_OBJECT_SIGNING_CA) {
trust->objectSigningFlags |= trustflags;
}
}
}
if (PK11_IsUserCert(slot, cert, certID)) {
trust->sslFlags |= CERTDB_USER;
trust->emailFlags |= CERTDB_USER;
/* trust->objectSigningFlags |= CERTDB_USER; */
}
CERT_LockCertTrust(cert);
cert->trust = trust;
CERT_UnlockCertTrust(cert);
return cert;
loser:
if (nickname)
PORT_Free(nickname);
if (cert)
CERT_DestroyCertificate(cert);
return NULL;
}
/*
* Build get a certificate from a private key
*/
CERTCertificate *
PK11_GetCertFromPrivateKey(SECKEYPrivateKey *privKey)
{
PK11SlotInfo *slot = privKey->pkcs11Slot;
CK_OBJECT_HANDLE handle = privKey->pkcs11ID;
CK_OBJECT_HANDLE certID =
PK11_MatchItem(slot, handle, CKO_CERTIFICATE);
CERTCertificate *cert;
if (certID == CK_INVALID_HANDLE) {
PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
return NULL;
}
cert = PK11_MakeCertFromHandle(slot, certID, NULL);
return (cert);
}
CK_OBJECT_HANDLE *
PK11_FindCertHandlesForKeyHandle(PK11SlotInfo *slot, CK_OBJECT_HANDLE keyHandle,
int *certHandleCountOut)
{
if (!slot || !certHandleCountOut || keyHandle == CK_INVALID_HANDLE) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
PORTCheapArenaPool arena;
PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
CK_ATTRIBUTE idTemplate[] = {
{ CKA_ID, NULL, 0 },
};
const int idAttrCount = sizeof(idTemplate) / sizeof(idTemplate[0]);
CK_RV crv = PK11_GetAttributes(&arena.arena, slot, keyHandle, idTemplate, idAttrCount);
if (crv != CKR_OK) {
PORT_DestroyCheapArena(&arena);
PORT_SetError(PK11_MapError(crv));
return NULL;
}
if ((idTemplate[0].ulValueLen == 0) || (idTemplate[0].ulValueLen == -1)) {
PORT_DestroyCheapArena(&arena);
PORT_SetError(SEC_ERROR_BAD_KEY);
return NULL;
}
CK_OBJECT_CLASS searchClass = CKO_CERTIFICATE;
CK_ATTRIBUTE searchTemplate[] = {
idTemplate[0],
{ CKA_CLASS, &searchClass, sizeof(searchClass) }
};
const size_t searchAttrCount = sizeof(searchTemplate) / sizeof(searchTemplate[0]);
CK_OBJECT_HANDLE *ids = pk11_FindObjectsByTemplate(slot, searchTemplate, searchAttrCount, certHandleCountOut);
PORT_DestroyCheapArena(&arena);
return ids;
}
CERTCertList *
PK11_GetCertsMatchingPrivateKey(SECKEYPrivateKey *privKey)
{
if (!privKey) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
CERTCertList *certs = CERT_NewCertList();
if (!certs) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return NULL;
}
PK11SlotInfo *slot = privKey->pkcs11Slot;
CK_OBJECT_HANDLE handle = privKey->pkcs11ID;
CK_OBJECT_HANDLE certID = PK11_MatchItem(slot, handle, CKO_CERTIFICATE);
/* If we can't get a matching certID, there are no matching certificates,
* which is not an error. */
if (certID == CK_INVALID_HANDLE) {
return certs;
}
int certHandleCount = 0;
CK_OBJECT_HANDLE *certHandles = PK11_FindCertHandlesForKeyHandle(slot, handle, &certHandleCount);
if (!certHandles) {
/* If certHandleCount is 0, there are no matching certificates, which is
* not an error. */
if (certHandleCount == 0) {
return certs;
}
CERT_DestroyCertList(certs);
return NULL;
}
int i;
for (i = 0; i < certHandleCount; i++) {
CERTCertificate *cert = PK11_MakeCertFromHandle(slot, certHandles[i], NULL);
/* If PK11_MakeCertFromHandle fails for one handle, optimistically
assume other handles may succeed (i.e. this is best-effort). */
if (!cert) {
continue;
}
if (CERT_AddCertToListTail(certs, cert) != SECSuccess) {
CERT_DestroyCertificate(cert);
}
}
PORT_Free(certHandles);
return certs;
}
/*
* delete a cert and it's private key (if no other certs are pointing to the
* private key.
*/
SECStatus
PK11_DeleteTokenCertAndKey(CERTCertificate *cert, void *wincx)
{
SECKEYPrivateKey *privKey = PK11_FindKeyByAnyCert(cert, wincx);
CK_OBJECT_HANDLE pubKey;
PK11SlotInfo *slot = NULL;
pubKey = pk11_FindPubKeyByAnyCert(cert, &slot, wincx);
if (privKey) {
/* For 3.4, utilize the generic cert delete function */
SEC_DeletePermCertificate(cert);
PK11_DeleteTokenPrivateKey(privKey, PR_FALSE);
}
if ((pubKey != CK_INVALID_HANDLE) && (slot != NULL)) {
PK11_DestroyTokenObject(slot, pubKey);
PK11_FreeSlot(slot);
}
return SECSuccess;
}
/*
* cert callback structure
*/
typedef struct pk11DoCertCallbackStr {
SECStatus (*callback)(PK11SlotInfo *slot, CERTCertificate *, void *);
SECStatus (*noslotcallback)(CERTCertificate *, void *);
SECStatus (*itemcallback)(CERTCertificate *, SECItem *, void *);
void *callbackArg;
} pk11DoCertCallback;
typedef struct pk11CertCallbackStr {
SECStatus (*callback)(CERTCertificate *, SECItem *, void *);
void *callbackArg;
} pk11CertCallback;
struct fake_der_cb_argstr {
SECStatus (*callback)(CERTCertificate *, SECItem *, void *);
void *arg;
};
static SECStatus
fake_der_cb(CERTCertificate *c, void *a)
{
struct fake_der_cb_argstr *fda = (struct fake_der_cb_argstr *)a;
return (*fda->callback)(c, &c->derCert, fda->arg);
}
/*
* Extract all the certs on a card from a slot.
*/
SECStatus
PK11_TraverseSlotCerts(SECStatus (*callback)(CERTCertificate *, SECItem *, void *),
void *arg, void *wincx)
{
NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
struct fake_der_cb_argstr fda;
struct nss3_cert_cbstr pk11cb;
/* authenticate to the tokens first */
(void)pk11_TraverseAllSlots(NULL, NULL, PR_TRUE, wincx);
fda.callback = callback;
fda.arg = arg;
pk11cb.callback = fake_der_cb;
pk11cb.arg = &fda;
NSSTrustDomain_TraverseCertificates(defaultTD, convert_cert, &pk11cb);
return SECSuccess;
}
static void
transfer_token_certs_to_collection(nssList *certList, NSSToken *token,
nssPKIObjectCollection *collection)
{
NSSCertificate **certs;
PRUint32 i, count;
NSSToken **tokens, **tp;
count = nssList_Count(certList);
if (count == 0) {
return;
}
certs = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
if (!certs) {
return;
}
nssList_GetArray(certList, (void **)certs, count);
for (i = 0; i < count; i++) {
tokens = nssPKIObject_GetTokens(&certs[i]->object, NULL);
if (tokens) {
for (tp = tokens; *tp; tp++) {
if (*tp == token) {
nssPKIObjectCollection_AddObject(collection,
(nssPKIObject *)certs[i]);
}
}
nssTokenArray_Destroy(tokens);
}
CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(certs[i]));
}
nss_ZFreeIf(certs);
}
static void
transfer_uri_certs_to_collection(nssList *certList, PK11URI *uri,
nssPKIObjectCollection *collection)
{
NSSCertificate **certs;
PRUint32 i, count;
NSSToken **tokens, **tp;
PK11SlotInfo *slot;
const char *id;
id = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_ID);
count = nssList_Count(certList);
if (count == 0) {
return;
}
certs = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
if (!certs) {
return;
}
nssList_GetArray(certList, (void **)certs, count);
for (i = 0; i < count; i++) {
/*
* Filter the subject matched certs based on the
* CKA_ID from the URI
*/
if (id && (strlen(id) != certs[i]->id.size ||
memcmp(id, certs[i]->id.data, certs[i]->id.size)))
continue;
tokens = nssPKIObject_GetTokens(&certs[i]->object, NULL);
if (tokens) {
for (tp = tokens; *tp; tp++) {
const char *value;
slot = (*tp)->pk11slot;
value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_TOKEN);
if (value &&
!pk11_MatchString(value,
(char *)slot->tokenInfo.label,
sizeof(slot->tokenInfo.label))) {
continue;
}
value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_MANUFACTURER);
if (value &&
!pk11_MatchString(value,
(char *)slot->tokenInfo.manufacturerID,
sizeof(slot->tokenInfo.manufacturerID))) {
continue;
}
value = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_MODEL);
if (value &&
!pk11_MatchString(value,
(char *)slot->tokenInfo.model,
sizeof(slot->tokenInfo.model))) {
continue;
}
nssPKIObjectCollection_AddObject(collection,
(nssPKIObject *)certs[i]);
break;
}
nssTokenArray_Destroy(tokens);
}
CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(certs[i]));
}
nss_ZFreeIf(certs);
}
static NSSCertificate **
find_certs_from_uri(const char *uriString, void *wincx)
{
PK11URI *uri = NULL;
CK_ATTRIBUTE attributes[10];
CK_ULONG nattributes = 0;
const char *label;
PK11SlotInfo *slotinfo;
nssCryptokiObject **instances;
PRStatus status;
nssPKIObjectCollection *collection = NULL;
NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
NSSCertificate **certs = NULL;
nssList *certList = NULL;
SECStatus rv;
CK_OBJECT_CLASS s_class = CKO_CERTIFICATE;
static const CK_BBOOL s_true = CK_TRUE;
NSSToken **tokens, **tok;
uri = PK11URI_ParseURI(uriString);
if (uri == NULL) {
goto loser;
}
collection = nssCertificateCollection_Create(defaultTD, NULL);
if (!collection) {
goto loser;
}
certList = nssList_Create(NULL, PR_FALSE);
if (!certList) {
goto loser;
}
label = PK11URI_GetPathAttribute(uri, PK11URI_PATTR_OBJECT);
if (label) {
(void)nssTrustDomain_GetCertsForNicknameFromCache(defaultTD,
(const char *)label,
certList);
} else {
(void)nssTrustDomain_GetCertsFromCache(defaultTD, certList);
}
transfer_uri_certs_to_collection(certList, uri, collection);
/* add the CKA_CLASS and CKA_TOKEN attributes manually */
attributes[nattributes].type = CKA_CLASS;
attributes[nattributes].pValue = (void *)&s_class;
attributes[nattributes].ulValueLen = sizeof(s_class);
nattributes++;
attributes[nattributes].type = CKA_TOKEN;
attributes[nattributes].pValue = (void *)&s_true;
attributes[nattributes].ulValueLen = sizeof(s_true);
nattributes++;
if (label) {
attributes[nattributes].type = CKA_LABEL;
attributes[nattributes].pValue = (void *)label;
attributes[nattributes].ulValueLen = strlen(label);
nattributes++;
}
tokens = NSSTrustDomain_FindTokensByURI(defaultTD, uri);
for (tok = tokens; tok && *tok; tok++) {
if (nssToken_IsPresent(*tok)) {
slotinfo = (*tok)->pk11slot;
rv = pk11_AuthenticateUnfriendly(slotinfo, PR_TRUE, wincx);
if (rv != SECSuccess) {
continue;
}
instances = nssToken_FindObjectsByTemplate(*tok, NULL,
attributes,
nattributes,
0, &status);
nssPKIObjectCollection_AddInstances(collection, instances, 0);
nss_ZFreeIf(instances);
}
nssToken_Destroy(*tok);
}
nss_ZFreeIf(tokens);
nssList_Destroy(certList);
certs = nssPKIObjectCollection_GetCertificates(collection, NULL, 0, NULL);
loser:
if (collection) {
nssPKIObjectCollection_Destroy(collection);
}
if (uri) {
PK11URI_DestroyURI(uri);
}
return certs;
}
CERTCertificate *
PK11_FindCertFromURI(const char *uri, void *wincx)
{
static const NSSUsage usage = { PR_TRUE /* ... */ };
NSSCertificate *cert = NULL;
NSSCertificate **certs = NULL;
CERTCertificate *rvCert = NULL;
certs = find_certs_from_uri(uri, wincx);
if (certs) {
cert = nssCertificateArray_FindBestCertificate(certs, NULL,
&usage, NULL);
if (cert) {
rvCert = STAN_GetCERTCertificateOrRelease(cert);
}
nssCertificateArray_Destroy(certs);
}
return rvCert;
}
CERTCertList *
PK11_FindCertsFromURI(const char *uri, void *wincx)
{
int i;
CERTCertList *certList = NULL;
NSSCertificate **foundCerts;
NSSCertificate *c;
foundCerts = find_certs_from_uri(uri, wincx);
if (foundCerts) {
PRTime now = PR_Now();
certList = CERT_NewCertList();
for (i = 0, c = *foundCerts; c; c = foundCerts[++i]) {
if (certList) {
CERTCertificate *certCert = STAN_GetCERTCertificateOrRelease(c);
/* c may be invalid after this, don't reference it */
if (certCert) {
/* CERT_AddCertToListSorted adopts certCert */
CERT_AddCertToListSorted(certList, certCert,
CERT_SortCBValidity, &now);
}
} else {
nssCertificate_Destroy(c);
}
}
if (certList && CERT_LIST_HEAD(certList) == NULL) {
CERT_DestroyCertList(certList);
certList = NULL;
}
/* all the certs have been adopted or freed, free the raw array */
nss_ZFreeIf(foundCerts);
}
return certList;
}
static NSSCertificate **
find_certs_from_nickname(const char *nickname, void *wincx)
{
PRStatus status;
NSSCertificate **certs = NULL;
NSSToken *token = NULL;
NSSTrustDomain *defaultTD = STAN_GetDefaultTrustDomain();
PK11SlotInfo *slot = NULL;
SECStatus rv;
char *nickCopy;
char *delimit = NULL;
char *tokenName;
if (!PORT_Strncasecmp(nickname, "pkcs11:", strlen("pkcs11:"))) {
certs = find_certs_from_uri(nickname, wincx);
if (certs)
return certs;
}
nickCopy = PORT_Strdup(nickname);
if (!nickCopy) {
/* error code is set */
return NULL;
}
if ((delimit = PORT_Strchr(nickCopy, ':')) != NULL) {
tokenName = nickCopy;
nickname = delimit + 1;
*delimit = '\0';
/* find token by name */
token = NSSTrustDomain_FindTokenByName(defaultTD, (NSSUTF8 *)tokenName);
if (token) {
slot = PK11_ReferenceSlot(token->pk11slot);
} else {
PORT_SetError(SEC_ERROR_NO_TOKEN);
}
*delimit = ':';
} else {
slot = PK11_GetInternalKeySlot();
token = PK11Slot_GetNSSToken(slot);
if (token) {
nssToken_AddRef(token);
} else {
PORT_SetError(SEC_ERROR_NO_TOKEN);
}
}
if (token) {
nssList *certList;
nssCryptokiObject **instances;
nssPKIObjectCollection *collection;
nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
if (!PK11_IsPresent(slot)) {
goto loser;
}
rv = pk11_AuthenticateUnfriendly(slot, PR_TRUE, wincx);
if (rv != SECSuccess) {
goto loser;
}
collection = nssCertificateCollection_Create(defaultTD, NULL);
if (!collection) {
goto loser;
}
certList = nssList_Create(NULL, PR_FALSE);
if (!certList) {
nssPKIObjectCollection_Destroy(collection);
goto loser;
}
(void)nssTrustDomain_GetCertsForNicknameFromCache(defaultTD,
nickname,
certList);
transfer_token_certs_to_collection(certList, token, collection);
instances = nssToken_FindCertificatesByNickname(token,
NULL,
nickname,
tokenOnly,
0,
&status);
nssPKIObjectCollection_AddInstances(collection, instances, 0);
nss_ZFreeIf(instances);
/* if it wasn't found, repeat the process for email address */
if (nssPKIObjectCollection_Count(collection) == 0 &&
PORT_Strchr(nickname, '@') != NULL) {
char *lowercaseName = CERT_FixupEmailAddr(nickname);
if (lowercaseName) {
(void)nssTrustDomain_GetCertsForEmailAddressFromCache(defaultTD,
lowercaseName,
certList);
transfer_token_certs_to_collection(certList, token, collection);
instances = nssToken_FindCertificatesByEmail(token,
NULL,
lowercaseName,
tokenOnly,
0,
&status);
nssPKIObjectCollection_AddInstances(collection, instances, 0);
nss_ZFreeIf(instances);
PORT_Free(lowercaseName);
}
}
certs = nssPKIObjectCollection_GetCertificates(collection,
NULL, 0, NULL);
nssPKIObjectCollection_Destroy(collection);
nssList_Destroy(certList);
}
loser:
if (token) {
nssToken_Destroy(token);
}
if (slot) {
PK11_FreeSlot(slot);
}
if (nickCopy)
PORT_Free(nickCopy);
return certs;
}
CERTCertificate *
PK11_FindCertFromNickname(const char *nickname, void *wincx)
{
CERTCertificate *rvCert = NULL;
NSSCertificate *cert = NULL;
NSSCertificate **certs = NULL;
static const NSSUsage usage = { PR_TRUE /* ... */ };
certs = find_certs_from_nickname(nickname, wincx);
if (certs) {
cert = nssCertificateArray_FindBestCertificate(certs, NULL,
&usage, NULL);
if (cert) {
rvCert = STAN_GetCERTCertificateOrRelease(cert);
}
nssCertificateArray_Destroy(certs);
}
return rvCert;
}
/* Traverse slots callback */
typedef struct FindCertsEmailArgStr {
char *email;
CERTCertList *certList;
} FindCertsEmailArg;
SECStatus
FindCertsEmailCallback(CERTCertificate *cert, SECItem *item, void *arg)
{
FindCertsEmailArg *cbparam = (FindCertsEmailArg *)arg;
const char *cert_email = CERT_GetFirstEmailAddress(cert);
PRBool found = PR_FALSE;
/* Email address present in certificate? */
if (cert_email == NULL) {
return SECSuccess;
}
/* Parameter correctly set? */
if (cbparam->email == NULL) {
return SECFailure;
}
/* Loop over all email addresses */
do {
if (!strcmp(cert_email, cbparam->email)) {
/* found one matching email address */
PRTime now = PR_Now();
found = PR_TRUE;
CERT_AddCertToListSorted(cbparam->certList,
CERT_DupCertificate(cert),
CERT_SortCBValidity, &now);
}
cert_email = CERT_GetNextEmailAddress(cert, cert_email);
} while (cert_email && !found);
return SECSuccess;
}