/
certutil.c
3549 lines (3265 loc) · 115 KB
/
certutil.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/. */
/*
** certutil.c
**
** utility for managing certificates and the cert database
**
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if defined(WIN32)
#include "fcntl.h"
#include "io.h"
#endif
#include "secutil.h"
#if defined(XP_UNIX)
#include <unistd.h>
#endif
#include "nspr.h"
#include "prtypes.h"
#include "prtime.h"
#include "prlong.h"
#include "pk11func.h"
#include "secasn1.h"
#include "cert.h"
#include "cryptohi.h"
#include "secoid.h"
#include "certdb.h"
#include "nss.h"
#include "certutil.h"
#define MIN_KEY_BITS 512
/* MAX_KEY_BITS should agree with MAX_RSA_MODULUS in freebl */
#define MAX_KEY_BITS 8192
#define DEFAULT_KEY_BITS 1024
#define GEN_BREAK(e) rv=e; break;
char *progName;
static CERTCertificateRequest *
GetCertRequest(const SECItem *reqDER)
{
CERTCertificateRequest *certReq = NULL;
CERTSignedData signedData;
PLArenaPool *arena = NULL;
SECStatus rv;
do {
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
GEN_BREAK (SECFailure);
}
certReq = (CERTCertificateRequest*) PORT_ArenaZAlloc
(arena, sizeof(CERTCertificateRequest));
if (!certReq) {
GEN_BREAK(SECFailure);
}
certReq->arena = arena;
/* Since cert request is a signed data, must decode to get the inner
data
*/
PORT_Memset(&signedData, 0, sizeof(signedData));
rv = SEC_ASN1DecodeItem(arena, &signedData,
SEC_ASN1_GET(CERT_SignedDataTemplate), reqDER);
if (rv) {
break;
}
rv = SEC_ASN1DecodeItem(arena, certReq,
SEC_ASN1_GET(CERT_CertificateRequestTemplate), &signedData.data);
if (rv) {
break;
}
rv = CERT_VerifySignedDataWithPublicKeyInfo(&signedData,
&certReq->subjectPublicKeyInfo, NULL /* wincx */);
} while (0);
if (rv) {
SECU_PrintError(progName, "bad certificate request\n");
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
certReq = NULL;
}
return certReq;
}
static SECStatus
AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts,
const SECItem *certDER, PRBool emailcert, void *pwdata)
{
CERTCertTrust *trust = NULL;
CERTCertificate *cert = NULL;
SECStatus rv;
do {
/* Read in an ASCII cert and return a CERTCertificate */
cert = CERT_DecodeCertFromPackage((char *)certDER->data, certDER->len);
if (!cert) {
SECU_PrintError(progName, "could not decode certificate");
GEN_BREAK(SECFailure);
}
/* Create a cert trust */
trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust));
if (!trust) {
SECU_PrintError(progName, "unable to allocate cert trust");
GEN_BREAK(SECFailure);
}
rv = CERT_DecodeTrustString(trust, trusts);
if (rv) {
SECU_PrintError(progName, "unable to decode trust string");
GEN_BREAK(SECFailure);
}
rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE);
if (rv != SECSuccess) {
/* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have
* been coded to take a password arg. */
if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not authenticate to token %s.",
PK11_GetTokenName(slot));
GEN_BREAK(SECFailure);
}
rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE,
name, PR_FALSE);
}
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not add certificate to token or database");
GEN_BREAK(SECFailure);
}
}
rv = CERT_ChangeCertTrust(handle, cert, trust);
if (rv != SECSuccess) {
if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not authenticate to token %s.",
PK11_GetTokenName(slot));
GEN_BREAK(SECFailure);
}
rv = CERT_ChangeCertTrust(handle, cert, trust);
}
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not change trust on certificate");
GEN_BREAK(SECFailure);
}
}
if ( emailcert ) {
CERT_SaveSMimeProfile(cert, NULL, pwdata);
}
} while (0);
CERT_DestroyCertificate (cert);
PORT_Free(trust);
return rv;
}
static SECStatus
CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType,
SECOidTag hashAlgTag, CERTName *subject, char *phone, int ascii,
const char *emailAddrs, const char *dnsNames,
certutilExtnList extnList, const char *extGeneric,
/*out*/ SECItem *result)
{
CERTSubjectPublicKeyInfo *spki;
CERTCertificateRequest *cr;
SECItem *encoding;
SECOidTag signAlgTag;
SECStatus rv;
PLArenaPool *arena;
void *extHandle;
SECItem signedReq = { siBuffer, NULL, 0 };
/* Create info about public key */
spki = SECKEY_CreateSubjectPublicKeyInfo(pubk);
if (!spki) {
SECU_PrintError(progName, "unable to create subject public key");
return SECFailure;
}
/* Generate certificate request */
cr = CERT_CreateCertificateRequest(subject, spki, NULL);
SECKEY_DestroySubjectPublicKeyInfo(spki);
if (!cr) {
SECU_PrintError(progName, "unable to make certificate request");
return SECFailure;
}
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if ( !arena ) {
SECU_PrintError(progName, "out of memory");
return SECFailure;
}
extHandle = CERT_StartCertificateRequestAttributes(cr);
if (extHandle == NULL) {
PORT_FreeArena (arena, PR_FALSE);
return SECFailure;
}
if (AddExtensions(extHandle, emailAddrs, dnsNames, extnList, extGeneric)
!= SECSuccess) {
PORT_FreeArena (arena, PR_FALSE);
return SECFailure;
}
CERT_FinishExtensions(extHandle);
CERT_FinishCertificateRequestAttributes(cr);
/* Der encode the request */
encoding = SEC_ASN1EncodeItem(arena, NULL, cr,
SEC_ASN1_GET(CERT_CertificateRequestTemplate));
CERT_DestroyCertificateRequest(cr);
if (encoding == NULL) {
PORT_FreeArena (arena, PR_FALSE);
SECU_PrintError(progName, "der encoding of request failed");
return SECFailure;
}
/* Sign the request */
signAlgTag = SEC_GetSignatureAlgorithmOidTag(keyType, hashAlgTag);
if (signAlgTag == SEC_OID_UNKNOWN) {
PORT_FreeArena (arena, PR_FALSE);
SECU_PrintError(progName, "unknown Key or Hash type");
return SECFailure;
}
rv = SEC_DerSignData(arena, &signedReq, encoding->data, encoding->len,
privk, signAlgTag);
if (rv) {
PORT_FreeArena (arena, PR_FALSE);
SECU_PrintError(progName, "signing of data failed");
return SECFailure;
}
/* Encode request in specified format */
if (ascii) {
char *obuf;
char *header, *name, *email, *org, *state, *country;
obuf = BTOA_ConvertItemToAscii(&signedReq);
if (!obuf) {
goto oom;
}
name = CERT_GetCommonName(subject);
if (!name) {
name = PORT_Strdup("(not specified)");
}
if (!phone)
phone = strdup("(not specified)");
email = CERT_GetCertEmailAddress(subject);
if (!email)
email = PORT_Strdup("(not specified)");
org = CERT_GetOrgName(subject);
if (!org)
org = PORT_Strdup("(not specified)");
state = CERT_GetStateName(subject);
if (!state)
state = PORT_Strdup("(not specified)");
country = CERT_GetCountryName(subject);
if (!country)
country = PORT_Strdup("(not specified)");
header = PR_smprintf(
"\nCertificate request generated by Netscape certutil\n"
"Phone: %s\n\n"
"Common Name: %s\n"
"Email: %s\n"
"Organization: %s\n"
"State: %s\n"
"Country: %s\n\n"
"%s\n",
phone, name, email, org, state, country, NS_CERTREQ_HEADER);
PORT_Free(name);
PORT_Free(email);
PORT_Free(org);
PORT_Free(state);
PORT_Free(country);
if (header) {
char * trailer = PR_smprintf("\n%s\n", NS_CERTREQ_TRAILER);
if (trailer) {
PRUint32 headerLen = PL_strlen(header);
PRUint32 obufLen = PL_strlen(obuf);
PRUint32 trailerLen = PL_strlen(trailer);
SECITEM_AllocItem(NULL, result,
headerLen + obufLen + trailerLen);
if (result->data) {
PORT_Memcpy(result->data, header, headerLen);
PORT_Memcpy(result->data + headerLen, obuf, obufLen);
PORT_Memcpy(result->data + headerLen + obufLen,
trailer, trailerLen);
}
PR_smprintf_free(trailer);
}
PR_smprintf_free(header);
}
} else {
(void) SECITEM_CopyItem(NULL, result, &signedReq);
}
if (!result->data) {
oom: SECU_PrintError(progName, "out of memory");
PORT_SetError(SEC_ERROR_NO_MEMORY);
rv = SECFailure;
}
PORT_FreeArena (arena, PR_FALSE);
return rv;
}
static SECStatus
ChangeTrustAttributes(CERTCertDBHandle *handle, PK11SlotInfo *slot,
char *name, char *trusts, void *pwdata)
{
SECStatus rv;
CERTCertificate *cert;
CERTCertTrust *trust;
cert = CERT_FindCertByNicknameOrEmailAddr(handle, name);
if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"",
name);
return SECFailure;
}
trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust));
if (!trust) {
SECU_PrintError(progName, "unable to allocate cert trust");
return SECFailure;
}
/* This function only decodes these characters: pPwcTCu, */
rv = CERT_DecodeTrustString(trust, trusts);
if (rv) {
SECU_PrintError(progName, "unable to decode trust string");
return SECFailure;
}
/* CERT_ChangeCertTrust API does not have a way to pass in
* a context, so NSS can't prompt for the password if it needs to.
* check to see if the failure was token not logged in and
* log in if need be. */
rv = CERT_ChangeCertTrust(handle, cert, trust);
if (rv != SECSuccess) {
if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
return SECFailure;
}
rv = CERT_ChangeCertTrust(handle, cert, trust);
}
if (rv != SECSuccess) {
SECU_PrintError(progName, "unable to modify trust attributes");
return SECFailure;
}
}
CERT_DestroyCertificate(cert);
return SECSuccess;
}
static SECStatus
DumpChain(CERTCertDBHandle *handle, char *name, PRBool ascii)
{
CERTCertificate *the_cert;
CERTCertificateList *chain;
int i, j;
the_cert = SECU_FindCertByNicknameOrFilename(handle, name,
ascii, NULL);
if (!the_cert) {
SECU_PrintError(progName, "Could not find: %s\n", name);
return SECFailure;
}
chain = CERT_CertChainFromCert(the_cert, 0, PR_TRUE);
CERT_DestroyCertificate(the_cert);
if (!chain) {
SECU_PrintError(progName, "Could not obtain chain for: %s\n", name);
return SECFailure;
}
for (i=chain->len-1; i>=0; i--) {
CERTCertificate *c;
c = CERT_FindCertByDERCert(handle, &chain->certs[i]);
for (j=i; j<chain->len-1; j++) printf(" ");
printf("\"%s\" [%s]\n\n", c->nickname, c->subjectName);
CERT_DestroyCertificate(c);
}
CERT_DestroyCertificateList(chain);
return SECSuccess;
}
static SECStatus
outputCertOrExtension(CERTCertificate *the_cert, PRBool raw, PRBool ascii,
SECItem *extensionOID, PRFileDesc *outfile)
{
SECItem data;
PRInt32 numBytes;
SECStatus rv = SECFailure;
if (extensionOID) {
int i;
PRBool found = PR_FALSE;
for (i=0; the_cert->extensions[i] != NULL; i++) {
CERTCertExtension *extension = the_cert->extensions[i];
if (SECITEM_CompareItem(&extension->id, extensionOID) == SECEqual) {
found = PR_TRUE;
numBytes = PR_Write(outfile, extension->value.data,
extension->value.len);
rv = SECSuccess;
if (numBytes != (PRInt32) extension->value.len) {
SECU_PrintSystemError(progName, "error writing extension");
rv = SECFailure;
}
rv = SECSuccess;
break;
}
}
if (!found) {
SECU_PrintSystemError(progName, "extension not found");
rv = SECFailure;
}
} else {
data.data = the_cert->derCert.data;
data.len = the_cert->derCert.len;
if (ascii) {
PR_fprintf(outfile, "%s\n%s\n%s\n", NS_CERT_HEADER,
BTOA_DataToAscii(data.data, data.len), NS_CERT_TRAILER);
rv = SECSuccess;
} else if (raw) {
numBytes = PR_Write(outfile, data.data, data.len);
rv = SECSuccess;
if (numBytes != (PRInt32) data.len) {
SECU_PrintSystemError(progName, "error writing raw cert");
rv = SECFailure;
}
} else {
rv = SEC_PrintCertificateAndTrust(the_cert, "Certificate", NULL);
if (rv != SECSuccess) {
SECU_PrintError(progName, "problem printing certificate");
}
}
}
return rv;
}
static SECStatus
listCerts(CERTCertDBHandle *handle, char *name, char *email,
PK11SlotInfo *slot, PRBool raw, PRBool ascii,
SECItem *extensionOID,
PRFileDesc *outfile, void *pwarg)
{
SECStatus rv = SECFailure;
CERTCertList *certs;
CERTCertListNode *node;
/* List certs on a non-internal slot. */
if (!PK11_IsFriendly(slot) && PK11_NeedLogin(slot)) {
SECStatus newrv = PK11_Authenticate(slot, PR_TRUE, pwarg);
if (newrv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
return SECFailure;
}
}
if (name) {
CERTCertificate *the_cert =
SECU_FindCertByNicknameOrFilename(handle, name, ascii, NULL);
if (!the_cert) {
SECU_PrintError(progName, "Could not find cert: %s\n", name);
return SECFailure;
}
/* Here, we have one cert with the desired nickname or email
* address. Now, we will attempt to get a list of ALL certs
* with the same subject name as the cert we have. That list
* should contain, at a minimum, the one cert we have already found.
* If the list of certs is empty (NULL), the libraries have failed.
*/
certs = CERT_CreateSubjectCertList(NULL, handle, &the_cert->derSubject,
PR_Now(), PR_FALSE);
CERT_DestroyCertificate(the_cert);
if (!certs) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
SECU_PrintError(progName, "problem printing certificates");
return SECFailure;
}
for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs);
node = CERT_LIST_NEXT(node)) {
rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID,
outfile);
if (rv != SECSuccess) {
break;
}
}
} else if (email) {
certs = PK11_FindCertsFromEmailAddress(email, NULL);
if (!certs) {
SECU_PrintError(progName,
"Could not find certificates for email address: %s\n",
email);
return SECFailure;
}
for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs);
node = CERT_LIST_NEXT(node)) {
rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID,
outfile);
if (rv != SECSuccess) {
break;
}
}
} else {
certs = PK11_ListCertsInSlot(slot);
if (certs) {
for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs);
node = CERT_LIST_NEXT(node)) {
SECU_PrintCertNickname(node,stdout);
}
rv = SECSuccess;
}
}
if (certs) {
CERT_DestroyCertList(certs);
}
if (rv) {
SECU_PrintError(progName, "problem printing certificate nicknames");
return SECFailure;
}
return SECSuccess; /* not rv ?? */
}
static SECStatus
ListCerts(CERTCertDBHandle *handle, char *nickname, char *email,
PK11SlotInfo *slot, PRBool raw, PRBool ascii,
SECItem *extensionOID,
PRFileDesc *outfile, secuPWData *pwdata)
{
SECStatus rv;
if (!ascii && !raw && !nickname && !email) {
PR_fprintf(outfile, "\n%-60s %-5s\n%-60s %-5s\n\n",
"Certificate Nickname", "Trust Attributes", "",
"SSL,S/MIME,JAR/XPI");
}
if (slot == NULL) {
CERTCertList *list;
CERTCertListNode *node;
list = PK11_ListCerts(PK11CertListAll, pwdata);
for (node = CERT_LIST_HEAD(list); !CERT_LIST_END(node, list);
node = CERT_LIST_NEXT(node)) {
SECU_PrintCertNickname(node, stdout);
}
CERT_DestroyCertList(list);
return SECSuccess;
}
rv = listCerts(handle, nickname, email, slot, raw, ascii,
extensionOID, outfile, pwdata);
return rv;
}
static SECStatus
DeleteCert(CERTCertDBHandle *handle, char *name)
{
SECStatus rv;
CERTCertificate *cert;
cert = CERT_FindCertByNicknameOrEmailAddr(handle, name);
if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"",
name);
return SECFailure;
}
rv = SEC_DeletePermCertificate(cert);
CERT_DestroyCertificate(cert);
if (rv) {
SECU_PrintError(progName, "unable to delete certificate");
}
return rv;
}
static SECStatus
ValidateCert(CERTCertDBHandle *handle, char *name, char *date,
char *certUsage, PRBool checkSig, PRBool logit,
PRBool ascii, secuPWData *pwdata)
{
SECStatus rv;
CERTCertificate *cert = NULL;
PRTime timeBoundary;
SECCertificateUsage usage;
CERTVerifyLog reallog;
CERTVerifyLog *log = NULL;
if (!certUsage) {
PORT_SetError (SEC_ERROR_INVALID_ARGS);
return (SECFailure);
}
switch (*certUsage) {
case 'O':
usage = certificateUsageStatusResponder;
break;
case 'L':
usage = certificateUsageSSLCA;
break;
case 'A':
usage = certificateUsageAnyCA;
break;
case 'Y':
usage = certificateUsageVerifyCA;
break;
case 'C':
usage = certificateUsageSSLClient;
break;
case 'V':
usage = certificateUsageSSLServer;
break;
case 'S':
usage = certificateUsageEmailSigner;
break;
case 'R':
usage = certificateUsageEmailRecipient;
break;
case 'J':
usage = certificateUsageObjectSigner;
break;
default:
PORT_SetError (SEC_ERROR_INVALID_ARGS);
return (SECFailure);
}
do {
cert = SECU_FindCertByNicknameOrFilename(handle, name, ascii,
NULL);
if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"",
name);
GEN_BREAK (SECFailure)
}
if (date != NULL) {
rv = DER_AsciiToTime(&timeBoundary, date);
if (rv) {
SECU_PrintError(progName, "invalid input date");
GEN_BREAK (SECFailure)
}
} else {
timeBoundary = PR_Now();
}
if ( logit ) {
log = &reallog;
log->count = 0;
log->head = NULL;
log->tail = NULL;
log->arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if ( log->arena == NULL ) {
SECU_PrintError(progName, "out of memory");
GEN_BREAK (SECFailure)
}
}
rv = CERT_VerifyCertificate(handle, cert, checkSig, usage,
timeBoundary, pwdata, log, &usage);
if ( log ) {
if ( log->head == NULL ) {
fprintf(stdout, "%s: certificate is valid\n", progName);
GEN_BREAK (SECSuccess)
} else {
char *name;
CERTVerifyLogNode *node;
node = log->head;
while ( node ) {
if ( node->cert->nickname != NULL ) {
name = node->cert->nickname;
} else {
name = node->cert->subjectName;
}
fprintf(stderr, "%s : %s\n", name,
SECU_Strerror(node->error));
CERT_DestroyCertificate(node->cert);
node = node->next;
}
}
} else {
if (rv != SECSuccess) {
PRErrorCode perr = PORT_GetError();
fprintf(stdout, "%s: certificate is invalid: %s\n",
progName, SECU_Strerror(perr));
GEN_BREAK (SECFailure)
}
fprintf(stdout, "%s: certificate is valid\n", progName);
GEN_BREAK (SECSuccess)
}
} while (0);
if (cert) {
CERT_DestroyCertificate(cert);
}
return (rv);
}
static PRBool
ItemIsPrintableASCII(const SECItem * item)
{
unsigned char *src = item->data;
unsigned int len = item->len;
while (len-- > 0) {
unsigned char uc = *src++;
if (uc < 0x20 || uc > 0x7e)
return PR_FALSE;
}
return PR_TRUE;
}
/* Caller ensures that dst is at least item->len*2+1 bytes long */
static void
SECItemToHex(const SECItem * item, char * dst)
{
if (dst && item && item->data) {
unsigned char * src = item->data;
unsigned int len = item->len;
for (; len > 0; --len, dst += 2) {
sprintf(dst, "%02x", *src++);
}
*dst = '\0';
}
}
static const char * const keyTypeName[] = {
"null", "rsa", "dsa", "fortezza", "dh", "kea", "ec" };
#define MAX_CKA_ID_BIN_LEN 20
#define MAX_CKA_ID_STR_LEN 40
/* print key number, key ID (in hex or ASCII), key label (nickname) */
static SECStatus
PrintKey(PRFileDesc *out, const char *nickName, int count,
SECKEYPrivateKey *key, void *pwarg)
{
SECItem * ckaID;
char ckaIDbuf[MAX_CKA_ID_STR_LEN + 4];
pwarg = NULL;
ckaID = PK11_GetLowLevelKeyIDForPrivateKey(key);
if (!ckaID) {
strcpy(ckaIDbuf, "(no CKA_ID)");
} else if (ItemIsPrintableASCII(ckaID)) {
int len = PR_MIN(MAX_CKA_ID_STR_LEN, ckaID->len);
ckaIDbuf[0] = '"';
memcpy(ckaIDbuf + 1, ckaID->data, len);
ckaIDbuf[1 + len] = '"';
ckaIDbuf[2 + len] = '\0';
} else {
/* print ckaid in hex */
SECItem idItem = *ckaID;
if (idItem.len > MAX_CKA_ID_BIN_LEN)
idItem.len = MAX_CKA_ID_BIN_LEN;
SECItemToHex(&idItem, ckaIDbuf);
}
PR_fprintf(out, "<%2d> %-8.8s %-42.42s %s\n", count,
keyTypeName[key->keyType], ckaIDbuf, nickName);
SECITEM_ZfreeItem(ckaID, PR_TRUE);
return SECSuccess;
}
/* returns SECSuccess if ANY keys are found, SECFailure otherwise. */
static SECStatus
ListKeysInSlot(PK11SlotInfo *slot, const char *nickName, KeyType keyType,
void *pwarg)
{
SECKEYPrivateKeyList *list;
SECKEYPrivateKeyListNode *node;
int count = 0;
if (PK11_NeedLogin(slot)) {
SECStatus rv = PK11_Authenticate(slot, PR_TRUE, pwarg);
if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
return SECFailure;
}
}
if (nickName && nickName[0])
list = PK11_ListPrivKeysInSlot(slot, (char *)nickName, pwarg);
else
list = PK11_ListPrivateKeysInSlot(slot);
if (list == NULL) {
SECU_PrintError(progName, "problem listing keys");
return SECFailure;
}
for (node=PRIVKEY_LIST_HEAD(list);
!PRIVKEY_LIST_END(node,list);
node=PRIVKEY_LIST_NEXT(node)) {
char * keyName;
static const char orphan[] = { "(orphan)" };
if (keyType != nullKey && keyType != node->key->keyType)
continue;
keyName = PK11_GetPrivateKeyNickname(node->key);
if (!keyName || !keyName[0]) {
/* Try extra hard to find nicknames for keys that lack them. */
CERTCertificate * cert;
PORT_Free((void *)keyName);
keyName = NULL;
cert = PK11_GetCertFromPrivateKey(node->key);
if (cert) {
if (cert->nickname && cert->nickname[0]) {
keyName = PORT_Strdup(cert->nickname);
} else if (cert->emailAddr && cert->emailAddr[0]) {
keyName = PORT_Strdup(cert->emailAddr);
}
CERT_DestroyCertificate(cert);
}
}
if (nickName) {
if (!keyName || PL_strcmp(keyName,nickName)) {
/* PKCS#11 module returned unwanted keys */
PORT_Free((void *)keyName);
continue;
}
}
if (!keyName)
keyName = (char *)orphan;
PrintKey(PR_STDOUT, keyName, count, node->key, pwarg);
if (keyName != (char *)orphan)
PORT_Free((void *)keyName);
count++;
}
SECKEY_DestroyPrivateKeyList(list);
if (count == 0) {
PR_fprintf(PR_STDOUT, "%s: no keys found\n", progName);
return SECFailure;
}
return SECSuccess;
}
/* returns SECSuccess if ANY keys are found, SECFailure otherwise. */
static SECStatus
ListKeys(PK11SlotInfo *slot, const char *nickName, int index,
KeyType keyType, PRBool dopriv, secuPWData *pwdata)
{
SECStatus rv = SECFailure;
static const char fmt[] = \
"%s: Checking token \"%.33s\" in slot \"%.65s\"\n";
if (slot == NULL) {
PK11SlotList *list;
PK11SlotListElement *le;
list= PK11_GetAllTokens(CKM_INVALID_MECHANISM,PR_FALSE,PR_FALSE,pwdata);
if (list) {
for (le = list->head; le; le = le->next) {
PR_fprintf(PR_STDOUT, fmt, progName,
PK11_GetTokenName(le->slot),
PK11_GetSlotName(le->slot));
rv &= ListKeysInSlot(le->slot,nickName,keyType,pwdata);
}
PK11_FreeSlotList(list);
}
} else {
PR_fprintf(PR_STDOUT, fmt, progName, PK11_GetTokenName(slot),
PK11_GetSlotName(slot));
rv = ListKeysInSlot(slot,nickName,keyType,pwdata);
}
return rv;
}
static SECStatus
DeleteKey(char *nickname, secuPWData *pwdata)
{
SECStatus rv;
CERTCertificate *cert;
PK11SlotInfo *slot;
slot = PK11_GetInternalKeySlot();
if (PK11_NeedLogin(slot)) {
SECStatus rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
return SECFailure;
}
}
cert = PK11_FindCertFromNickname(nickname, pwdata);
if (!cert) {
PK11_FreeSlot(slot);
return SECFailure;
}
rv = PK11_DeleteTokenCertAndKey(cert, pwdata);
if (rv != SECSuccess) {
SECU_PrintError("problem deleting private key \"%s\"\n", nickname);
}
CERT_DestroyCertificate(cert);
PK11_FreeSlot(slot);
return rv;
}
/*
* L i s t M o d u l e s
*
* Print a list of the PKCS11 modules that are
* available. This is useful for smartcard people to
* make sure they have the drivers loaded.
*
*/
static SECStatus
ListModules(void)
{
PK11SlotList *list;
PK11SlotListElement *le;
/* get them all! */
list = PK11_GetAllTokens(CKM_INVALID_MECHANISM,PR_FALSE,PR_FALSE,NULL);
if (list == NULL) return SECFailure;
/* look at each slot*/
for (le = list->head ; le; le = le->next) {
printf ("\n");
printf (" slot: %s\n", PK11_GetSlotName(le->slot));
printf (" token: %s\n", PK11_GetTokenName(le->slot));
}
PK11_FreeSlotList(list);
return SECSuccess;
}
static void
PrintSyntax(char *progName)
{
#define FPS fprintf(stderr,
FPS "Type %s -H for more detailed descriptions\n", progName);
FPS "Usage: %s -N [-d certdir] [-P dbprefix] [-f pwfile] [--empty-password]\n", progName);
FPS "Usage: %s -T [-d certdir] [-P dbprefix] [-h token-name]\n"
"\t\t [-f pwfile] [-0 SSO-password]\n", progName);
FPS "\t%s -A -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n",
progName);
FPS "\t%s -B -i batch-file\n", progName);
FPS "\t%s -C [-c issuer-name | -x] -i cert-request-file -o cert-file\n"
"\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
"\t\t [-f pwfile] [-d certdir] [-P dbprefix]\n"
"\t\t [-1 | --keyUsage [keyUsageKeyword,..]] [-2] [-3] [-4]\n"
"\t\t [-5 | --nsCertType [nsCertTypeKeyword,...]]\n"
"\t\t [-6 | --extKeyUsage [extKeyUsageKeyword,...]] [-7 emailAddrs]\n"
"\t\t [-8 dns-names] [-a]\n",
progName);
FPS "\t%s -D -n cert-name [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n",
progName);
FPS "\t%s -F -n nickname [-d certdir] [-P dbprefix]\n",
progName);
FPS "\t%s -G -n key-name [-h token-name] [-k rsa] [-g key-size] [-y exp]\n"
"\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n"
"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
#ifndef NSS_DISABLE_ECC
FPS "\t%s -G [-h token-name] -k ec -q curve [-f pwfile]\n"
"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n",
progName);
#else
FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|rsa|all]\n",