/
sftkpwd.c
1209 lines (1088 loc) · 35.4 KB
/
sftkpwd.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/. */
/*
* The following code handles the storage of PKCS 11 modules used by the
* NSS. For the rest of NSS, only one kind of database handle exists:
*
* SFTKDBHandle
*
* There is one SFTKDBHandle for the each key database and one for each cert
* database. These databases are opened as associated pairs, one pair per
* slot. SFTKDBHandles are reference counted objects.
*
* Each SFTKDBHandle points to a low level database handle (SDB). This handle
* represents the underlying physical database. These objects are not
* reference counted, an are 'owned' by their respective SFTKDBHandles.
*
*
*/
#include "sftkdb.h"
#include "sftkdbti.h"
#include "pkcs11t.h"
#include "pkcs11i.h"
#include "sdb.h"
#include "prprf.h"
#include "secasn1.h"
#include "pratom.h"
#include "blapi.h"
#include "secoid.h"
#include "lowpbe.h"
#include "secdert.h"
#include "prsystem.h"
#include "lgglue.h"
#include "secerr.h"
#include "softoken.h"
/******************************************************************
*
* Key DB password handling functions
*
* These functions manage the key db password (set, reset, initialize, use).
*
* The key is managed on 'this side' of the database. All private data is
* encrypted before it is sent to the database itself. Besides PBE's, the
* database management code can also mix in various fixed keys so the data
* in the database is no longer considered 'plain text'.
*/
/* take string password and turn it into a key. The key is dependent
* on a global salt entry acquired from the database. This salted
* value will be based to a pkcs5 pbe function before it is used
* in an actual encryption */
static SECStatus
sftkdb_passwordToKey(SFTKDBHandle *keydb, SECItem *salt,
const char *pw, SECItem *key)
{
SHA1Context *cx = NULL;
SECStatus rv = SECFailure;
key->data = PORT_Alloc(SHA1_LENGTH);
if (key->data == NULL) {
goto loser;
}
key->len = SHA1_LENGTH;
cx = SHA1_NewContext();
if (cx == NULL) {
goto loser;
}
SHA1_Begin(cx);
if (salt && salt->data) {
SHA1_Update(cx, salt->data, salt->len);
}
SHA1_Update(cx, (unsigned char *)pw, PORT_Strlen(pw));
SHA1_End(cx, key->data, &key->len, key->len);
rv = SECSuccess;
loser:
if (cx) {
SHA1_DestroyContext(cx, PR_TRUE);
}
if (rv != SECSuccess) {
if (key->data != NULL) {
PORT_ZFree(key->data, key->len);
}
key->data = NULL;
}
return rv;
}
/*
* Cipher text stored in the database contains 3 elements:
* 1) an identifier describing the encryption algorithm.
* 2) an entry specific salt value.
* 3) the encrypted value.
*
* The following data structure represents the encrypted data in a decoded
* (but still encrypted) form.
*/
typedef struct sftkCipherValueStr sftkCipherValue;
struct sftkCipherValueStr {
PLArenaPool *arena;
SECOidTag alg;
NSSPKCS5PBEParameter *param;
SECItem salt;
SECItem value;
};
#define SFTK_CIPHERTEXT_VERSION 3
struct SFTKDBEncryptedDataInfoStr {
SECAlgorithmID algorithm;
SECItem encryptedData;
};
typedef struct SFTKDBEncryptedDataInfoStr SFTKDBEncryptedDataInfo;
SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
const SEC_ASN1Template sftkdb_EncryptedDataInfoTemplate[] = {
{ SEC_ASN1_SEQUENCE,
0, NULL, sizeof(SFTKDBEncryptedDataInfo) },
{ SEC_ASN1_INLINE | SEC_ASN1_XTRN,
offsetof(SFTKDBEncryptedDataInfo, algorithm),
SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
{ SEC_ASN1_OCTET_STRING,
offsetof(SFTKDBEncryptedDataInfo, encryptedData) },
{ 0 }
};
/*
* This parses the cipherText into cipher value. NOTE: cipherValue will point
* to data in cipherText, if cipherText is freed, cipherValue will be invalid.
*/
static SECStatus
sftkdb_decodeCipherText(SECItem *cipherText, sftkCipherValue *cipherValue)
{
PLArenaPool *arena = NULL;
SFTKDBEncryptedDataInfo edi;
SECStatus rv;
PORT_Assert(cipherValue);
cipherValue->arena = NULL;
cipherValue->param = NULL;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
return SECFailure;
}
rv = SEC_QuickDERDecodeItem(arena, &edi, sftkdb_EncryptedDataInfoTemplate,
cipherText);
if (rv != SECSuccess) {
goto loser;
}
cipherValue->alg = SECOID_GetAlgorithmTag(&edi.algorithm);
cipherValue->param = nsspkcs5_AlgidToParam(&edi.algorithm);
if (cipherValue->param == NULL) {
goto loser;
}
cipherValue->value = edi.encryptedData;
cipherValue->arena = arena;
return SECSuccess;
loser:
if (cipherValue->param) {
nsspkcs5_DestroyPBEParameter(cipherValue->param);
cipherValue->param = NULL;
}
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
return SECFailure;
}
/*
* unlike decode, Encode actually allocates a SECItem the caller must free
* The caller can pass an optional arena to to indicate where to place
* the resultant cipherText.
*/
static SECStatus
sftkdb_encodeCipherText(PLArenaPool *arena, sftkCipherValue *cipherValue,
SECItem **cipherText)
{
SFTKDBEncryptedDataInfo edi;
SECAlgorithmID *algid;
SECStatus rv;
PLArenaPool *localArena = NULL;
localArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (localArena == NULL) {
return SECFailure;
}
algid = nsspkcs5_CreateAlgorithmID(localArena, cipherValue->alg,
cipherValue->param);
if (algid == NULL) {
rv = SECFailure;
goto loser;
}
rv = SECOID_CopyAlgorithmID(localArena, &edi.algorithm, algid);
SECOID_DestroyAlgorithmID(algid, PR_TRUE);
if (rv != SECSuccess) {
goto loser;
}
edi.encryptedData = cipherValue->value;
*cipherText = SEC_ASN1EncodeItem(arena, NULL, &edi,
sftkdb_EncryptedDataInfoTemplate);
if (*cipherText == NULL) {
rv = SECFailure;
}
loser:
if (localArena) {
PORT_FreeArena(localArena, PR_FALSE);
}
return rv;
}
/*
* Use our key to decode a cipherText block from the database.
*
* plain text is allocated by nsspkcs5_CipherData and must be freed
* with SECITEM_FreeItem by the caller.
*/
SECStatus
sftkdb_DecryptAttribute(SECItem *passKey, SECItem *cipherText, SECItem **plain)
{
SECStatus rv;
sftkCipherValue cipherValue;
/* First get the cipher type */
rv = sftkdb_decodeCipherText(cipherText, &cipherValue);
if (rv != SECSuccess) {
goto loser;
}
*plain = nsspkcs5_CipherData(cipherValue.param, passKey, &cipherValue.value,
PR_FALSE, NULL);
if (*plain == NULL) {
rv = SECFailure;
goto loser;
}
loser:
if (cipherValue.param) {
nsspkcs5_DestroyPBEParameter(cipherValue.param);
}
if (cipherValue.arena) {
PORT_FreeArena(cipherValue.arena, PR_FALSE);
}
return rv;
}
/*
* encrypt a block. This function returned the encrypted ciphertext which
* the caller must free. If the caller provides an arena, cipherText will
* be allocated out of that arena. This also generated the per entry
* salt automatically.
*/
SECStatus
sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey,
SECItem *plainText, SECItem **cipherText)
{
SECStatus rv;
sftkCipherValue cipherValue;
SECItem *cipher = NULL;
NSSPKCS5PBEParameter *param = NULL;
unsigned char saltData[HASH_LENGTH_MAX];
cipherValue.alg = SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC;
cipherValue.salt.len = SHA1_LENGTH;
cipherValue.salt.data = saltData;
RNG_GenerateGlobalRandomBytes(saltData, cipherValue.salt.len);
param = nsspkcs5_NewParam(cipherValue.alg, HASH_AlgSHA1, &cipherValue.salt,
1);
if (param == NULL) {
rv = SECFailure;
goto loser;
}
cipher = nsspkcs5_CipherData(param, passKey, plainText, PR_TRUE, NULL);
if (cipher == NULL) {
rv = SECFailure;
goto loser;
}
cipherValue.value = *cipher;
cipherValue.param = param;
rv = sftkdb_encodeCipherText(arena, &cipherValue, cipherText);
if (rv != SECSuccess) {
goto loser;
}
loser:
if (cipher) {
SECITEM_FreeItem(cipher, PR_TRUE);
}
if (param) {
nsspkcs5_DestroyPBEParameter(param);
}
return rv;
}
/*
* use the password and the pbe parameters to generate an HMAC for the
* given plain text data. This is used by sftkdb_VerifyAttribute and
* sftkdb_SignAttribute. Signature is returned in signData. The caller
* must preallocate the space in the secitem.
*/
static SECStatus
sftkdb_pbehash(SECOidTag sigOid, SECItem *passKey,
NSSPKCS5PBEParameter *param,
CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType,
SECItem *plainText, SECItem *signData)
{
SECStatus rv = SECFailure;
SECItem *key = NULL;
HMACContext *hashCx = NULL;
HASH_HashType hashType = HASH_AlgNULL;
const SECHashObject *hashObj;
unsigned char addressData[SDB_ULONG_SIZE];
hashType = HASH_FromHMACOid(param->encAlg);
if (hashType == HASH_AlgNULL) {
PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
return SECFailure;
}
hashObj = HASH_GetRawHashObject(hashType);
if (hashObj == NULL) {
goto loser;
}
key = nsspkcs5_ComputeKeyAndIV(param, passKey, NULL, PR_FALSE);
if (!key) {
goto loser;
}
hashCx = HMAC_Create(hashObj, key->data, key->len, PR_TRUE);
if (!hashCx) {
goto loser;
}
HMAC_Begin(hashCx);
/* Tie this value to a particular object. This is most important for
* the trust attributes, where and attacker could copy a value for
* 'validCA' from another cert in the database */
sftk_ULong2SDBULong(addressData, objectID);
HMAC_Update(hashCx, addressData, SDB_ULONG_SIZE);
sftk_ULong2SDBULong(addressData, attrType);
HMAC_Update(hashCx, addressData, SDB_ULONG_SIZE);
HMAC_Update(hashCx, plainText->data, plainText->len);
rv = HMAC_Finish(hashCx, signData->data, &signData->len, signData->len);
loser:
if (hashCx) {
HMAC_Destroy(hashCx, PR_TRUE);
}
if (key) {
SECITEM_FreeItem(key, PR_TRUE);
}
return rv;
}
/*
* Use our key to verify a signText block from the database matches
* the plainText from the database. The signText is a PKCS 5 v2 pbe.
* plainText is the plainText of the attribute.
*/
SECStatus
sftkdb_VerifyAttribute(SECItem *passKey, CK_OBJECT_HANDLE objectID,
CK_ATTRIBUTE_TYPE attrType,
SECItem *plainText, SECItem *signText)
{
SECStatus rv;
sftkCipherValue signValue;
SECItem signature;
unsigned char signData[HASH_LENGTH_MAX];
/* First get the cipher type */
rv = sftkdb_decodeCipherText(signText, &signValue);
if (rv != SECSuccess) {
goto loser;
}
signature.data = signData;
signature.len = sizeof(signData);
rv = sftkdb_pbehash(signValue.alg, passKey, signValue.param,
objectID, attrType, plainText, &signature);
if (rv != SECSuccess) {
goto loser;
}
if (SECITEM_CompareItem(&signValue.value, &signature) != 0) {
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
rv = SECFailure;
}
loser:
if (signValue.param) {
nsspkcs5_DestroyPBEParameter(signValue.param);
}
if (signValue.arena) {
PORT_FreeArena(signValue.arena, PR_FALSE);
}
return rv;
}
/*
* Use our key to create a signText block the plain text of an
* attribute. The signText is a PKCS 5 v2 pbe.
*/
SECStatus
sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey,
CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType,
SECItem *plainText, SECItem **signature)
{
SECStatus rv;
sftkCipherValue signValue;
NSSPKCS5PBEParameter *param = NULL;
unsigned char saltData[HASH_LENGTH_MAX];
unsigned char signData[HASH_LENGTH_MAX];
SECOidTag hmacAlg = SEC_OID_HMAC_SHA256; /* hash for authentication */
SECOidTag prfAlg = SEC_OID_HMAC_SHA256; /* hash for pb key generation */
HASH_HashType prfType;
unsigned int hmacLength;
unsigned int prfLength;
/* this code allows us to fetch the lengths and hashes on the fly
* by simply changing the OID above */
prfType = HASH_FromHMACOid(prfAlg);
PORT_Assert(prfType != HASH_AlgNULL);
prfLength = HASH_GetRawHashObject(prfType)->length;
PORT_Assert(prfLength <= HASH_LENGTH_MAX);
hmacLength = HASH_GetRawHashObject(HASH_FromHMACOid(hmacAlg))->length;
PORT_Assert(hmacLength <= HASH_LENGTH_MAX);
/* initialize our CipherValue structure */
signValue.alg = SEC_OID_PKCS5_PBMAC1;
signValue.salt.len = prfLength;
signValue.salt.data = saltData;
signValue.value.data = signData;
signValue.value.len = hmacLength;
RNG_GenerateGlobalRandomBytes(saltData, prfLength);
/* initialize our pkcs5 parameter */
param = nsspkcs5_NewParam(signValue.alg, HASH_AlgSHA1, &signValue.salt, 1);
if (param == NULL) {
rv = SECFailure;
goto loser;
}
param->keyID = pbeBitGenIntegrityKey;
/* set the PKCS 5 v2 parameters, not extractable from the
* data passed into nsspkcs5_NewParam */
param->encAlg = hmacAlg;
param->hashType = prfType;
param->keyLen = hmacLength;
rv = SECOID_SetAlgorithmID(param->poolp, ¶m->prfAlg, prfAlg, NULL);
if (rv != SECSuccess) {
goto loser;
}
/* calculate the mac */
rv = sftkdb_pbehash(signValue.alg, passKey, param, objectID, attrType,
plainText, &signValue.value);
if (rv != SECSuccess) {
goto loser;
}
signValue.param = param;
/* write it out */
rv = sftkdb_encodeCipherText(arena, &signValue, signature);
if (rv != SECSuccess) {
goto loser;
}
loser:
if (param) {
nsspkcs5_DestroyPBEParameter(param);
}
return rv;
}
/*
* safely swith the passed in key for the one caches in the keydb handle
*
* A key attached to the handle tells us the the token is logged in.
* We can used the key attached to the handle in sftkdb_EncryptAttribute
* and sftkdb_DecryptAttribute calls.
*/
static void
sftkdb_switchKeys(SFTKDBHandle *keydb, SECItem *passKey)
{
unsigned char *data;
int len;
if (keydb->passwordLock == NULL) {
PORT_Assert(keydb->type != SFTK_KEYDB_TYPE);
return;
}
/* an atomic pointer set would be nice */
SKIP_AFTER_FORK(PZ_Lock(keydb->passwordLock));
data = keydb->passwordKey.data;
len = keydb->passwordKey.len;
keydb->passwordKey.data = passKey->data;
keydb->passwordKey.len = passKey->len;
passKey->data = data;
passKey->len = len;
SKIP_AFTER_FORK(PZ_Unlock(keydb->passwordLock));
}
/*
* returns true if we are in a middle of a merge style update.
*/
PRBool
sftkdb_InUpdateMerge(SFTKDBHandle *keydb)
{
return keydb->updateID ? PR_TRUE : PR_FALSE;
}
/*
* returns true if we are looking for the password for the user's old source
* database as part of a merge style update.
*/
PRBool
sftkdb_NeedUpdateDBPassword(SFTKDBHandle *keydb)
{
if (!sftkdb_InUpdateMerge(keydb)) {
return PR_FALSE;
}
if (keydb->updateDBIsInit && !keydb->updatePasswordKey) {
return PR_TRUE;
}
return PR_FALSE;
}
/*
* fetch an update password key from a handle.
*/
SECItem *
sftkdb_GetUpdatePasswordKey(SFTKDBHandle *handle)
{
SECItem *key = NULL;
/* if we're a cert db, fetch it from our peer key db */
if (handle->type == SFTK_CERTDB_TYPE) {
handle = handle->peerDB;
}
/* don't have one */
if (!handle) {
return NULL;
}
PZ_Lock(handle->passwordLock);
if (handle->updatePasswordKey) {
key = SECITEM_DupItem(handle->updatePasswordKey);
}
PZ_Unlock(handle->passwordLock);
return key;
}
/*
* free the update password key from a handle.
*/
void
sftkdb_FreeUpdatePasswordKey(SFTKDBHandle *handle)
{
SECItem *key = NULL;
/* don't have one */
if (!handle) {
return;
}
/* if we're a cert db, we don't have one */
if (handle->type == SFTK_CERTDB_TYPE) {
return;
}
PZ_Lock(handle->passwordLock);
if (handle->updatePasswordKey) {
key = handle->updatePasswordKey;
handle->updatePasswordKey = NULL;
}
PZ_Unlock(handle->passwordLock);
if (key) {
SECITEM_ZfreeItem(key, PR_TRUE);
}
return;
}
/*
* what password db we use depends heavily on the update state machine
*
* 1) no update db, return the normal database.
* 2) update db and no merge return the update db.
* 3) update db and in merge:
* return the update db if we need the update db's password,
* otherwise return our normal datbase.
*/
static SDB *
sftk_getPWSDB(SFTKDBHandle *keydb)
{
if (!keydb->update) {
return keydb->db;
}
if (!sftkdb_InUpdateMerge(keydb)) {
return keydb->update;
}
if (sftkdb_NeedUpdateDBPassword(keydb)) {
return keydb->update;
}
return keydb->db;
}
/*
* return success if we have a valid password entry.
* This is will show up outside of PKCS #11 as CKF_USER_PIN_INIT
* in the token flags.
*/
SECStatus
sftkdb_HasPasswordSet(SFTKDBHandle *keydb)
{
SECItem salt, value;
unsigned char saltData[SDB_MAX_META_DATA_LEN];
unsigned char valueData[SDB_MAX_META_DATA_LEN];
CK_RV crv;
SDB *db;
if (keydb == NULL) {
return SECFailure;
}
db = sftk_getPWSDB(keydb);
if (db == NULL) {
return SECFailure;
}
salt.data = saltData;
salt.len = sizeof(saltData);
value.data = valueData;
value.len = sizeof(valueData);
crv = (*db->sdb_GetMetaData)(db, "password", &salt, &value);
/* If no password is set, we can update right away */
if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update && crv != CKR_OK) {
/* update the peer certdb if it exists */
if (keydb->peerDB) {
sftkdb_Update(keydb->peerDB, NULL);
}
sftkdb_Update(keydb, NULL);
}
return (crv == CKR_OK) ? SECSuccess : SECFailure;
}
#define SFTK_PW_CHECK_STRING "password-check"
#define SFTK_PW_CHECK_LEN 14
/*
* check if the supplied password is valid
*/
SECStatus
sftkdb_CheckPassword(SFTKDBHandle *keydb, const char *pw, PRBool *tokenRemoved)
{
SECStatus rv;
SECItem salt, value;
unsigned char saltData[SDB_MAX_META_DATA_LEN];
unsigned char valueData[SDB_MAX_META_DATA_LEN];
SECItem key;
SECItem *result = NULL;
SDB *db;
CK_RV crv;
if (keydb == NULL) {
return SECFailure;
}
db = sftk_getPWSDB(keydb);
if (db == NULL) {
return SECFailure;
}
key.data = NULL;
key.len = 0;
if (pw == NULL)
pw = "";
/* get the entry from the database */
salt.data = saltData;
salt.len = sizeof(saltData);
value.data = valueData;
value.len = sizeof(valueData);
crv = (*db->sdb_GetMetaData)(db, "password", &salt, &value);
if (crv != CKR_OK) {
rv = SECFailure;
goto done;
}
/* get our intermediate key based on the entry salt value */
rv = sftkdb_passwordToKey(keydb, &salt, pw, &key);
if (rv != SECSuccess) {
goto done;
}
/* decrypt the entry value */
rv = sftkdb_DecryptAttribute(&key, &value, &result);
if (rv != SECSuccess) {
goto done;
}
/* if it's what we expect, update our key in the database handle and
* return Success */
if ((result->len == SFTK_PW_CHECK_LEN) &&
PORT_Memcmp(result->data, SFTK_PW_CHECK_STRING, SFTK_PW_CHECK_LEN) == 0) {
/*
* We have a password, now lets handle any potential update cases..
*
* First, the normal case: no update. In this case we only need the
* the password for our only DB, which we now have, we switch
* the keys and fall through.
* Second regular (non-merge) update: The target DB does not yet have
* a password initialized, we now have the password for the source DB,
* so we can switch the keys and simply update the target database.
* Merge update case: This one is trickier.
* 1) If we need the source DB password, then we just got it here.
* We need to save that password,
* then we need to check to see if we need or have the target
* database password.
* If we have it (it's the same as the source), or don't need
* it (it's not set or is ""), we can start the update now.
* If we don't have it, we need the application to get it from
* the user. Clear our sessions out to simulate a token
* removal. C_GetTokenInfo will change the token description
* and the token will still appear to be logged out.
* 2) If we already have the source DB password, this password is
* for the target database. We can now move forward with the
* update, as we now have both required passwords.
*
*/
PZ_Lock(keydb->passwordLock);
if (sftkdb_NeedUpdateDBPassword(keydb)) {
/* Squirrel this special key away.
* This has the side effect of turning sftkdb_NeedLegacyPW off,
* as well as changing which database is returned from
* SFTK_GET_PW_DB (thus effecting both sftkdb_CheckPassword()
* and sftkdb_HasPasswordSet()) */
keydb->updatePasswordKey = SECITEM_DupItem(&key);
PZ_Unlock(keydb->passwordLock);
if (keydb->updatePasswordKey == NULL) {
/* PORT_Error set by SECITEM_DupItem */
rv = SECFailure;
goto done;
}
/* Simulate a token removal -- we need to do this any
* any case at this point so the token name is correct. */
*tokenRemoved = PR_TRUE;
/*
* OK, we got the update DB password, see if we need a password
* for the target...
*/
if (sftkdb_HasPasswordSet(keydb) == SECSuccess) {
/* We have a password, do we know what the password is?
* check 1) for the password the user supplied for the
* update DB,
* and 2) for the null password.
*
* RECURSION NOTE: we are calling ourselves here. This means
* any updates, switchKeys, etc will have been completed
* if these functions return successfully, in those cases
* just exit returning Success. We don't recurse infinitely
* because we are making this call from a NeedUpdateDBPassword
* block and we've already set that update password at this
* point. */
rv = sftkdb_CheckPassword(keydb, pw, tokenRemoved);
if (rv == SECSuccess) {
/* source and target databases have the same password, we
* are good to go */
goto done;
}
sftkdb_CheckPassword(keydb, "", tokenRemoved);
/*
* Important 'NULL' code here. At this point either we
* succeeded in logging in with "" or we didn't.
*
* If we did succeed at login, our machine state will be set
* to logged in appropriately. The application will find that
* it's logged in as soon as it opens a new session. We have
* also completed the update. Life is good.
*
* If we did not succeed, well the user still successfully
* logged into the update database, since we faked the token
* removal it's just like the user logged into his smart card
* then removed it. the actual login work, so we report that
* success back to the user, but we won't actually be
* logged in. The application will find this out when it
* checks it's login state, thus triggering another password
* prompt so we can get the real target DB password.
*
* summary, we exit from here with SECSuccess no matter what.
*/
rv = SECSuccess;
goto done;
} else {
/* there is no password, just fall through to update.
* update will write the source DB's password record
* into the target DB just like it would in a non-merge
* update case. */
}
} else {
PZ_Unlock(keydb->passwordLock);
}
/* load the keys, so the keydb can parse it's key set */
sftkdb_switchKeys(keydb, &key);
/* we need to update, do it now */
if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update) {
/* update the peer certdb if it exists */
if (keydb->peerDB) {
sftkdb_Update(keydb->peerDB, &key);
}
sftkdb_Update(keydb, &key);
}
} else {
rv = SECFailure;
/*PORT_SetError( bad password); */
}
done:
if (key.data) {
PORT_ZFree(key.data, key.len);
}
if (result) {
SECITEM_FreeItem(result, PR_TRUE);
}
return rv;
}
/*
* return Success if the there is a cached password key.
*/
SECStatus
sftkdb_PWCached(SFTKDBHandle *keydb)
{
return keydb->passwordKey.data ? SECSuccess : SECFailure;
}
static CK_RV
sftk_updateMacs(PLArenaPool *arena, SFTKDBHandle *handle,
CK_OBJECT_HANDLE id, SECItem *newKey)
{
SFTKDBHandle *keyHandle = handle;
SDB *keyTarget = NULL;
if (handle->type != SFTK_KEYDB_TYPE) {
keyHandle = handle->peerDB;
}
if (keyHandle == NULL) {
return CKR_OK;
}
// Old DBs don't have metadata, so we can return early here.
keyTarget = SFTK_GET_SDB(keyHandle);
if ((keyTarget->sdb_flags & SDB_HAS_META) == 0) {
return CKR_OK;
}
id &= SFTK_OBJ_ID_MASK;
CK_ATTRIBUTE_TYPE authAttrTypes[] = {
CKA_MODULUS,
CKA_PUBLIC_EXPONENT,
CKA_CERT_SHA1_HASH,
CKA_CERT_MD5_HASH,
CKA_TRUST_SERVER_AUTH,
CKA_TRUST_CLIENT_AUTH,
CKA_TRUST_EMAIL_PROTECTION,
CKA_TRUST_CODE_SIGNING,
CKA_TRUST_STEP_UP_APPROVED,
CKA_NSS_OVERRIDE_EXTENSIONS,
};
const CK_ULONG authAttrTypeCount = sizeof(authAttrTypes) / sizeof(authAttrTypes[0]);
// We don't know what attributes this object has, so we update them one at a
// time.
unsigned int i;
for (i = 0; i < authAttrTypeCount; i++) {
CK_ATTRIBUTE authAttr = { authAttrTypes[i], NULL, 0 };
CK_RV rv = sftkdb_GetAttributeValue(handle, id, &authAttr, 1);
if (rv != CKR_OK) {
continue;
}
if ((authAttr.ulValueLen == -1) || (authAttr.ulValueLen == 0)) {
continue;
}
authAttr.pValue = PORT_ArenaAlloc(arena, authAttr.ulValueLen);
if (authAttr.pValue == NULL) {
return CKR_HOST_MEMORY;
}
rv = sftkdb_GetAttributeValue(handle, id, &authAttr, 1);
if (rv != CKR_OK) {
return rv;
}
if ((authAttr.ulValueLen == -1) || (authAttr.ulValueLen == 0)) {
return CKR_GENERAL_ERROR;
}
// GetAttributeValue just verified the old macs, so it is safe to write
// them out now.
if (authAttr.ulValueLen == sizeof(CK_ULONG) &&
sftkdb_isULONGAttribute(authAttr.type)) {
CK_ULONG value = *(CK_ULONG *)authAttr.pValue;
sftk_ULong2SDBULong(authAttr.pValue, value);
authAttr.ulValueLen = SDB_ULONG_SIZE;
}
SECItem *signText;
SECItem plainText;
plainText.data = authAttr.pValue;
plainText.len = authAttr.ulValueLen;
if (sftkdb_SignAttribute(arena, newKey, id, authAttr.type, &plainText,
&signText) != SECSuccess) {
return CKR_GENERAL_ERROR;
}
if (sftkdb_PutAttributeSignature(handle, keyTarget, id, authAttr.type,
signText) != SECSuccess) {
return CKR_GENERAL_ERROR;
}
}
return CKR_OK;
}
static CK_RV
sftk_updateEncrypted(PLArenaPool *arena, SFTKDBHandle *keydb,
CK_OBJECT_HANDLE id, SECItem *newKey)
{
CK_ATTRIBUTE_TYPE privAttrTypes[] = {
CKA_VALUE,
CKA_PRIVATE_EXPONENT,
CKA_PRIME_1,
CKA_PRIME_2,
CKA_EXPONENT_1,
CKA_EXPONENT_2,
CKA_COEFFICIENT,
};
const CK_ULONG privAttrCount = sizeof(privAttrTypes) / sizeof(privAttrTypes[0]);
// We don't know what attributes this object has, so we update them one at a
// time.
unsigned int i;
for (i = 0; i < privAttrCount; i++) {
// Read the old attribute in the clear.
CK_ATTRIBUTE privAttr = { privAttrTypes[i], NULL, 0 };
CK_RV crv = sftkdb_GetAttributeValue(keydb, id, &privAttr, 1);
if (crv != CKR_OK) {
continue;
}
if ((privAttr.ulValueLen == -1) || (privAttr.ulValueLen == 0)) {
continue;
}
privAttr.pValue = PORT_ArenaAlloc(arena, privAttr.ulValueLen);
if (privAttr.pValue == NULL) {
return CKR_HOST_MEMORY;
}
crv = sftkdb_GetAttributeValue(keydb, id, &privAttr, 1);
if (crv != CKR_OK) {
return crv;
}
if ((privAttr.ulValueLen == -1) || (privAttr.ulValueLen == 0)) {
return CKR_GENERAL_ERROR;
}
SECItem plainText;
SECItem *result;
plainText.data = privAttr.pValue;
plainText.len = privAttr.ulValueLen;
if (sftkdb_EncryptAttribute(arena, newKey, &plainText, &result) != SECSuccess) {
return CKR_GENERAL_ERROR;
}
privAttr.pValue = result->data;
privAttr.ulValueLen = result->len;
// Clear sensitive data.
PORT_Memset(plainText.data, 0, plainText.len);
// Write the newly encrypted attributes out directly.
CK_OBJECT_HANDLE newId = id & SFTK_OBJ_ID_MASK;
keydb->newKey = newKey;
crv = (*keydb->db->sdb_SetAttributeValue)(keydb->db, newId, &privAttr, 1);
keydb->newKey = NULL;
if (crv != CKR_OK) {
return crv;
}
}