/
pk11merge.c
1437 lines (1314 loc) · 45.7 KB
/
pk11merge.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/. */
/*
* Merge the source token into the target token.
*/
#include "secmod.h"
#include "secmodi.h"
#include "secmodti.h"
#include "pk11pub.h"
#include "pk11priv.h"
#include "pkcs11.h"
#include "seccomon.h"
#include "secerr.h"
#include "keyhi.h"
#include "hasht.h"
#include "cert.h"
#include "certdb.h"
/*************************************************************************
*
* short utilities to aid in the merge
*
*************************************************************************/
/*
* write a bunch of attributes out to an existing object.
*/
static SECStatus
pk11_setAttributes(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
CK_ATTRIBUTE *setTemplate, CK_ULONG setTemplCount)
{
CK_RV crv;
CK_SESSION_HANDLE rwsession;
rwsession = PK11_GetRWSession(slot);
if (rwsession == CK_INVALID_HANDLE) {
PORT_SetError(SEC_ERROR_BAD_DATA);
return SECFailure;
}
crv = PK11_GETTAB(slot)->C_SetAttributeValue(rwsession, id,
setTemplate, setTemplCount);
PK11_RestoreROSession(slot, rwsession);
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv));
return SECFailure;
}
return SECSuccess;
}
/*
* copy a template of attributes from a source object to a target object.
* if target object is not given, create it.
*/
static SECStatus
pk11_copyAttributes(PLArenaPool *arena,
PK11SlotInfo *targetSlot, CK_OBJECT_HANDLE targetID,
PK11SlotInfo *sourceSlot, CK_OBJECT_HANDLE sourceID,
CK_ATTRIBUTE *copyTemplate, CK_ULONG copyTemplateCount)
{
SECStatus rv;
CK_ATTRIBUTE *newTemplate = NULL;
CK_RV crv;
crv = PK11_GetAttributes(arena, sourceSlot, sourceID,
copyTemplate, copyTemplateCount);
/* if we have missing attributes, just skip them and create the object */
if (crv == CKR_ATTRIBUTE_TYPE_INVALID) {
CK_ULONG i, j;
newTemplate = PORT_NewArray(CK_ATTRIBUTE, copyTemplateCount);
if (!newTemplate) {
return SECFailure;
}
/* remove the unknown attributes. If we don't have enough attributes
* PK11_CreateNewObject() will fail */
for (i = 0, j = 0; i < copyTemplateCount; i++) {
if (copyTemplate[i].ulValueLen != -1) {
newTemplate[j] = copyTemplate[i];
j++;
}
}
copyTemplate = newTemplate;
copyTemplateCount = j;
crv = PK11_GetAttributes(arena, sourceSlot, sourceID,
copyTemplate, copyTemplateCount);
}
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv));
PORT_Free(newTemplate);
return SECFailure;
}
if (targetID == CK_INVALID_HANDLE) {
/* we need to create the object */
rv = PK11_CreateNewObject(targetSlot, CK_INVALID_HANDLE,
copyTemplate, copyTemplateCount, PR_TRUE, &targetID);
} else {
/* update the existing object with the new attributes */
rv = pk11_setAttributes(targetSlot, targetID,
copyTemplate, copyTemplateCount);
}
if (newTemplate) {
PORT_Free(newTemplate);
}
return rv;
}
/*
* look for a matching object across tokens.
*/
static SECStatus
pk11_matchAcrossTokens(PLArenaPool *arena, PK11SlotInfo *targetSlot,
PK11SlotInfo *sourceSlot,
CK_ATTRIBUTE *template, CK_ULONG tsize,
CK_OBJECT_HANDLE id, CK_OBJECT_HANDLE *peer)
{
CK_RV crv;
*peer = CK_INVALID_HANDLE;
crv = PK11_GetAttributes(arena, sourceSlot, id, template, tsize);
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv));
goto loser;
}
if (template[0].ulValueLen == -1) {
crv = CKR_ATTRIBUTE_TYPE_INVALID;
PORT_SetError(PK11_MapError(crv));
goto loser;
}
*peer = pk11_FindObjectByTemplate(targetSlot, template, tsize);
return SECSuccess;
loser:
return SECFailure;
}
/*
* Encrypt using key and parameters
*/
SECStatus
pk11_encrypt(PK11SymKey *symKey, CK_MECHANISM_TYPE mechType, SECItem *param,
SECItem *input, SECItem **output)
{
PK11Context *ctxt = NULL;
SECStatus rv = SECSuccess;
if (*output) {
SECITEM_FreeItem(*output, PR_TRUE);
}
*output = SECITEM_AllocItem(NULL, NULL, input->len + 20 /*slop*/);
if (!*output) {
rv = SECFailure;
goto done;
}
ctxt = PK11_CreateContextBySymKey(mechType, CKA_ENCRYPT, symKey, param);
if (ctxt == NULL) {
rv = SECFailure;
goto done;
}
rv = PK11_CipherOp(ctxt, (*output)->data,
(int *)&((*output)->len),
(*output)->len, input->data, input->len);
done:
if (ctxt) {
PK11_Finalize(ctxt);
PK11_DestroyContext(ctxt, PR_TRUE);
}
if (rv != SECSuccess) {
if (*output) {
SECITEM_FreeItem(*output, PR_TRUE);
*output = NULL;
}
}
return rv;
}
/*************************************************************************
*
* Private Keys
*
*************************************************************************/
/*
* Fetch the key usage based on the pkcs #11 flags
*/
unsigned int
pk11_getPrivateKeyUsage(PK11SlotInfo *slot, CK_OBJECT_HANDLE id)
{
unsigned int usage = 0;
if ((PK11_HasAttributeSet(slot, id, CKA_UNWRAP, PR_FALSE) ||
PK11_HasAttributeSet(slot, id, CKA_DECRYPT, PR_FALSE))) {
usage |= KU_KEY_ENCIPHERMENT;
}
if (PK11_HasAttributeSet(slot, id, CKA_DERIVE, PR_FALSE)) {
usage |= KU_KEY_AGREEMENT;
}
if ((PK11_HasAttributeSet(slot, id, CKA_SIGN_RECOVER, PR_FALSE) ||
PK11_HasAttributeSet(slot, id, CKA_SIGN, PR_FALSE))) {
usage |= KU_DIGITAL_SIGNATURE;
}
return usage;
}
/*
* merge a private key,
*
* Private keys are merged using PBE wrapped keys with a random
* value as the 'password'. Once the base key is moved, The remaining
* attributes (SUBJECT) is copied.
*/
static SECStatus
pk11_mergePrivateKey(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
SECKEYPrivateKey *sourceKey = NULL;
CK_OBJECT_HANDLE targetKeyID;
SECKEYEncryptedPrivateKeyInfo *epki = NULL;
char *nickname = NULL;
SECItem nickItem;
SECItem pwitem;
SECItem publicValue;
PLArenaPool *arena = NULL;
SECStatus rv = SECSuccess;
unsigned int keyUsage;
unsigned char randomData[SHA1_LENGTH];
SECOidTag algTag = SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC;
CK_ATTRIBUTE privTemplate[] = {
{ CKA_ID, NULL, 0 },
{ CKA_CLASS, NULL, 0 }
};
CK_ULONG privTemplateCount = sizeof(privTemplate) / sizeof(privTemplate[0]);
CK_ATTRIBUTE privCopyTemplate[] = {
{ CKA_SUBJECT, NULL, 0 }
};
CK_ULONG privCopyTemplateCount =
sizeof(privCopyTemplate) / sizeof(privCopyTemplate[0]);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
/* check to see if the key is already in the target slot */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot, privTemplate,
privTemplateCount, id, &targetKeyID);
if (rv != SECSuccess) {
goto done;
}
if (targetKeyID != CK_INVALID_HANDLE) {
/* match found, not an error ... */
goto done;
}
/* get an NSS representation of our source key */
sourceKey = PK11_MakePrivKey(sourceSlot, nullKey, PR_FALSE,
id, sourcePwArg);
if (sourceKey == NULL) {
rv = SECFailure;
goto done;
}
/* Load the private key */
/* generate a random pwitem */
rv = PK11_GenerateRandom(randomData, sizeof(randomData));
if (rv != SECSuccess) {
goto done;
}
pwitem.data = randomData;
pwitem.len = sizeof(randomData);
/* fetch the private key encrypted */
epki = PK11_ExportEncryptedPrivKeyInfo(sourceSlot, algTag, &pwitem,
sourceKey, 1, sourcePwArg);
if (epki == NULL) {
rv = SECFailure;
goto done;
}
nickname = PK11_GetObjectNickname(sourceSlot, id);
/* NULL nickanme is fine (in fact is often normal) */
if (nickname) {
nickItem.data = (unsigned char *)nickname;
nickItem.len = PORT_Strlen(nickname);
}
keyUsage = pk11_getPrivateKeyUsage(sourceSlot, id);
/* pass in the CKA_ID */
publicValue.data = privTemplate[0].pValue;
publicValue.len = privTemplate[0].ulValueLen;
rv = PK11_ImportEncryptedPrivateKeyInfo(targetSlot, epki, &pwitem,
nickname ? &nickItem : NULL, &publicValue,
PR_TRUE, PR_TRUE, sourceKey->keyType, keyUsage,
targetPwArg);
if (rv != SECSuccess) {
goto done;
}
/* make sure it made it */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot, privTemplate,
privTemplateCount, id, &targetKeyID);
if (rv != SECSuccess) {
goto done;
}
if (targetKeyID == CK_INVALID_HANDLE) {
/* this time the key should exist */
rv = SECFailure;
goto done;
}
/* fill in remaining attributes */
rv = pk11_copyAttributes(arena, targetSlot, targetKeyID, sourceSlot, id,
privCopyTemplate, privCopyTemplateCount);
done:
/* make sure the 'key' is cleared */
PORT_Memset(randomData, 0, sizeof(randomData));
if (nickname) {
PORT_Free(nickname);
}
if (sourceKey) {
SECKEY_DestroyPrivateKey(sourceKey);
}
if (epki) {
SECKEY_DestroyEncryptedPrivateKeyInfo(epki, PR_TRUE);
}
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return rv;
}
/*************************************************************************
*
* Secret Keys
*
*************************************************************************/
/*
* we need to find a unique CKA_ID.
* The basic idea is to just increment the lowest byte.
* This code also handles the following corner cases:
* 1) the single byte overflows. On overflow we increment the next byte up
* and so forth until we have overflowed the entire CKA_ID.
* 2) If we overflow the entire CKA_ID we expand it by one byte.
* 3) the CKA_ID is non-existent, we create a new one with one byte.
* This means no matter what CKA_ID is passed, the result of this function
* is always a new CKA_ID, and this function will never return the same
* CKA_ID the it has returned in the passed.
*/
static SECStatus
pk11_incrementID(PLArenaPool *arena, CK_ATTRIBUTE *ptemplate)
{
unsigned char *buf = ptemplate->pValue;
CK_ULONG len = ptemplate->ulValueLen;
if (buf == NULL || len == (CK_ULONG)-1) {
/* we have no valid CKAID, we'll create a basic one byte CKA_ID below */
len = 0;
} else {
CK_ULONG i;
/* walk from the back to front, incrementing
* the CKA_ID until we no longer have a carry,
* or have hit the front of the id. */
for (i = len; i != 0; i--) {
buf[i - 1]++;
if (buf[i - 1] != 0) {
/* no more carries, the increment is complete */
return SECSuccess;
}
}
/* we've now overflowed, fall through and expand the CKA_ID by
* one byte */
}
/* if we are here we've run the counter to zero (indicating an overflow).
* create an CKA_ID that is all zeros, but has one more zero than
* the previous CKA_ID */
buf = PORT_ArenaZAlloc(arena, len + 1);
if (buf == NULL) {
return SECFailure;
}
ptemplate->pValue = buf;
ptemplate->ulValueLen = len + 1;
return SECSuccess;
}
static CK_FLAGS
pk11_getSecretKeyFlags(PK11SlotInfo *slot, CK_OBJECT_HANDLE id)
{
CK_FLAGS flags = 0;
if (PK11_HasAttributeSet(slot, id, CKA_UNWRAP, PR_FALSE)) {
flags |= CKF_UNWRAP;
}
if (PK11_HasAttributeSet(slot, id, CKA_WRAP, PR_FALSE)) {
flags |= CKF_WRAP;
}
if (PK11_HasAttributeSet(slot, id, CKA_ENCRYPT, PR_FALSE)) {
flags |= CKF_ENCRYPT;
}
if (PK11_HasAttributeSet(slot, id, CKA_DECRYPT, PR_FALSE)) {
flags |= CKF_DECRYPT;
}
if (PK11_HasAttributeSet(slot, id, CKA_DERIVE, PR_FALSE)) {
flags |= CKF_DERIVE;
}
if (PK11_HasAttributeSet(slot, id, CKA_SIGN, PR_FALSE)) {
flags |= CKF_SIGN;
}
if (PK11_HasAttributeSet(slot, id, CKA_SIGN_RECOVER, PR_FALSE)) {
flags |= CKF_SIGN_RECOVER;
}
if (PK11_HasAttributeSet(slot, id, CKA_VERIFY, PR_FALSE)) {
flags |= CKF_VERIFY;
}
if (PK11_HasAttributeSet(slot, id, CKA_VERIFY_RECOVER, PR_FALSE)) {
flags |= CKF_VERIFY_RECOVER;
}
return flags;
}
static const char testString[] =
"My Encrytion Test Data (should be at least 32 bytes long)";
/*
* merge a secret key,
*
* Secret keys may collide by CKA_ID as we merge 2 token. If we collide
* on the CKA_ID, we need to make sure we are dealing with different keys.
* The reason for this is it is possible that we've merged this database
* before, and this key could have been merged already. If the keys are
* the same, we are done. If they are not, we need to update the CKA_ID of
* the source key and try again.
*
* Once we know we have a unique key to merge in, we use NSS's underlying
* key Move function which will do a key exchange if necessary to move
* the key from one token to another. Then we set the CKA_ID and additional
* pkcs #11 attributes.
*/
static SECStatus
pk11_mergeSecretKey(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
PK11SymKey *sourceKey = NULL;
PK11SymKey *targetKey = NULL;
SECItem *sourceOutput = NULL;
SECItem *targetOutput = NULL;
SECItem *param = NULL;
int blockSize;
SECItem input;
CK_OBJECT_HANDLE targetKeyID;
CK_FLAGS flags;
PLArenaPool *arena = NULL;
SECStatus rv = SECSuccess;
CK_MECHANISM_TYPE keyMechType, cryptoMechType;
CK_KEY_TYPE sourceKeyType, targetKeyType;
CK_ATTRIBUTE symTemplate[] = {
{ CKA_ID, NULL, 0 },
{ CKA_CLASS, NULL, 0 }
};
const CK_ULONG symTemplateCount = sizeof(symTemplate) / sizeof(symTemplate[0]);
CK_ATTRIBUTE symCopyTemplate[] = {
{ CKA_LABEL, NULL, 0 }
};
CK_ULONG symCopyTemplateCount =
sizeof(symCopyTemplate) / sizeof(symCopyTemplate[0]);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
sourceKeyType = PK11_ReadULongAttribute(sourceSlot, id, CKA_KEY_TYPE);
if (sourceKeyType == (CK_ULONG)-1) {
rv = SECFailure;
goto done;
}
/* get the key mechanism */
keyMechType = PK11_GetKeyMechanism(sourceKeyType);
/* get a mechanism suitable to encryption.
* PK11_GetKeyMechanism returns a mechanism that is unique to the key
* type. It tries to return encryption/decryption mechanisms, however
* CKM_DES3_CBC uses and abmiguous keyType, so keyMechType is returned as
* 'keygen' mechanism. Detect that case here */
cryptoMechType = keyMechType;
if ((keyMechType == CKM_DES3_KEY_GEN) ||
(keyMechType == CKM_DES2_KEY_GEN)) {
cryptoMechType = CKM_DES3_CBC;
}
sourceKey = PK11_SymKeyFromHandle(sourceSlot, NULL, PK11_OriginDerive,
keyMechType, id, PR_FALSE, sourcePwArg);
if (sourceKey == NULL) {
rv = SECFailure;
goto done;
}
/* check to see a key with the same CKA_ID already exists in
* the target slot. If it does, then we need to verify if the keys
* really matches. If they don't import the key with a new CKA_ID
* value. */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot,
symTemplate, symTemplateCount, id, &targetKeyID);
if (rv != SECSuccess) {
goto done;
}
/* set up the input test */
input.data = (unsigned char *)testString;
blockSize = PK11_GetBlockSize(cryptoMechType, NULL);
if (blockSize < 0) {
rv = SECFailure;
goto done;
}
input.len = blockSize;
if (input.len == 0) {
input.len = sizeof(testString);
}
while (targetKeyID != CK_INVALID_HANDLE) {
/* test to see if the keys are identical */
targetKeyType = PK11_ReadULongAttribute(sourceSlot, id, CKA_KEY_TYPE);
if (targetKeyType == sourceKeyType) {
/* same keyType - see if it's the same key */
targetKey = PK11_SymKeyFromHandle(targetSlot, NULL,
PK11_OriginDerive, keyMechType, targetKeyID, PR_FALSE,
targetPwArg);
/* get a parameter if we don't already have one */
if (!param) {
param = PK11_GenerateNewParam(cryptoMechType, sourceKey);
if (param == NULL) {
rv = SECFailure;
goto done;
}
}
/* use the source key to encrypt a reference */
if (!sourceOutput) {
rv = pk11_encrypt(sourceKey, cryptoMechType, param, &input,
&sourceOutput);
if (rv != SECSuccess) {
goto done;
}
}
/* encrypt the reference with the target key */
rv = pk11_encrypt(targetKey, cryptoMechType, param, &input,
&targetOutput);
if (rv == SECSuccess) {
if (SECITEM_ItemsAreEqual(sourceOutput, targetOutput)) {
/* they produce the same output, they must be the
* same key */
goto done;
}
SECITEM_FreeItem(targetOutput, PR_TRUE);
targetOutput = NULL;
}
PK11_FreeSymKey(targetKey);
targetKey = NULL;
}
/* keys aren't equal, update the KEY_ID and look again */
rv = pk11_incrementID(arena, &symTemplate[0]);
if (rv != SECSuccess) {
goto done;
}
targetKeyID = pk11_FindObjectByTemplate(targetSlot,
symTemplate, symTemplateCount);
}
/* we didn't find a matching key, import this one with the new
* CKAID */
flags = pk11_getSecretKeyFlags(sourceSlot, id);
targetKey = PK11_MoveSymKey(targetSlot, PK11_OriginDerive, flags, PR_TRUE,
sourceKey);
if (targetKey == NULL) {
rv = SECFailure;
goto done;
}
/* set the key new CKAID */
rv = pk11_setAttributes(targetSlot, targetKey->objectID, symTemplate, 1);
if (rv != SECSuccess) {
goto done;
}
/* fill in remaining attributes */
rv = pk11_copyAttributes(arena, targetSlot, targetKey->objectID,
sourceSlot, id, symCopyTemplate, symCopyTemplateCount);
done:
if (sourceKey) {
PK11_FreeSymKey(sourceKey);
}
if (targetKey) {
PK11_FreeSymKey(targetKey);
}
if (sourceOutput) {
SECITEM_FreeItem(sourceOutput, PR_TRUE);
}
if (targetOutput) {
SECITEM_FreeItem(targetOutput, PR_TRUE);
}
if (param) {
SECITEM_FreeItem(param, PR_TRUE);
}
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return rv;
}
/*************************************************************************
*
* Public Keys
*
*************************************************************************/
/*
* Merge public key
*
* Use the high level NSS calls to extract the public key and import it
* into the token. Extra attributes are then copied to the new token.
*/
static SECStatus
pk11_mergePublicKey(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
SECKEYPublicKey *sourceKey = NULL;
CK_OBJECT_HANDLE targetKeyID;
PLArenaPool *arena = NULL;
SECStatus rv = SECSuccess;
CK_ATTRIBUTE pubTemplate[] = {
{ CKA_ID, NULL, 0 },
{ CKA_CLASS, NULL, 0 }
};
CK_ULONG pubTemplateCount = sizeof(pubTemplate) / sizeof(pubTemplate[0]);
CK_ATTRIBUTE pubCopyTemplate[] = {
{ CKA_ID, NULL, 0 },
{ CKA_LABEL, NULL, 0 },
{ CKA_SUBJECT, NULL, 0 }
};
CK_ULONG pubCopyTemplateCount =
sizeof(pubCopyTemplate) / sizeof(pubCopyTemplate[0]);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
/* check to see if the key is already in the target slot */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot, pubTemplate,
pubTemplateCount, id, &targetKeyID);
if (rv != SECSuccess) {
goto done;
}
/* Key is already in the target slot */
if (targetKeyID != CK_INVALID_HANDLE) {
/* not an error ... */
goto done;
}
/* fetch an NSS representation of the public key */
sourceKey = PK11_ExtractPublicKey(sourceSlot, nullKey, id);
if (sourceKey == NULL) {
rv = SECFailure;
goto done;
}
/* load the public key into the target token. */
targetKeyID = PK11_ImportPublicKey(targetSlot, sourceKey, PR_TRUE);
if (targetKeyID == CK_INVALID_HANDLE) {
rv = SECFailure;
goto done;
}
/* fill in remaining attributes */
rv = pk11_copyAttributes(arena, targetSlot, targetKeyID, sourceSlot, id,
pubCopyTemplate, pubCopyTemplateCount);
done:
if (sourceKey) {
SECKEY_DestroyPublicKey(sourceKey);
}
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return rv;
}
/*************************************************************************
*
* Certificates
*
*************************************************************************/
/*
* Two copies of the source code for this algorithm exist in NSS.
* Changes must be made in both copies.
* The other copy is in sftkdb_resolveConflicts() in softoken/sftkdb.c.
*/
static char *
pk11_IncrementNickname(char *nickname)
{
char *newNickname = NULL;
int end;
int digit;
int len = strlen(nickname);
/* does nickname end with " #n*" ? */
for (end = len - 1;
end >= 2 && (digit = nickname[end]) <= '9' && digit >= '0';
end--) /* just scan */
;
if (len >= 3 &&
end < (len - 1) /* at least one digit */ &&
nickname[end] == '#' &&
nickname[end - 1] == ' ') {
/* Already has a suitable suffix string */
} else {
/* ... append " #2" to the name */
static const char num2[] = " #2";
newNickname = PORT_Realloc(nickname, len + sizeof(num2));
if (newNickname) {
PORT_Strcat(newNickname, num2);
} else {
PORT_Free(nickname);
}
return newNickname;
}
for (end = len - 1;
end >= 0 && (digit = nickname[end]) <= '9' && digit >= '0';
end--) {
if (digit < '9') {
nickname[end]++;
return nickname;
}
nickname[end] = '0';
}
/* we overflowed, insert a new '1' for a carry in front of the number */
newNickname = PORT_Realloc(nickname, len + 2);
if (newNickname) {
newNickname[++end] = '1';
PORT_Memset(&newNickname[end + 1], '0', len - end);
newNickname[len + 1] = 0;
} else {
PORT_Free(nickname);
}
return newNickname;
}
/*
* merge a certificate object
*
* Use the high level NSS calls to extract and import the certificate.
*/
static SECStatus
pk11_mergeCert(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
CERTCertificate *sourceCert = NULL;
CK_OBJECT_HANDLE targetCertID = CK_INVALID_HANDLE;
char *nickname = NULL;
SECStatus rv = SECSuccess;
PLArenaPool *arena = NULL;
CK_ATTRIBUTE sourceCKAID = { CKA_ID, NULL, 0 };
CK_ATTRIBUTE targetCKAID = { CKA_ID, NULL, 0 };
SECStatus lrv = SECSuccess;
int error = SEC_ERROR_LIBRARY_FAILURE;
sourceCert = PK11_MakeCertFromHandle(sourceSlot, id, NULL);
if (sourceCert == NULL) {
rv = SECFailure;
goto done;
}
nickname = PK11_GetObjectNickname(sourceSlot, id);
/* The database code will prevent nickname collisions for certs with
* different subjects. This code will prevent us from getting
* actual import errors */
if (nickname) {
const char *tokenName = PK11_GetTokenName(targetSlot);
char *tokenNickname = NULL;
do {
tokenNickname = PR_smprintf("%s:%s", tokenName, nickname);
if (!tokenNickname) {
break;
}
if (!SEC_CertNicknameConflict(tokenNickname,
&sourceCert->derSubject, CERT_GetDefaultCertDB())) {
break;
}
nickname = pk11_IncrementNickname(nickname);
if (!nickname) {
break;
}
PR_smprintf_free(tokenNickname);
} while (1);
if (tokenNickname) {
PR_smprintf_free(tokenNickname);
}
}
/* see if the cert is already there */
targetCertID = PK11_FindCertInSlot(targetSlot, sourceCert, targetPwArg);
if (targetCertID == CK_INVALID_HANDLE) {
/* cert doesn't exist load the cert in. */
/* OK for the nickname to be NULL, not all certs have nicknames */
rv = PK11_ImportCert(targetSlot, sourceCert, CK_INVALID_HANDLE,
nickname, PR_FALSE);
goto done;
}
/* the cert already exists, see if the nickname and/or CKA_ID need
* to be updated */
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
/* does our source have a CKA_ID ? */
rv = PK11_GetAttributes(arena, sourceSlot, id, &sourceCKAID, 1);
if (rv != SECSuccess) {
sourceCKAID.ulValueLen = 0;
}
/* if we have a source CKA_ID, see of we need to update the
* target's CKA_ID */
if (sourceCKAID.ulValueLen != 0) {
rv = PK11_GetAttributes(arena, targetSlot, targetCertID,
&targetCKAID, 1);
if (rv != SECSuccess) {
targetCKAID.ulValueLen = 0;
}
/* if the target has no CKA_ID, update it from the source */
if (targetCKAID.ulValueLen == 0) {
lrv = pk11_setAttributes(targetSlot, targetCertID, &sourceCKAID, 1);
if (lrv != SECSuccess) {
error = PORT_GetError();
}
}
}
rv = SECSuccess;
/* now check if we need to update the nickname */
if (nickname && *nickname) {
char *targetname;
targetname = PK11_GetObjectNickname(targetSlot, targetCertID);
if (!targetname || !*targetname) {
/* target has no nickname, or it's empty, update it */
rv = PK11_SetObjectNickname(targetSlot, targetCertID, nickname);
}
if (targetname) {
PORT_Free(targetname);
}
}
/* restore the error code if CKA_ID failed, but nickname didn't */
if ((rv == SECSuccess) && (lrv != SECSuccess)) {
rv = lrv;
PORT_SetError(error);
}
done:
if (nickname) {
PORT_Free(nickname);
}
if (sourceCert) {
CERT_DestroyCertificate(sourceCert);
}
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return rv;
}
/*************************************************************************
*
* Crls
*
*************************************************************************/
/*
* Use the raw PKCS #11 interface to merge the CRLs.
*
* In the case where of collision, choose the newest CRL that is valid.
*/
static SECStatus
pk11_mergeCrl(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
CK_OBJECT_HANDLE targetCrlID;
PLArenaPool *arena = NULL;
SECStatus rv = SECSuccess;
CK_ATTRIBUTE crlTemplate[] = {
{ CKA_SUBJECT, NULL, 0 },
{ CKA_CLASS, NULL, 0 },
{ CKA_NSS_KRL, NULL, 0 }
};
CK_ULONG crlTemplateCount = sizeof(crlTemplate) / sizeof(crlTemplate[0]);
CK_ATTRIBUTE crlCopyTemplate[] = {
{ CKA_CLASS, NULL, 0 },
{ CKA_TOKEN, NULL, 0 },
{ CKA_LABEL, NULL, 0 },
{ CKA_PRIVATE, NULL, 0 },
{ CKA_MODIFIABLE, NULL, 0 },
{ CKA_SUBJECT, NULL, 0 },
{ CKA_NSS_KRL, NULL, 0 },
{ CKA_NSS_URL, NULL, 0 },
{ CKA_VALUE, NULL, 0 }
};
CK_ULONG crlCopyTemplateCount =
sizeof(crlCopyTemplate) / sizeof(crlCopyTemplate[0]);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
/* check to see if the crl is already in the target slot */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot, crlTemplate,
crlTemplateCount, id, &targetCrlID);
if (rv != SECSuccess) {
goto done;
}
if (targetCrlID != CK_INVALID_HANDLE) {
/* we already have a CRL, check to see which is more up-to-date. */
goto done;
}
/* load the CRL into the target token. */
rv = pk11_copyAttributes(arena, targetSlot, targetCrlID, sourceSlot, id,
crlCopyTemplate, crlCopyTemplateCount);
done:
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return rv;
}
/*************************************************************************
*
* SMIME objects
*
*************************************************************************/
/*
* use the raw PKCS #11 interface to merge the S/MIME records
*/
static SECStatus
pk11_mergeSmime(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
CK_OBJECT_HANDLE id, void *targetPwArg, void *sourcePwArg)
{
CK_OBJECT_HANDLE targetSmimeID;
PLArenaPool *arena = NULL;
SECStatus rv = SECSuccess;
CK_ATTRIBUTE smimeTemplate[] = {
{ CKA_SUBJECT, NULL, 0 },
{ CKA_NSS_EMAIL, NULL, 0 },
{ CKA_CLASS, NULL, 0 },
};
CK_ULONG smimeTemplateCount =
sizeof(smimeTemplate) / sizeof(smimeTemplate[0]);
CK_ATTRIBUTE smimeCopyTemplate[] = {
{ CKA_CLASS, NULL, 0 },
{ CKA_TOKEN, NULL, 0 },
{ CKA_LABEL, NULL, 0 },
{ CKA_PRIVATE, NULL, 0 },
{ CKA_MODIFIABLE, NULL, 0 },
{ CKA_SUBJECT, NULL, 0 },
{ CKA_NSS_EMAIL, NULL, 0 },
{ CKA_NSS_SMIME_TIMESTAMP, NULL, 0 },
{ CKA_VALUE, NULL, 0 }
};
CK_ULONG smimeCopyTemplateCount =
sizeof(smimeCopyTemplate) / sizeof(smimeCopyTemplate[0]);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
rv = SECFailure;
goto done;
}
/* check to see if the crl is already in the target slot */
rv = pk11_matchAcrossTokens(arena, targetSlot, sourceSlot, smimeTemplate,
smimeTemplateCount, id, &targetSmimeID);
if (rv != SECSuccess) {
goto done;
}
if (targetSmimeID != CK_INVALID_HANDLE) {
/* we already have a SMIME record */