/
cmsutil.c
1625 lines (1538 loc) · 56.7 KB
/
cmsutil.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/. */
/*
* cmsutil -- A command to work with CMS data
*/
#include "nspr.h"
#include "secutil.h"
#include "plgetopt.h"
#include "secpkcs7.h"
#include "cert.h"
#include "certdb.h"
#include "secoid.h"
#include "cms.h"
#include "nss.h"
#include "smime.h"
#include "pk11func.h"
#if defined(XP_UNIX)
#include <unistd.h>
#endif
#if defined(_WIN32)
#include "fcntl.h"
#include "io.h"
#endif
#include <stdio.h>
#include <string.h>
char *progName = NULL;
static int cms_verbose = 0;
static secuPWData pwdata = { PW_NONE, 0 };
static PK11PasswordFunc pwcb = NULL;
static void *pwcb_arg = NULL;
/* XXX stolen from cmsarray.c
* nss_CMSArray_Count - count number of elements in array
*/
int
nss_CMSArray_Count(void **array)
{
int n = 0;
if (array == NULL)
return 0;
while (*array++ != NULL)
n++;
return n;
}
static SECStatus
DigestFile(PLArenaPool *poolp, SECItem ***digests, SECItem *input,
SECAlgorithmID **algids)
{
NSSCMSDigestContext *digcx;
SECStatus rv;
digcx = NSS_CMSDigestContext_StartMultiple(algids);
if (digcx == NULL)
return SECFailure;
NSS_CMSDigestContext_Update(digcx, input->data, input->len);
rv = NSS_CMSDigestContext_FinishMultiple(digcx, poolp, digests);
return rv;
}
static void
Usage(void)
{
fprintf(stderr,
"Usage: %s [-C|-D|-E|-O|-S] [<options>] [-d dbdir] [-u certusage]\n"
" -C create a CMS encrypted data message\n"
" -D decode a CMS message\n"
" -b decode a batch of files named in infile\n"
" -c content use this detached content\n"
" -n suppress output of content\n"
" -h num display num levels of CMS message info as email headers\n"
" -k keep decoded encryption certs in perm cert db\n"
" -E create a CMS enveloped data message\n"
" -r id,... create envelope for these recipients,\n"
" where id can be a certificate nickname or email address\n"
" -S create a CMS signed data message\n"
" -G include a signing time attribute\n"
" -H hash use hash (default:SHA256)\n"
" -N nick use certificate named \"nick\" for signing\n"
" -P include a SMIMECapabilities attribute\n"
" -T do not include content in CMS message\n"
" -Y nick include a EncryptionKeyPreference attribute with cert\n"
" (use \"NONE\" to omit)\n"
" -O create a CMS signed message containing only certificates\n"
" General Options:\n"
" -d dbdir key/cert database directory (default: ~/.netscape)\n"
" -e envelope enveloped data message in this file is used for bulk key\n"
" -i infile use infile as source of data (default: stdin)\n"
" -o outfile use outfile as destination of data (default: stdout)\n"
" -p password use password as key db password (default: prompt)\n"
" -f pwfile use password file to set password on all PKCS#11 tokens)\n"
" -u certusage set type of certificate usage (default: certUsageEmailSigner)\n"
" -v print debugging information\n"
"\n"
"Cert usage codes:\n",
progName);
fprintf(stderr, "%-25s 0 - certUsageSSLClient\n", " ");
fprintf(stderr, "%-25s 1 - certUsageSSLServer\n", " ");
fprintf(stderr, "%-25s 2 - certUsageSSLServerWithStepUp\n", " ");
fprintf(stderr, "%-25s 3 - certUsageSSLCA\n", " ");
fprintf(stderr, "%-25s 4 - certUsageEmailSigner\n", " ");
fprintf(stderr, "%-25s 5 - certUsageEmailRecipient\n", " ");
fprintf(stderr, "%-25s 6 - certUsageObjectSigner\n", " ");
fprintf(stderr, "%-25s 7 - certUsageUserCertImport\n", " ");
fprintf(stderr, "%-25s 8 - certUsageVerifyCA\n", " ");
fprintf(stderr, "%-25s 9 - certUsageProtectedObjectSigner\n", " ");
fprintf(stderr, "%-25s 10 - certUsageStatusResponder\n", " ");
fprintf(stderr, "%-25s 11 - certUsageAnyCA\n", " ");
fprintf(stderr, "%-25s 12 - certUsageIPsec\n", " ");
exit(-1);
}
struct optionsStr {
char *pwfile;
char *password;
SECCertUsage certUsage;
CERTCertDBHandle *certHandle;
};
struct decodeOptionsStr {
struct optionsStr *options;
SECItem content;
int headerLevel;
PRBool suppressContent;
NSSCMSGetDecryptKeyCallback dkcb;
PK11SymKey *bulkkey;
PRBool keepCerts;
};
struct signOptionsStr {
struct optionsStr *options;
char *nickname;
char *encryptionKeyPreferenceNick;
PRBool signingTime;
PRBool smimeProfile;
PRBool detached;
SECOidTag hashAlgTag;
};
struct envelopeOptionsStr {
struct optionsStr *options;
char **recipients;
};
struct certsonlyOptionsStr {
struct optionsStr *options;
char **recipients;
};
struct encryptOptionsStr {
struct optionsStr *options;
char **recipients;
NSSCMSMessage *envmsg;
SECItem *input;
FILE *outfile;
PRFileDesc *envFile;
PK11SymKey *bulkkey;
SECOidTag bulkalgtag;
int keysize;
};
static NSSCMSMessage *
decode(FILE *out, SECItem *input, const struct decodeOptionsStr *decodeOptions)
{
NSSCMSDecoderContext *dcx;
SECStatus rv;
NSSCMSMessage *cmsg;
int nlevels, i;
SECItem sitem = { 0, 0, 0 };
PORT_SetError(0);
dcx = NSS_CMSDecoder_Start(NULL,
NULL, NULL, /* content callback */
pwcb, pwcb_arg, /* password callback */
decodeOptions->dkcb, /* decrypt key callback */
decodeOptions->bulkkey);
if (dcx == NULL) {
fprintf(stderr, "%s: failed to set up message decoder.\n", progName);
return NULL;
}
rv = NSS_CMSDecoder_Update(dcx, (char *)input->data, input->len);
if (rv != SECSuccess) {
fprintf(stderr, "%s: failed to decode message.\n", progName);
NSS_CMSDecoder_Cancel(dcx);
return NULL;
}
cmsg = NSS_CMSDecoder_Finish(dcx);
if (cmsg == NULL) {
fprintf(stderr, "%s: failed to decode message.\n", progName);
return NULL;
}
if (decodeOptions->headerLevel >= 0) {
/*fprintf(out, "SMIME: ", decodeOptions->headerLevel, i);*/
fprintf(out, "SMIME: ");
}
nlevels = NSS_CMSMessage_ContentLevelCount(cmsg);
for (i = 0; i < nlevels; i++) {
NSSCMSContentInfo *cinfo;
SECOidTag typetag;
cinfo = NSS_CMSMessage_ContentLevel(cmsg, i);
typetag = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
if (decodeOptions->headerLevel >= 0)
fprintf(out, "\tlevel=%d.%d; ", decodeOptions->headerLevel, nlevels - i);
switch (typetag) {
case SEC_OID_PKCS7_SIGNED_DATA: {
NSSCMSSignedData *sigd = NULL;
SECItem **digests = NULL;
int nsigners;
int j;
if (decodeOptions->headerLevel >= 0)
fprintf(out, "type=signedData; ");
sigd = (NSSCMSSignedData *)NSS_CMSContentInfo_GetContent(cinfo);
if (sigd == NULL) {
SECU_PrintError(progName, "signedData component missing");
goto loser;
}
/* if we have a content file, but no digests for this signedData */
if (decodeOptions->content.data != NULL &&
!NSS_CMSSignedData_HasDigests(sigd)) {
PLArenaPool *poolp;
SECAlgorithmID **digestalgs;
/* detached content: grab content file */
sitem = decodeOptions->content;
if ((poolp = PORT_NewArena(1024)) == NULL) {
fprintf(stderr, "cmsutil: Out of memory.\n");
goto loser;
}
digestalgs = NSS_CMSSignedData_GetDigestAlgs(sigd);
if (DigestFile(poolp, &digests, &sitem, digestalgs) !=
SECSuccess) {
SECU_PrintError(progName,
"problem computing message digest");
PORT_FreeArena(poolp, PR_FALSE);
goto loser;
}
if (NSS_CMSSignedData_SetDigests(sigd, digestalgs, digests) !=
SECSuccess) {
SECU_PrintError(progName,
"problem setting message digests");
PORT_FreeArena(poolp, PR_FALSE);
goto loser;
}
PORT_FreeArena(poolp, PR_FALSE);
}
/* import the certificates */
if (NSS_CMSSignedData_ImportCerts(sigd,
decodeOptions->options->certHandle,
decodeOptions->options->certUsage,
decodeOptions->keepCerts) !=
SECSuccess) {
SECU_PrintError(progName, "cert import failed");
goto loser;
}
/* find out about signers */
nsigners = NSS_CMSSignedData_SignerInfoCount(sigd);
if (decodeOptions->headerLevel >= 0)
fprintf(out, "nsigners=%d; ", nsigners);
if (nsigners == 0) {
/* Might be a cert transport message
** or might be an invalid message, such as a QA test message
** or a message from an attacker.
*/
rv = NSS_CMSSignedData_VerifyCertsOnly(sigd,
decodeOptions->options->certHandle,
decodeOptions->options->certUsage);
if (rv != SECSuccess) {
fprintf(stderr, "cmsutil: Verify certs-only failed!\n");
goto loser;
}
return cmsg;
}
/* still no digests? */
if (!NSS_CMSSignedData_HasDigests(sigd)) {
SECU_PrintError(progName, "no message digests");
goto loser;
}
for (j = 0; j < nsigners; j++) {
const char *svs;
NSSCMSSignerInfo *si;
NSSCMSVerificationStatus vs;
SECStatus bad;
si = NSS_CMSSignedData_GetSignerInfo(sigd, j);
if (decodeOptions->headerLevel >= 0) {
char *signercn;
static char empty[] = { "" };
signercn = NSS_CMSSignerInfo_GetSignerCommonName(si);
if (signercn == NULL)
signercn = empty;
fprintf(out, "\n\t\tsigner%d.id=\"%s\"; ", j, signercn);
if (signercn != empty)
PORT_Free(signercn);
}
bad = NSS_CMSSignedData_VerifySignerInfo(sigd, j,
decodeOptions->options->certHandle,
decodeOptions->options->certUsage);
vs = NSS_CMSSignerInfo_GetVerificationStatus(si);
svs = NSS_CMSUtil_VerificationStatusToString(vs);
if (decodeOptions->headerLevel >= 0) {
fprintf(out, "signer%d.status=%s; ", j, svs);
/* goto loser ? */
} else if (bad && out) {
fprintf(stderr, "signer %d status = %s\n", j, svs);
goto loser;
}
}
} break;
case SEC_OID_PKCS7_ENVELOPED_DATA: {
NSSCMSEnvelopedData *envd;
if (decodeOptions->headerLevel >= 0)
fprintf(out, "type=envelopedData; ");
envd = (NSSCMSEnvelopedData *)NSS_CMSContentInfo_GetContent(cinfo);
if (envd == NULL) {
SECU_PrintError(progName, "envelopedData component missing");
goto loser;
}
} break;
case SEC_OID_PKCS7_ENCRYPTED_DATA: {
NSSCMSEncryptedData *encd;
if (decodeOptions->headerLevel >= 0)
fprintf(out, "type=encryptedData; ");
encd = (NSSCMSEncryptedData *)NSS_CMSContentInfo_GetContent(cinfo);
if (encd == NULL) {
SECU_PrintError(progName, "encryptedData component missing");
goto loser;
}
} break;
case SEC_OID_PKCS7_DATA:
if (decodeOptions->headerLevel >= 0)
fprintf(out, "type=data; ");
break;
default:
break;
}
if (decodeOptions->headerLevel >= 0)
fprintf(out, "\n");
}
if (!decodeOptions->suppressContent && out) {
SECItem *item = (sitem.data ? &sitem
: NSS_CMSMessage_GetContent(cmsg));
if (item && item->data && item->len) {
fwrite(item->data, item->len, 1, out);
}
}
return cmsg;
loser:
if (cmsg)
NSS_CMSMessage_Destroy(cmsg);
return NULL;
}
/* example of a callback function to use with encoder */
/*
static void
writeout(void *arg, const char *buf, unsigned long len)
{
FILE *f = (FILE *)arg;
if (f != NULL && buf != NULL)
(void)fwrite(buf, len, 1, f);
}
*/
static NSSCMSMessage *
signed_data(struct signOptionsStr *signOptions)
{
NSSCMSMessage *cmsg = NULL;
NSSCMSContentInfo *cinfo;
NSSCMSSignedData *sigd;
NSSCMSSignerInfo *signerinfo;
CERTCertificate *cert = NULL, *ekpcert = NULL;
if (cms_verbose) {
fprintf(stderr, "Input to signed_data:\n");
if (signOptions->options->password)
fprintf(stderr, "password [%s]\n", signOptions->options->password);
else if (signOptions->options->pwfile)
fprintf(stderr, "password file [%s]\n", signOptions->options->pwfile);
else
fprintf(stderr, "password [NULL]\n");
fprintf(stderr, "certUsage [%d]\n", signOptions->options->certUsage);
if (signOptions->options->certHandle)
fprintf(stderr, "certdb [%p]\n", signOptions->options->certHandle);
else
fprintf(stderr, "certdb [NULL]\n");
if (signOptions->nickname)
fprintf(stderr, "nickname [%s]\n", signOptions->nickname);
else
fprintf(stderr, "nickname [NULL]\n");
}
if (signOptions->nickname == NULL) {
fprintf(stderr,
"ERROR: please indicate the nickname of a certificate to sign with.\n");
return NULL;
}
if ((cert = CERT_FindUserCertByUsage(signOptions->options->certHandle,
signOptions->nickname,
signOptions->options->certUsage,
PR_FALSE,
&pwdata)) == NULL) {
SECU_PrintError(progName,
"the corresponding cert for key \"%s\" does not exist",
signOptions->nickname);
return NULL;
}
if (cms_verbose) {
fprintf(stderr, "Found certificate for %s\n", signOptions->nickname);
}
/*
* create the message object
*/
cmsg = NSS_CMSMessage_Create(NULL); /* create a message on its own pool */
if (cmsg == NULL) {
fprintf(stderr, "ERROR: cannot create CMS message.\n");
return NULL;
}
/*
* build chain of objects: message->signedData->data
*/
if ((sigd = NSS_CMSSignedData_Create(cmsg)) == NULL) {
fprintf(stderr, "ERROR: cannot create CMS signedData object.\n");
goto loser;
}
cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
if (NSS_CMSContentInfo_SetContent_SignedData(cmsg, cinfo, sigd) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS signedData object.\n");
goto loser;
}
cinfo = NSS_CMSSignedData_GetContentInfo(sigd);
/* we're always passing data in and detaching optionally */
if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL,
signOptions->detached) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS data object.\n");
goto loser;
}
/*
* create & attach signer information
*/
signerinfo = NSS_CMSSignerInfo_Create(cmsg, cert, signOptions->hashAlgTag);
if (signerinfo == NULL) {
fprintf(stderr, "ERROR: cannot create CMS signerInfo object.\n");
goto loser;
}
if (cms_verbose) {
fprintf(stderr,
"Created CMS message, added signed data w/ signerinfo\n");
}
signerinfo->cmsg->pwfn_arg = pwcb_arg;
/* we want the cert chain included for this one */
if (NSS_CMSSignerInfo_IncludeCerts(signerinfo, NSSCMSCM_CertChain,
signOptions->options->certUsage) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot find cert chain.\n");
goto loser;
}
if (cms_verbose) {
fprintf(stderr, "imported certificate\n");
}
if (signOptions->signingTime) {
if (NSS_CMSSignerInfo_AddSigningTime(signerinfo, PR_Now()) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot add signingTime attribute.\n");
goto loser;
}
}
if (signOptions->smimeProfile) {
if (NSS_CMSSignerInfo_AddSMIMECaps(signerinfo) != SECSuccess) {
fprintf(stderr, "ERROR: cannot add SMIMECaps attribute.\n");
goto loser;
}
}
if (!signOptions->encryptionKeyPreferenceNick) {
/* check signing cert for fitness as encryption cert */
SECStatus FitForEncrypt = CERT_CheckCertUsage(cert,
certUsageEmailRecipient);
if (SECSuccess == FitForEncrypt) {
/* if yes, add signing cert as EncryptionKeyPreference */
if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, cert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr,
"ERROR: cannot add default SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
if (NSS_CMSSignerInfo_AddMSSMIMEEncKeyPrefs(signerinfo, cert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr,
"ERROR: cannot add default MS SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
} else {
/* this is a dual-key cert case, we need to look for the encryption
certificate under the same nickname as the signing cert */
/* get the cert, add it to the message */
if ((ekpcert = CERT_FindUserCertByUsage(
signOptions->options->certHandle,
signOptions->nickname,
certUsageEmailRecipient,
PR_FALSE,
&pwdata)) == NULL) {
SECU_PrintError(progName,
"the corresponding cert for key \"%s\" does not exist",
signOptions->encryptionKeyPreferenceNick);
goto loser;
}
if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, ekpcert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr,
"ERROR: cannot add SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
if (NSS_CMSSignerInfo_AddMSSMIMEEncKeyPrefs(signerinfo, ekpcert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr,
"ERROR: cannot add MS SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
if (NSS_CMSSignedData_AddCertificate(sigd, ekpcert) != SECSuccess) {
fprintf(stderr, "ERROR: cannot add encryption certificate.\n");
goto loser;
}
}
} else if (PL_strcmp(signOptions->encryptionKeyPreferenceNick, "NONE") == 0) {
/* No action */
} else {
/* get the cert, add it to the message */
if ((ekpcert = CERT_FindUserCertByUsage(
signOptions->options->certHandle,
signOptions->encryptionKeyPreferenceNick,
certUsageEmailRecipient, PR_FALSE, &pwdata)) ==
NULL) {
SECU_PrintError(progName,
"the corresponding cert for key \"%s\" does not exist",
signOptions->encryptionKeyPreferenceNick);
goto loser;
}
if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, ekpcert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot add SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
if (NSS_CMSSignerInfo_AddMSSMIMEEncKeyPrefs(signerinfo, ekpcert,
signOptions->options->certHandle) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot add MS SMIMEEncKeyPrefs attribute.\n");
goto loser;
}
if (NSS_CMSSignedData_AddCertificate(sigd, ekpcert) != SECSuccess) {
fprintf(stderr, "ERROR: cannot add encryption certificate.\n");
goto loser;
}
}
if (NSS_CMSSignedData_AddSignerInfo(sigd, signerinfo) != SECSuccess) {
fprintf(stderr, "ERROR: cannot add CMS signerInfo object.\n");
goto loser;
}
if (cms_verbose) {
fprintf(stderr, "created signed-data message\n");
}
if (ekpcert) {
CERT_DestroyCertificate(ekpcert);
}
if (cert) {
CERT_DestroyCertificate(cert);
}
return cmsg;
loser:
if (ekpcert) {
CERT_DestroyCertificate(ekpcert);
}
if (cert) {
CERT_DestroyCertificate(cert);
}
NSS_CMSMessage_Destroy(cmsg);
return NULL;
}
static NSSCMSMessage *
enveloped_data(struct envelopeOptionsStr *envelopeOptions)
{
NSSCMSMessage *cmsg = NULL;
NSSCMSContentInfo *cinfo;
NSSCMSEnvelopedData *envd;
NSSCMSRecipientInfo *recipientinfo;
CERTCertificate **recipientcerts = NULL;
CERTCertDBHandle *dbhandle;
PLArenaPool *tmppoolp = NULL;
SECOidTag bulkalgtag;
int keysize, i = 0;
int cnt;
dbhandle = envelopeOptions->options->certHandle;
/* count the recipients */
if ((cnt = nss_CMSArray_Count((void **)envelopeOptions->recipients)) == 0) {
fprintf(stderr, "ERROR: please name at least one recipient.\n");
goto loser;
}
if ((tmppoolp = PORT_NewArena(1024)) == NULL) {
fprintf(stderr, "ERROR: out of memory.\n");
goto loser;
}
/* XXX find the recipient's certs by email address or nickname */
if ((recipientcerts =
(CERTCertificate **)PORT_ArenaZAlloc(tmppoolp,
(cnt + 1) * sizeof(CERTCertificate *))) ==
NULL) {
fprintf(stderr, "ERROR: out of memory.\n");
goto loser;
}
for (i = 0; envelopeOptions->recipients[i] != NULL; i++) {
if ((recipientcerts[i] =
CERT_FindCertByNicknameOrEmailAddr(dbhandle,
envelopeOptions->recipients[i])) ==
NULL) {
SECU_PrintError(progName, "cannot find certificate for \"%s\"",
envelopeOptions->recipients[i]);
i = 0;
goto loser;
}
}
recipientcerts[i] = NULL;
i = 0;
/* find a nice bulk algorithm */
if (NSS_SMIMEUtil_FindBulkAlgForRecipients(recipientcerts, &bulkalgtag,
&keysize) != SECSuccess) {
fprintf(stderr, "ERROR: cannot find common bulk algorithm.\n");
goto loser;
}
/*
* create the message object
*/
cmsg = NSS_CMSMessage_Create(NULL); /* create a message on its own pool */
if (cmsg == NULL) {
fprintf(stderr, "ERROR: cannot create CMS message.\n");
goto loser;
}
/*
* build chain of objects: message->envelopedData->data
*/
if ((envd = NSS_CMSEnvelopedData_Create(cmsg, bulkalgtag, keysize)) ==
NULL) {
fprintf(stderr, "ERROR: cannot create CMS envelopedData object.\n");
goto loser;
}
cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
if (NSS_CMSContentInfo_SetContent_EnvelopedData(cmsg, cinfo, envd) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS envelopedData object.\n");
goto loser;
}
cinfo = NSS_CMSEnvelopedData_GetContentInfo(envd);
/* we're always passing data in, so the content is NULL */
if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL, PR_FALSE) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS data object.\n");
goto loser;
}
/*
* create & attach recipient information
*/
for (i = 0; recipientcerts[i] != NULL; i++) {
if ((recipientinfo = NSS_CMSRecipientInfo_Create(cmsg,
recipientcerts[i])) ==
NULL) {
fprintf(stderr, "ERROR: cannot create CMS recipientInfo object.\n");
goto loser;
}
if (NSS_CMSEnvelopedData_AddRecipient(envd, recipientinfo) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot add CMS recipientInfo object.\n");
goto loser;
}
CERT_DestroyCertificate(recipientcerts[i]);
}
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
return cmsg;
loser:
if (recipientcerts) {
for (; recipientcerts[i] != NULL; i++) {
CERT_DestroyCertificate(recipientcerts[i]);
}
}
if (cmsg)
NSS_CMSMessage_Destroy(cmsg);
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
return NULL;
}
PK11SymKey *
dkcb(void *arg, SECAlgorithmID *algid)
{
return (PK11SymKey *)arg;
}
static SECStatus
get_enc_params(struct encryptOptionsStr *encryptOptions)
{
struct envelopeOptionsStr envelopeOptions;
SECStatus rv = SECFailure;
NSSCMSMessage *env_cmsg;
NSSCMSContentInfo *cinfo;
int i, nlevels;
/*
* construct an enveloped data message to obtain bulk keys
*/
if (encryptOptions->envmsg) {
env_cmsg = encryptOptions->envmsg; /* get it from an old message */
} else {
SECItem dummyOut = { 0, 0, 0 };
SECItem dummyIn = { 0, 0, 0 };
char str[] = "Hello!";
PLArenaPool *tmparena = PORT_NewArena(1024);
dummyIn.data = (unsigned char *)str;
dummyIn.len = strlen(str);
envelopeOptions.options = encryptOptions->options;
envelopeOptions.recipients = encryptOptions->recipients;
env_cmsg = enveloped_data(&envelopeOptions);
NSS_CMSDEREncode(env_cmsg, &dummyIn, &dummyOut, tmparena);
PR_Write(encryptOptions->envFile, dummyOut.data, dummyOut.len);
PORT_FreeArena(tmparena, PR_FALSE);
}
/*
* get the content info for the enveloped data
*/
nlevels = NSS_CMSMessage_ContentLevelCount(env_cmsg);
for (i = 0; i < nlevels; i++) {
SECOidTag typetag;
cinfo = NSS_CMSMessage_ContentLevel(env_cmsg, i);
typetag = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
if (typetag == SEC_OID_PKCS7_DATA) {
/*
* get the symmetric key
*/
encryptOptions->bulkalgtag = NSS_CMSContentInfo_GetContentEncAlgTag(cinfo);
encryptOptions->keysize = NSS_CMSContentInfo_GetBulkKeySize(cinfo);
encryptOptions->bulkkey = NSS_CMSContentInfo_GetBulkKey(cinfo);
rv = SECSuccess;
break;
}
}
if (i == nlevels) {
fprintf(stderr, "%s: could not retrieve enveloped data.", progName);
}
if (env_cmsg)
NSS_CMSMessage_Destroy(env_cmsg);
return rv;
}
static NSSCMSMessage *
encrypted_data(struct encryptOptionsStr *encryptOptions)
{
SECStatus rv = SECFailure;
NSSCMSMessage *cmsg = NULL;
NSSCMSContentInfo *cinfo;
NSSCMSEncryptedData *encd;
NSSCMSEncoderContext *ecx = NULL;
PLArenaPool *tmppoolp = NULL;
SECItem derOut = { 0, 0, 0 };
/* arena for output */
tmppoolp = PORT_NewArena(1024);
if (!tmppoolp) {
fprintf(stderr, "%s: out of memory.\n", progName);
return NULL;
}
/*
* create the message object
*/
cmsg = NSS_CMSMessage_Create(NULL);
if (cmsg == NULL) {
fprintf(stderr, "ERROR: cannot create CMS message.\n");
goto loser;
}
/*
* build chain of objects: message->encryptedData->data
*/
if ((encd = NSS_CMSEncryptedData_Create(cmsg, encryptOptions->bulkalgtag,
encryptOptions->keysize)) ==
NULL) {
fprintf(stderr, "ERROR: cannot create CMS encryptedData object.\n");
goto loser;
}
cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
if (NSS_CMSContentInfo_SetContent_EncryptedData(cmsg, cinfo, encd) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS encryptedData object.\n");
goto loser;
}
cinfo = NSS_CMSEncryptedData_GetContentInfo(encd);
/* we're always passing data in, so the content is NULL */
if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL, PR_FALSE) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS data object.\n");
goto loser;
}
ecx = NSS_CMSEncoder_Start(cmsg, NULL, NULL, &derOut, tmppoolp, NULL, NULL,
dkcb, encryptOptions->bulkkey, NULL, NULL);
if (!ecx) {
fprintf(stderr, "%s: cannot create encoder context.\n", progName);
goto loser;
}
rv = NSS_CMSEncoder_Update(ecx, (char *)encryptOptions->input->data,
encryptOptions->input->len);
if (rv) {
fprintf(stderr, "%s: failed to add data to encoder.\n", progName);
goto loser;
}
rv = NSS_CMSEncoder_Finish(ecx);
if (rv) {
fprintf(stderr, "%s: failed to encrypt data.\n", progName);
goto loser;
}
fwrite(derOut.data, derOut.len, 1, encryptOptions->outfile);
/*
if (bulkkey)
PK11_FreeSymKey(bulkkey);
*/
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
return cmsg;
loser:
/*
if (bulkkey)
PK11_FreeSymKey(bulkkey);
*/
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
if (cmsg)
NSS_CMSMessage_Destroy(cmsg);
return NULL;
}
static NSSCMSMessage *
signed_data_certsonly(struct certsonlyOptionsStr *certsonlyOptions)
{
NSSCMSMessage *cmsg = NULL;
NSSCMSContentInfo *cinfo;
NSSCMSSignedData *sigd;
CERTCertificate **certs = NULL;
CERTCertDBHandle *dbhandle;
PLArenaPool *tmppoolp = NULL;
int i = 0, cnt;
dbhandle = certsonlyOptions->options->certHandle;
if ((cnt = nss_CMSArray_Count((void **)certsonlyOptions->recipients)) == 0) {
fprintf(stderr,
"ERROR: please indicate the nickname of a certificate to sign with.\n");
goto loser;
}
if (!(tmppoolp = PORT_NewArena(1024))) {
fprintf(stderr, "ERROR: out of memory.\n");
goto loser;
}
if (!(certs = PORT_ArenaZNewArray(tmppoolp, CERTCertificate *, cnt + 1))) {
fprintf(stderr, "ERROR: out of memory.\n");
goto loser;
}
for (i = 0; certsonlyOptions->recipients[i] != NULL; i++) {
if ((certs[i] =
CERT_FindCertByNicknameOrEmailAddr(dbhandle,
certsonlyOptions->recipients[i])) ==
NULL) {
SECU_PrintError(progName, "cannot find certificate for \"%s\"",
certsonlyOptions->recipients[i]);
i = 0;
goto loser;
}
}
certs[i] = NULL;
i = 0;
/*
* create the message object
*/
cmsg = NSS_CMSMessage_Create(NULL);
if (cmsg == NULL) {
fprintf(stderr, "ERROR: cannot create CMS message.\n");
goto loser;
}
/*
* build chain of objects: message->signedData->data
*/
if ((sigd = NSS_CMSSignedData_CreateCertsOnly(cmsg, certs[0], PR_TRUE)) ==
NULL) {
fprintf(stderr, "ERROR: cannot create CMS signedData object.\n");
goto loser;
}
CERT_DestroyCertificate(certs[0]);
for (i = 1; i < cnt; i++) {
if (NSS_CMSSignedData_AddCertChain(sigd, certs[i])) {
fprintf(stderr, "ERROR: cannot add cert chain for \"%s\".\n",
certsonlyOptions->recipients[i]);
goto loser;
}
CERT_DestroyCertificate(certs[i]);
}
cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
if (NSS_CMSContentInfo_SetContent_SignedData(cmsg, cinfo, sigd) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS signedData object.\n");
goto loser;
}
cinfo = NSS_CMSSignedData_GetContentInfo(sigd);
if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL, PR_FALSE) !=
SECSuccess) {
fprintf(stderr, "ERROR: cannot attach CMS data object.\n");
goto loser;
}
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
return cmsg;
loser:
if (certs) {
for (; i < cnt; i++) {
CERT_DestroyCertificate(certs[i]);
}
}
if (cmsg)
NSS_CMSMessage_Destroy(cmsg);
if (tmppoolp)
PORT_FreeArena(tmppoolp, PR_FALSE);
return NULL;
}
static char *
pl_fgets(char *buf, int size, PRFileDesc *fd)
{
char *bp = buf;
int nb = 0;
;
while (size > 1) {
nb = PR_Read(fd, bp, 1);
if (nb < 0) {
/* deal with error */
return NULL;
} else if (nb == 0) {
/* deal with EOF */
return NULL;
} else if (*bp == '\n') {
/* deal with EOL */
++bp; /* keep EOL character */
break;
} else {
/* ordinary character */
++bp;
--size;
}
}
*bp = '\0';
return buf;
}
typedef enum { UNKNOWN,
DECODE,
SIGN,
ENCRYPT,
ENVELOPE,
CERTSONLY } Mode;
static int
doBatchDecode(FILE *outFile, PRFileDesc *batchFile,
const struct decodeOptionsStr *decodeOptions)
{
char *str;
int exitStatus = 0;
char batchLine[512];