Coverage Report

Created: 2025-07-11 07:04

/src/nss/lib/softoken/sftkdb.c
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
/*
5
 *  The following code handles the storage of PKCS 11 modules used by the
6
 * NSS. For the rest of NSS, only one kind of database handle exists:
7
 *
8
 *     SFTKDBHandle
9
 *
10
 * There is one SFTKDBHandle for the each key database and one for each cert
11
 * database. These databases are opened as associated pairs, one pair per
12
 * slot. SFTKDBHandles are reference counted objects.
13
 *
14
 * Each SFTKDBHandle points to a low level database handle (SDB). This handle
15
 * represents the underlying physical database. These objects are not
16
 * reference counted, an are 'owned' by their respective SFTKDBHandles.
17
 *
18
 *
19
 */
20
#include "sftkdb.h"
21
#include "sftkdbti.h"
22
#include "pkcs11t.h"
23
#include "pkcs11i.h"
24
#include "sdb.h"
25
#include "prprf.h"
26
#include "pratom.h"
27
#include "lgglue.h"
28
#include "utilpars.h"
29
#include "secerr.h"
30
#include "softoken.h"
31
#if defined(_WIN32)
32
#include <windows.h>
33
#endif
34
35
/*
36
 * We want all databases to have the same binary representation independent of
37
 * endianness or length of the host architecture. In general PKCS #11 attributes
38
 * are endian/length independent except those attributes that pass CK_ULONG.
39
 *
40
 * The following functions fixes up the CK_ULONG type attributes so that the data
41
 * base sees a machine independent view. CK_ULONGs are stored as 4 byte network
42
 * byte order values (big endian).
43
 */
44
0
#define BBP 8
45
46
PRBool
47
sftkdb_isULONGAttribute(CK_ATTRIBUTE_TYPE type)
48
0
{
49
0
    switch (type) {
50
0
        case CKA_CERTIFICATE_CATEGORY:
51
0
        case CKA_CERTIFICATE_TYPE:
52
0
        case CKA_CLASS:
53
0
        case CKA_JAVA_MIDP_SECURITY_DOMAIN:
54
0
        case CKA_KEY_GEN_MECHANISM:
55
0
        case CKA_KEY_TYPE:
56
0
        case CKA_MECHANISM_TYPE:
57
0
        case CKA_MODULUS_BITS:
58
0
        case CKA_PRIME_BITS:
59
0
        case CKA_SUBPRIME_BITS:
60
0
        case CKA_VALUE_BITS:
61
0
        case CKA_VALUE_LEN:
62
63
0
        case CKA_PKCS_TRUST_SERVER_AUTH:
64
0
        case CKA_PKCS_TRUST_CLIENT_AUTH:
65
0
        case CKA_PKCS_TRUST_CODE_SIGNING:
66
0
        case CKA_PKCS_TRUST_EMAIL_PROTECTION:
67
0
        case CKA_TRUST_IPSEC_IKE:
68
0
        case CKA_PKCS_TRUST_TIME_STAMPING:
69
0
        case CKA_NAME_HASH_ALGORITHM:
70
71
0
        case CKA_NSS_TRUST_DIGITAL_SIGNATURE:
72
0
        case CKA_NSS_TRUST_NON_REPUDIATION:
73
0
        case CKA_NSS_TRUST_KEY_ENCIPHERMENT:
74
0
        case CKA_NSS_TRUST_DATA_ENCIPHERMENT:
75
0
        case CKA_NSS_TRUST_KEY_AGREEMENT:
76
0
        case CKA_NSS_TRUST_KEY_CERT_SIGN:
77
0
        case CKA_NSS_TRUST_CRL_SIGN:
78
79
0
        case CKA_NSS_TRUST_SERVER_AUTH:
80
0
        case CKA_NSS_TRUST_CLIENT_AUTH:
81
0
        case CKA_NSS_TRUST_CODE_SIGNING:
82
0
        case CKA_NSS_TRUST_EMAIL_PROTECTION:
83
0
        case CKA_NSS_TRUST_IPSEC_END_SYSTEM:
84
0
        case CKA_NSS_TRUST_IPSEC_TUNNEL:
85
0
        case CKA_NSS_TRUST_IPSEC_USER:
86
0
        case CKA_NSS_TRUST_TIME_STAMPING:
87
0
        case CKA_NSS_TRUST_STEP_UP_APPROVED:
88
0
            return PR_TRUE;
89
0
        default:
90
0
            break;
91
0
    }
92
0
    return PR_FALSE;
93
0
}
94
95
/* are the attributes private? */
96
static PRBool
97
sftkdb_isPrivateAttribute(CK_ATTRIBUTE_TYPE type)
98
0
{
99
0
    switch (type) {
100
0
        case CKA_VALUE:
101
0
        case CKA_PRIVATE_EXPONENT:
102
0
        case CKA_PRIME_1:
103
0
        case CKA_PRIME_2:
104
0
        case CKA_EXPONENT_1:
105
0
        case CKA_EXPONENT_2:
106
0
        case CKA_COEFFICIENT:
107
0
            return PR_TRUE;
108
0
        default:
109
0
            break;
110
0
    }
111
0
    return PR_FALSE;
112
0
}
113
114
/* These attributes must be authenticated with an hmac. */
115
static PRBool
116
sftkdb_isAuthenticatedAttribute(CK_ATTRIBUTE_TYPE type)
117
0
{
118
0
    switch (type) {
119
0
        case CKA_MODULUS:
120
0
        case CKA_PUBLIC_EXPONENT:
121
0
        case CKA_NSS_CERT_SHA1_HASH:
122
0
        case CKA_NSS_CERT_MD5_HASH:
123
0
        case CKA_NSS_TRUST_SERVER_AUTH:
124
0
        case CKA_NSS_TRUST_CLIENT_AUTH:
125
0
        case CKA_NSS_TRUST_EMAIL_PROTECTION:
126
0
        case CKA_NSS_TRUST_CODE_SIGNING:
127
0
        case CKA_NSS_TRUST_STEP_UP_APPROVED:
128
0
        case CKA_HASH_OF_CERTIFICATE:
129
0
        case CKA_NAME_HASH_ALGORITHM:
130
0
        case CKA_PKCS_TRUST_SERVER_AUTH:
131
0
        case CKA_PKCS_TRUST_CLIENT_AUTH:
132
0
        case CKA_PKCS_TRUST_EMAIL_PROTECTION:
133
0
        case CKA_PKCS_TRUST_CODE_SIGNING:
134
0
        case CKA_NSS_OVERRIDE_EXTENSIONS:
135
0
            return PR_TRUE;
136
0
        default:
137
0
            break;
138
0
    }
139
0
    return PR_FALSE;
140
0
}
141
/*
142
 * convert a native ULONG to a database ulong. Database ulong's
143
 * are all 4 byte big endian values.
144
 */
145
void
146
sftk_ULong2SDBULong(unsigned char *data, CK_ULONG value)
147
0
{
148
0
    int i;
149
150
0
    for (i = 0; i < SDB_ULONG_SIZE; i++) {
151
0
        data[i] = (value >> (SDB_ULONG_SIZE - 1 - i) * BBP) & 0xff;
152
0
    }
153
0
}
154
155
/*
156
 * convert a database ulong back to a native ULONG. (reverse of the above
157
 * function).
158
 */
159
static CK_ULONG
160
sftk_SDBULong2ULong(unsigned char *data)
161
0
{
162
0
    int i;
163
0
    CK_ULONG value = 0;
164
165
0
    for (i = 0; i < SDB_ULONG_SIZE; i++) {
166
0
        value |= (((CK_ULONG)data[i]) << (SDB_ULONG_SIZE - 1 - i) * BBP);
167
0
    }
168
0
    return value;
169
0
}
170
171
/* certain trust records are default values, which are the values
172
 * returned if the signature check fails anyway.
173
 * In those cases, we can skip the signature check. */
174
PRBool
175
sftkdb_isNullTrust(const CK_ATTRIBUTE *template)
176
0
{
177
0
    switch (template->type) {
178
0
        case CKA_NSS_TRUST_SERVER_AUTH:
179
0
        case CKA_NSS_TRUST_CLIENT_AUTH:
180
0
        case CKA_NSS_TRUST_EMAIL_PROTECTION:
181
0
        case CKA_NSS_TRUST_CODE_SIGNING:
182
0
            if (template->ulValueLen != SDB_ULONG_SIZE) {
183
0
                break;
184
0
            }
185
0
            if (sftk_SDBULong2ULong(template->pValue) ==
186
0
                CKT_NSS_TRUST_UNKNOWN) {
187
0
                return PR_TRUE;
188
0
            }
189
0
            break;
190
0
        case CKA_PKCS_TRUST_SERVER_AUTH:
191
0
        case CKA_PKCS_TRUST_CLIENT_AUTH:
192
0
        case CKA_PKCS_TRUST_EMAIL_PROTECTION:
193
0
        case CKA_PKCS_TRUST_CODE_SIGNING:
194
0
            if (template->ulValueLen != SDB_ULONG_SIZE) {
195
0
                break;
196
0
            }
197
0
            if (sftk_SDBULong2ULong(template->pValue) ==
198
0
                CKT_TRUST_UNKNOWN) {
199
0
                return PR_TRUE;
200
0
            }
201
0
            break;
202
0
        case CKA_NSS_TRUST_STEP_UP_APPROVED:
203
0
            if (template->ulValueLen != 1) {
204
0
                break;
205
0
            }
206
0
            if (*((unsigned char *)(template->pValue)) == 0) {
207
0
                return PR_TRUE;
208
0
            }
209
0
            break;
210
0
        default:
211
0
            break;
212
0
    }
213
0
    return PR_FALSE;
214
0
}
215
216
/*
217
 * fix up the input templates. Our fixed up ints are stored in data and must
218
 * be freed by the caller. The new template must also be freed. If there are no
219
 * CK_ULONG attributes, the orignal template is passed in as is.
220
 */
221
static CK_ATTRIBUTE *
222
sftkdb_fixupTemplateIn(const CK_ATTRIBUTE *template, int count,
223
                       unsigned char **dataOut, int *dataOutSize)
224
0
{
225
0
    int i;
226
0
    int ulongCount = 0;
227
0
    unsigned char *data;
228
0
    CK_ATTRIBUTE *ntemplate;
229
230
0
    *dataOut = NULL;
231
0
    *dataOutSize = 0;
232
233
    /* first count the number of CK_ULONG attributes */
234
0
    for (i = 0; i < count; i++) {
235
        /* Don't 'fixup' NULL values */
236
0
        if (!template[i].pValue) {
237
0
            continue;
238
0
        }
239
0
        if (template[i].ulValueLen == sizeof(CK_ULONG)) {
240
0
            if (sftkdb_isULONGAttribute(template[i].type)) {
241
0
                ulongCount++;
242
0
            }
243
0
        }
244
0
    }
245
    /* no attributes to fixup, just call on through */
246
0
    if (ulongCount == 0) {
247
0
        return (CK_ATTRIBUTE *)template;
248
0
    }
249
250
    /* allocate space for new ULONGS */
251
0
    data = (unsigned char *)PORT_Alloc(SDB_ULONG_SIZE * ulongCount);
252
0
    if (!data) {
253
0
        return NULL;
254
0
    }
255
256
    /* allocate new template */
257
0
    ntemplate = PORT_NewArray(CK_ATTRIBUTE, count);
258
0
    if (!ntemplate) {
259
0
        PORT_Free(data);
260
0
        return NULL;
261
0
    }
262
0
    *dataOut = data;
263
0
    *dataOutSize = SDB_ULONG_SIZE * ulongCount;
264
    /* copy the old template, fixup the actual ulongs */
265
0
    for (i = 0; i < count; i++) {
266
0
        ntemplate[i] = template[i];
267
        /* Don't 'fixup' NULL values */
268
0
        if (!template[i].pValue) {
269
0
            continue;
270
0
        }
271
0
        if (template[i].ulValueLen == sizeof(CK_ULONG)) {
272
0
            if (sftkdb_isULONGAttribute(template[i].type)) {
273
0
                CK_ULONG value = *(CK_ULONG *)template[i].pValue;
274
0
                sftk_ULong2SDBULong(data, value);
275
0
                ntemplate[i].pValue = data;
276
0
                ntemplate[i].ulValueLen = SDB_ULONG_SIZE;
277
0
                data += SDB_ULONG_SIZE;
278
0
            }
279
0
        }
280
0
    }
281
0
    return ntemplate;
282
0
}
283
284
static const char SFTKDB_META_SIG_TEMPLATE[] = "sig_%s_%08x_%08x";
285
286
/*
287
 * return a string describing the database type (key or cert)
288
 */
289
const char *
290
sftkdb_TypeString(SFTKDBHandle *handle)
291
0
{
292
0
    return (handle->type == SFTK_KEYDB_TYPE) ? "key" : "cert";
293
0
}
294
295
/*
296
 * Some attributes are signed with an Hmac and a pbe key generated from
297
 * the password. This signature is stored indexed by object handle and
298
 * attribute type in the meta data table in the key database.
299
 *
300
 * Signature entries are indexed by the string
301
 * sig_[cert/key]_{ObjectID}_{Attribute}
302
 *
303
 * This function fetches that pkcs5 signature. Caller supplies a SECItem
304
 * pre-allocated to the appropriate size if the SECItem is too small the
305
 * function will fail with CKR_BUFFER_TOO_SMALL.
306
 */
307
static CK_RV
308
sftkdb_getRawAttributeSignature(SFTKDBHandle *handle, SDB *db,
309
                                CK_OBJECT_HANDLE objectID,
310
                                CK_ATTRIBUTE_TYPE type,
311
                                SECItem *signText)
312
0
{
313
0
    char id[30];
314
0
    CK_RV crv;
315
316
0
    snprintf(id, sizeof(id), SFTKDB_META_SIG_TEMPLATE,
317
0
             sftkdb_TypeString(handle),
318
0
             (unsigned int)objectID, (unsigned int)type);
319
320
0
    crv = (*db->sdb_GetMetaData)(db, id, signText, NULL);
321
0
    return crv;
322
0
}
323
324
CK_RV
325
sftkdb_GetAttributeSignature(SFTKDBHandle *handle, SFTKDBHandle *keyHandle,
326
                             CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type,
327
                             SECItem *signText)
328
0
{
329
0
    SDB *db = SFTK_GET_SDB(keyHandle);
330
0
    return sftkdb_getRawAttributeSignature(handle, db, objectID, type, signText);
331
0
}
332
333
CK_RV
334
sftkdb_DestroyAttributeSignature(SFTKDBHandle *handle, SDB *db,
335
                                 CK_OBJECT_HANDLE objectID,
336
                                 CK_ATTRIBUTE_TYPE type)
337
0
{
338
0
    char id[30];
339
0
    CK_RV crv;
340
341
0
    snprintf(id, sizeof(id), SFTKDB_META_SIG_TEMPLATE,
342
0
             sftkdb_TypeString(handle),
343
0
             (unsigned int)objectID, (unsigned int)type);
344
345
0
    crv = (*db->sdb_DestroyMetaData)(db, id);
346
0
    return crv;
347
0
}
348
349
/*
350
 * Some attributes are signed with an Hmac and a pbe key generated from
351
 * the password. This signature is stored indexed by object handle and
352
 * attribute type in the meta data table in the key database.
353
 *
354
 * Signature entries are indexed by the string
355
 * sig_[cert/key]_{ObjectID}_{Attribute}
356
 *
357
 * This function stores that pkcs5 signature.
358
 */
359
CK_RV
360
sftkdb_PutAttributeSignature(SFTKDBHandle *handle, SDB *keyTarget,
361
                             CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type,
362
                             SECItem *signText)
363
0
{
364
0
    char id[30];
365
0
    CK_RV crv;
366
367
0
    snprintf(id, sizeof(id), SFTKDB_META_SIG_TEMPLATE,
368
0
             sftkdb_TypeString(handle),
369
0
             (unsigned int)objectID, (unsigned int)type);
370
371
0
    crv = (*keyTarget->sdb_PutMetaData)(keyTarget, id, signText, NULL);
372
0
    return crv;
373
0
}
374
375
/*
376
 * fix up returned data. NOTE: sftkdb_fixupTemplateIn has already allocated
377
 * separate data sections for the database ULONG values.
378
 */
379
static CK_RV
380
sftkdb_fixupTemplateOut(CK_ATTRIBUTE *template, CK_OBJECT_HANDLE objectID,
381
                        CK_ATTRIBUTE *ntemplate, int count, SFTKDBHandle *handle)
382
0
{
383
0
    int i;
384
0
    CK_RV crv = CKR_OK;
385
0
    SFTKDBHandle *keyHandle;
386
0
    PRBool checkSig = PR_TRUE;
387
0
    PRBool checkEnc = PR_TRUE;
388
389
0
    PORT_Assert(handle);
390
391
    /* find the key handle */
392
0
    keyHandle = handle;
393
0
    if (handle->type != SFTK_KEYDB_TYPE) {
394
0
        checkEnc = PR_FALSE;
395
0
        keyHandle = handle->peerDB;
396
0
    }
397
398
0
    if ((keyHandle == NULL) ||
399
0
        ((SFTK_GET_SDB(keyHandle)->sdb_flags & SDB_HAS_META) == 0) ||
400
0
        (sftkdb_PWCached(keyHandle) != SECSuccess)) {
401
0
        checkSig = PR_FALSE;
402
0
    }
403
404
0
    for (i = 0; i < count; i++) {
405
0
        CK_ULONG length = template[i].ulValueLen;
406
0
        template[i].ulValueLen = ntemplate[i].ulValueLen;
407
        /* fixup ulongs */
408
0
        if (ntemplate[i].ulValueLen == SDB_ULONG_SIZE) {
409
0
            if (sftkdb_isULONGAttribute(template[i].type)) {
410
0
                if (template[i].pValue) {
411
0
                    CK_ULONG value;
412
413
0
                    value = sftk_SDBULong2ULong(ntemplate[i].pValue);
414
0
                    if (length < sizeof(CK_ULONG)) {
415
0
                        template[i].ulValueLen = -1;
416
0
                        crv = CKR_BUFFER_TOO_SMALL;
417
0
                        continue;
418
0
                    }
419
0
                    PORT_Memcpy(template[i].pValue, &value, sizeof(CK_ULONG));
420
0
                }
421
0
                template[i].ulValueLen = sizeof(CK_ULONG);
422
0
            }
423
0
        }
424
425
        /* if no data was retrieved, no need to process encrypted or signed
426
         * attributes */
427
0
        if ((template[i].pValue == NULL) || (template[i].ulValueLen == -1)) {
428
0
            continue;
429
0
        }
430
431
        /* fixup private attributes */
432
0
        if (checkEnc && sftkdb_isPrivateAttribute(ntemplate[i].type)) {
433
            /* we have a private attribute */
434
            /* This code depends on the fact that the cipherText is bigger
435
             * than the plain text */
436
0
            SECItem cipherText;
437
0
            SECItem *plainText;
438
0
            SECStatus rv;
439
440
0
            cipherText.data = ntemplate[i].pValue;
441
0
            cipherText.len = ntemplate[i].ulValueLen;
442
0
            PZ_Lock(handle->passwordLock);
443
0
            if (handle->passwordKey.data == NULL) {
444
0
                PZ_Unlock(handle->passwordLock);
445
0
                template[i].ulValueLen = -1;
446
0
                crv = CKR_USER_NOT_LOGGED_IN;
447
0
                continue;
448
0
            }
449
0
            rv = sftkdb_DecryptAttribute(handle,
450
0
                                         &handle->passwordKey,
451
0
                                         objectID,
452
0
                                         ntemplate[i].type,
453
0
                                         &cipherText, &plainText);
454
0
            PZ_Unlock(handle->passwordLock);
455
0
            if (rv != SECSuccess) {
456
0
                PORT_Memset(template[i].pValue, 0, template[i].ulValueLen);
457
0
                template[i].ulValueLen = -1;
458
0
                crv = CKR_GENERAL_ERROR;
459
0
                continue;
460
0
            }
461
0
            PORT_Assert(template[i].ulValueLen >= plainText->len);
462
0
            if (template[i].ulValueLen < plainText->len) {
463
0
                SECITEM_ZfreeItem(plainText, PR_TRUE);
464
0
                PORT_Memset(template[i].pValue, 0, template[i].ulValueLen);
465
0
                template[i].ulValueLen = -1;
466
0
                crv = CKR_GENERAL_ERROR;
467
0
                continue;
468
0
            }
469
470
            /* copy the plain text back into the template */
471
0
            PORT_Memcpy(template[i].pValue, plainText->data, plainText->len);
472
0
            template[i].ulValueLen = plainText->len;
473
0
            SECITEM_ZfreeItem(plainText, PR_TRUE);
474
0
        }
475
        /* make sure signed attributes are valid */
476
0
        if (checkSig && sftkdb_isAuthenticatedAttribute(ntemplate[i].type) && !sftkdb_isNullTrust(&ntemplate[i])) {
477
0
            SECStatus rv;
478
0
            CK_RV local_crv;
479
0
            SECItem signText;
480
0
            SECItem plainText;
481
0
            unsigned char signData[SDB_MAX_META_DATA_LEN];
482
483
0
            signText.data = signData;
484
0
            signText.len = sizeof(signData);
485
486
            /* Use a local variable so that we don't clobber any already
487
             * set error. This function returns either CKR_OK or the last
488
             * found error in the template */
489
0
            local_crv = sftkdb_GetAttributeSignature(handle, keyHandle,
490
0
                                                     objectID,
491
0
                                                     ntemplate[i].type,
492
0
                                                     &signText);
493
0
            if (local_crv != CKR_OK) {
494
0
                PORT_Memset(template[i].pValue, 0, template[i].ulValueLen);
495
0
                template[i].ulValueLen = -1;
496
0
                crv = local_crv;
497
0
                continue;
498
0
            }
499
500
0
            plainText.data = ntemplate[i].pValue;
501
0
            plainText.len = ntemplate[i].ulValueLen;
502
503
            /*
504
             * we do a second check holding the lock just in case the user
505
             * loggout while we were trying to get the signature.
506
             */
507
0
            PZ_Lock(keyHandle->passwordLock);
508
0
            if (keyHandle->passwordKey.data == NULL) {
509
                /* if we are no longer logged in, no use checking the other
510
                 * Signatures either. */
511
0
                checkSig = PR_FALSE;
512
0
                PZ_Unlock(keyHandle->passwordLock);
513
0
                continue;
514
0
            }
515
516
0
            rv = sftkdb_VerifyAttribute(keyHandle,
517
0
                                        &keyHandle->passwordKey,
518
0
                                        objectID, ntemplate[i].type,
519
0
                                        &plainText, &signText);
520
0
            PZ_Unlock(keyHandle->passwordLock);
521
0
            if (rv != SECSuccess) {
522
0
                PORT_Memset(template[i].pValue, 0, template[i].ulValueLen);
523
0
                template[i].ulValueLen = -1;
524
0
                crv = CKR_SIGNATURE_INVALID; /* better error code? */
525
0
            }
526
            /* This Attribute is fine */
527
0
        }
528
0
    }
529
0
    return crv;
530
0
}
531
532
/*
533
 * Some attributes are signed with an HMAC and a pbe key generated from
534
 * the password. This signature is stored indexed by object handle and
535
 *
536
 * Those attributes are:
537
 * 1) Trust object hashes and trust values.
538
 * 2) public key values.
539
 *
540
 * Certs themselves are considered properly authenticated by virtue of their
541
 * signature, or their matching hash with the trust object.
542
 *
543
 * These signature is only checked for objects coming from shared databases.
544
 * Older dbm style databases have such no signature checks. HMACs are also
545
 * only checked when the token is logged in, as it requires a pbe generated
546
 * from the password.
547
 *
548
 * Tokens which have no key database (and therefore no master password) do not
549
 * have any stored signature values. Signature values are stored in the key
550
 * database, since the signature data is tightly coupled to the key database
551
 * password.
552
 *
553
 * This function takes a template of attributes that were either created or
554
 * modified. These attributes are checked to see if the need to be signed.
555
 * If they do, then this function signs the attributes and writes them
556
 * to the meta data store.
557
 *
558
 * This function can fail if there are attributes that must be signed, but
559
 * the token is not logged in.
560
 *
561
 * The caller is expected to abort any transaction he was in in the
562
 * event of a failure of this function.
563
 */
564
static CK_RV
565
sftk_signTemplate(PLArenaPool *arena, SFTKDBHandle *handle,
566
                  PRBool mayBeUpdateDB,
567
                  CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template,
568
                  CK_ULONG count)
569
0
{
570
0
    unsigned int i;
571
0
    CK_RV crv;
572
0
    SFTKDBHandle *keyHandle = handle;
573
0
    SDB *keyTarget = NULL;
574
0
    PRBool usingPeerDB = PR_FALSE;
575
0
    PRBool inPeerDBTransaction = PR_FALSE;
576
577
0
    PORT_Assert(handle);
578
579
0
    if (handle->type != SFTK_KEYDB_TYPE) {
580
0
        keyHandle = handle->peerDB;
581
0
        usingPeerDB = PR_TRUE;
582
0
    }
583
584
    /* no key DB defined? then no need to sign anything */
585
0
    if (keyHandle == NULL) {
586
0
        crv = CKR_OK;
587
0
        goto loser;
588
0
    }
589
590
    /* When we are in a middle of an update, we have an update database set,
591
     * but we want to write to the real database. The bool mayBeUpdateDB is
592
     * set to TRUE if it's possible that we want to write an update database
593
     * rather than a primary */
594
0
    keyTarget = (mayBeUpdateDB && keyHandle->update) ? keyHandle->update : keyHandle->db;
595
596
    /* skip the the database does not support meta data */
597
0
    if ((keyTarget->sdb_flags & SDB_HAS_META) == 0) {
598
0
        crv = CKR_OK;
599
0
        goto loser;
600
0
    }
601
602
    /* If we had to switch databases, we need to initialize a transaction. */
603
0
    if (usingPeerDB) {
604
0
        crv = (*keyTarget->sdb_Begin)(keyTarget);
605
0
        if (crv != CKR_OK) {
606
0
            goto loser;
607
0
        }
608
0
        inPeerDBTransaction = PR_TRUE;
609
0
    }
610
611
0
    for (i = 0; i < count; i++) {
612
0
        if (sftkdb_isAuthenticatedAttribute(template[i].type)) {
613
0
            SECStatus rv;
614
0
            SECItem *signText;
615
0
            SECItem plainText;
616
617
0
            plainText.data = template[i].pValue;
618
0
            plainText.len = template[i].ulValueLen;
619
0
            PZ_Lock(keyHandle->passwordLock);
620
0
            if (keyHandle->passwordKey.data == NULL) {
621
0
                PZ_Unlock(keyHandle->passwordLock);
622
0
                crv = CKR_USER_NOT_LOGGED_IN;
623
0
                goto loser;
624
0
            }
625
0
            rv = sftkdb_SignAttribute(arena, keyHandle, keyTarget,
626
0
                                      &keyHandle->passwordKey,
627
0
                                      keyHandle->defaultIterationCount,
628
0
                                      objectID, template[i].type,
629
0
                                      &plainText, &signText);
630
0
            PZ_Unlock(keyHandle->passwordLock);
631
0
            if (rv != SECSuccess) {
632
0
                crv = CKR_GENERAL_ERROR; /* better error code here? */
633
0
                goto loser;
634
0
            }
635
0
            crv = sftkdb_PutAttributeSignature(handle, keyTarget, objectID,
636
0
                                               template[i].type, signText);
637
0
            if (crv != CKR_OK) {
638
0
                goto loser;
639
0
            }
640
0
        }
641
0
    }
642
0
    crv = CKR_OK;
643
644
    /* If necessary, commit the transaction */
645
0
    if (inPeerDBTransaction) {
646
0
        crv = (*keyTarget->sdb_Commit)(keyTarget);
647
0
        if (crv != CKR_OK) {
648
0
            goto loser;
649
0
        }
650
0
        inPeerDBTransaction = PR_FALSE;
651
0
    }
652
653
0
loser:
654
0
    if (inPeerDBTransaction) {
655
        /* The transaction must have failed. Abort. */
656
0
        (*keyTarget->sdb_Abort)(keyTarget);
657
0
        PORT_Assert(crv != CKR_OK);
658
0
        if (crv == CKR_OK)
659
0
            crv = CKR_GENERAL_ERROR;
660
0
    }
661
0
    return crv;
662
0
}
663
664
static CK_RV
665
sftkdb_CreateObject(PLArenaPool *arena, SFTKDBHandle *handle,
666
                    SDB *db, CK_OBJECT_HANDLE *objectID,
667
                    CK_ATTRIBUTE *template, CK_ULONG count)
668
0
{
669
0
    CK_RV crv;
670
671
0
    crv = (*db->sdb_CreateObject)(db, objectID, template, count);
672
0
    if (crv != CKR_OK) {
673
0
        goto loser;
674
0
    }
675
0
    crv = sftk_signTemplate(arena, handle, (db == handle->update),
676
0
                            *objectID, template, count);
677
0
loser:
678
679
0
    return crv;
680
0
}
681
682
static CK_RV
683
sftkdb_fixupSignatures(SFTKDBHandle *handle,
684
                       SDB *db, CK_OBJECT_HANDLE oldID, CK_OBJECT_HANDLE newID,
685
                       CK_ATTRIBUTE *ptemplate, CK_ULONG max_attributes)
686
0
{
687
0
    unsigned int i;
688
0
    CK_RV crv = CKR_OK;
689
690
    /* if we don't have a meta table, we didn't write any signature objects  */
691
0
    if ((db->sdb_flags & SDB_HAS_META) == 0) {
692
0
        return CKR_OK;
693
0
    }
694
0
    for (i = 0; i < max_attributes; i++) {
695
0
        CK_ATTRIBUTE *att = &ptemplate[i];
696
0
        CK_ATTRIBUTE_TYPE type = att->type;
697
0
        if (sftkdb_isPrivateAttribute(type)) {
698
            /* move the signature from one object handle to another and delete
699
             * the old entry */
700
0
            SECItem signature;
701
0
            unsigned char signData[SDB_MAX_META_DATA_LEN];
702
703
0
            signature.data = signData;
704
0
            signature.len = sizeof(signData);
705
0
            crv = sftkdb_getRawAttributeSignature(handle, db, oldID, type,
706
0
                                                  &signature);
707
0
            if (crv != CKR_OK) {
708
                /* NOTE: if we ever change our default write from AES_CBC
709
                 * to AES_KW, We'll need to change this to a continue as
710
                 * we won't need the integrity record for AES_KW */
711
0
                break;
712
0
            }
713
0
            crv = sftkdb_PutAttributeSignature(handle, db, newID, type,
714
0
                                               &signature);
715
0
            if (crv != CKR_OK) {
716
0
                break;
717
0
            }
718
            /* now get rid of the old one */
719
0
            crv = sftkdb_DestroyAttributeSignature(handle, db, oldID, type);
720
0
            if (crv != CKR_OK) {
721
0
                break;
722
0
            }
723
0
        }
724
0
    }
725
0
    return crv;
726
0
}
727
728
CK_ATTRIBUTE *
729
sftk_ExtractTemplate(PLArenaPool *arena, SFTKObject *object,
730
                     SFTKDBHandle *handle, CK_OBJECT_HANDLE objectID,
731
                     SDB *db, CK_ULONG *pcount, CK_RV *crv)
732
0
{
733
0
    unsigned int count;
734
0
    CK_ATTRIBUTE *template;
735
0
    unsigned int i, templateIndex;
736
0
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
737
0
    PRBool doEnc = PR_TRUE;
738
739
0
    *crv = CKR_OK;
740
741
0
    if (sessObject == NULL) {
742
0
        *crv = CKR_GENERAL_ERROR; /* internal programming error */
743
0
        return NULL;
744
0
    }
745
746
0
    PORT_Assert(handle);
747
    /* find the key handle */
748
0
    if (handle->type != SFTK_KEYDB_TYPE) {
749
0
        doEnc = PR_FALSE;
750
0
    }
751
752
0
    PZ_Lock(sessObject->attributeLock);
753
0
    count = 0;
754
0
    for (i = 0; i < sessObject->hashSize; i++) {
755
0
        SFTKAttribute *attr;
756
0
        for (attr = sessObject->head[i]; attr; attr = attr->next) {
757
0
            count++;
758
0
        }
759
0
    }
760
0
    template = PORT_ArenaNewArray(arena, CK_ATTRIBUTE, count);
761
0
    if (template == NULL) {
762
0
        PZ_Unlock(sessObject->attributeLock);
763
0
        *crv = CKR_HOST_MEMORY;
764
0
        return NULL;
765
0
    }
766
0
    templateIndex = 0;
767
0
    for (i = 0; i < sessObject->hashSize; i++) {
768
0
        SFTKAttribute *attr;
769
0
        for (attr = sessObject->head[i]; attr; attr = attr->next) {
770
0
            CK_ATTRIBUTE *tp = &template[templateIndex++];
771
            /* copy the attribute */
772
0
            *tp = attr->attrib;
773
774
            /* fixup  ULONG s */
775
0
            if ((tp->ulValueLen == sizeof(CK_ULONG)) &&
776
0
                (sftkdb_isULONGAttribute(tp->type))) {
777
0
                CK_ULONG value = *(CK_ULONG *)tp->pValue;
778
0
                unsigned char *data;
779
780
0
                tp->pValue = PORT_ArenaAlloc(arena, SDB_ULONG_SIZE);
781
0
                data = (unsigned char *)tp->pValue;
782
0
                if (data == NULL) {
783
0
                    *crv = CKR_HOST_MEMORY;
784
0
                    break;
785
0
                }
786
0
                sftk_ULong2SDBULong(data, value);
787
0
                tp->ulValueLen = SDB_ULONG_SIZE;
788
0
            }
789
790
            /* encrypt private attributes */
791
0
            if (doEnc && sftkdb_isPrivateAttribute(tp->type)) {
792
                /* we have a private attribute */
793
0
                SECItem *cipherText;
794
0
                SECItem plainText;
795
0
                SECStatus rv;
796
797
0
                plainText.data = tp->pValue;
798
0
                plainText.len = tp->ulValueLen;
799
0
                PZ_Lock(handle->passwordLock);
800
0
                if (handle->passwordKey.data == NULL) {
801
0
                    PZ_Unlock(handle->passwordLock);
802
0
                    *crv = CKR_USER_NOT_LOGGED_IN;
803
0
                    break;
804
0
                }
805
0
                rv = sftkdb_EncryptAttribute(arena, handle, db,
806
0
                                             &handle->passwordKey,
807
0
                                             handle->defaultIterationCount,
808
0
                                             objectID,
809
0
                                             tp->type,
810
0
                                             &plainText, &cipherText);
811
0
                PZ_Unlock(handle->passwordLock);
812
0
                if (rv == SECSuccess) {
813
0
                    tp->pValue = cipherText->data;
814
0
                    tp->ulValueLen = cipherText->len;
815
0
                } else {
816
0
                    *crv = CKR_GENERAL_ERROR; /* better error code here? */
817
0
                    break;
818
0
                }
819
0
                PORT_Memset(plainText.data, 0, plainText.len);
820
0
            }
821
0
        }
822
0
    }
823
0
    PORT_Assert(templateIndex <= count);
824
0
    PZ_Unlock(sessObject->attributeLock);
825
826
0
    if (*crv != CKR_OK) {
827
0
        return NULL;
828
0
    }
829
0
    if (pcount) {
830
0
        *pcount = count;
831
0
    }
832
0
    return template;
833
0
}
834
835
/*
836
 * return a pointer to the attribute in the give template.
837
 * The return value is not const, as the caller may modify
838
 * the given attribute value, but such modifications will
839
 * modify the actual value in the template.
840
 */
841
static CK_ATTRIBUTE *
842
sftkdb_getAttributeFromTemplate(CK_ATTRIBUTE_TYPE attribute,
843
                                CK_ATTRIBUTE *ptemplate, CK_ULONG len)
844
0
{
845
0
    CK_ULONG i;
846
847
0
    for (i = 0; i < len; i++) {
848
0
        if (attribute == ptemplate[i].type) {
849
0
            return &ptemplate[i];
850
0
        }
851
0
    }
852
0
    return NULL;
853
0
}
854
855
static const CK_ATTRIBUTE *
856
sftkdb_getAttributeFromConstTemplate(CK_ATTRIBUTE_TYPE attribute,
857
                                     const CK_ATTRIBUTE *ptemplate, CK_ULONG len)
858
0
{
859
0
    CK_ULONG i;
860
861
0
    for (i = 0; i < len; i++) {
862
0
        if (attribute == ptemplate[i].type) {
863
0
            return &ptemplate[i];
864
0
        }
865
0
    }
866
0
    return NULL;
867
0
}
868
869
/*
870
 * fetch a template which identifies 'unique' entries based on object type
871
 */
872
static CK_RV
873
sftkdb_getFindTemplate(CK_OBJECT_CLASS objectType, unsigned char *objTypeData,
874
                       CK_ATTRIBUTE *findTemplate, CK_ULONG *findCount,
875
                       CK_ATTRIBUTE *ptemplate, int len)
876
0
{
877
0
    CK_ATTRIBUTE *attr;
878
0
    CK_ULONG count = 1;
879
880
0
    sftk_ULong2SDBULong(objTypeData, objectType);
881
0
    findTemplate[0].type = CKA_CLASS;
882
0
    findTemplate[0].pValue = objTypeData;
883
0
    findTemplate[0].ulValueLen = SDB_ULONG_SIZE;
884
885
0
    switch (objectType) {
886
0
        case CKO_CERTIFICATE:
887
0
        case CKO_NSS_TRUST:
888
0
        case CKO_TRUST:
889
0
            attr = sftkdb_getAttributeFromTemplate(CKA_ISSUER, ptemplate, len);
890
0
            if (attr == NULL) {
891
0
                return CKR_TEMPLATE_INCOMPLETE;
892
0
            }
893
0
            findTemplate[1] = *attr;
894
0
            attr = sftkdb_getAttributeFromTemplate(CKA_SERIAL_NUMBER,
895
0
                                                   ptemplate, len);
896
0
            if (attr == NULL) {
897
0
                return CKR_TEMPLATE_INCOMPLETE;
898
0
            }
899
0
            findTemplate[2] = *attr;
900
0
            count = 3;
901
0
            break;
902
903
0
        case CKO_PRIVATE_KEY:
904
0
        case CKO_PUBLIC_KEY:
905
0
        case CKO_SECRET_KEY:
906
0
            attr = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, len);
907
0
            if (attr == NULL) {
908
0
                return CKR_TEMPLATE_INCOMPLETE;
909
0
            }
910
0
            if (attr->ulValueLen == 0) {
911
                /* key is too generic to determine that it's unique, usually
912
                 * happens in the key gen case */
913
0
                return CKR_OBJECT_HANDLE_INVALID;
914
0
            }
915
916
0
            findTemplate[1] = *attr;
917
0
            count = 2;
918
0
            break;
919
920
0
        case CKO_NSS_CRL:
921
0
            attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len);
922
0
            if (attr == NULL) {
923
0
                return CKR_TEMPLATE_INCOMPLETE;
924
0
            }
925
0
            findTemplate[1] = *attr;
926
0
            count = 2;
927
0
            break;
928
929
0
        case CKO_NSS_SMIME:
930
0
            attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len);
931
0
            if (attr == NULL) {
932
0
                return CKR_TEMPLATE_INCOMPLETE;
933
0
            }
934
0
            findTemplate[1] = *attr;
935
0
            attr = sftkdb_getAttributeFromTemplate(CKA_NSS_EMAIL, ptemplate, len);
936
0
            if (attr == NULL) {
937
0
                return CKR_TEMPLATE_INCOMPLETE;
938
0
            }
939
0
            findTemplate[2] = *attr;
940
0
            count = 3;
941
0
            break;
942
0
        default:
943
0
            attr = sftkdb_getAttributeFromTemplate(CKA_VALUE, ptemplate, len);
944
0
            if (attr == NULL) {
945
0
                return CKR_TEMPLATE_INCOMPLETE;
946
0
            }
947
0
            findTemplate[1] = *attr;
948
0
            count = 2;
949
0
            break;
950
0
    }
951
0
    *findCount = count;
952
953
0
    return CKR_OK;
954
0
}
955
956
/*
957
 * look to see if this object already exists and return its object ID if
958
 * it does.
959
 */
960
static CK_RV
961
sftkdb_lookupObject(SDB *db, CK_OBJECT_CLASS objectType,
962
                    CK_OBJECT_HANDLE *id, CK_ATTRIBUTE *ptemplate, CK_ULONG len)
963
0
{
964
0
    CK_ATTRIBUTE findTemplate[3];
965
0
    CK_ULONG count = 1;
966
0
    CK_ULONG objCount = 0;
967
0
    SDBFind *find = NULL;
968
0
    unsigned char objTypeData[SDB_ULONG_SIZE];
969
0
    CK_RV crv;
970
971
0
    *id = CK_INVALID_HANDLE;
972
0
    if (objectType == CKO_NSS_CRL) {
973
0
        return CKR_OK;
974
0
    }
975
0
    crv = sftkdb_getFindTemplate(objectType, objTypeData,
976
0
                                 findTemplate, &count, ptemplate, len);
977
978
0
    if (crv == CKR_OBJECT_HANDLE_INVALID) {
979
        /* key is too generic to determine that it's unique, usually
980
         * happens in the key gen case, tell the caller to go ahead
981
         * and just create it */
982
0
        return CKR_OK;
983
0
    }
984
0
    if (crv != CKR_OK) {
985
0
        return crv;
986
0
    }
987
988
    /* use the raw find, so we get the correct database */
989
0
    crv = (*db->sdb_FindObjectsInit)(db, findTemplate, count, &find);
990
0
    if (crv != CKR_OK) {
991
0
        return crv;
992
0
    }
993
0
    (*db->sdb_FindObjects)(db, find, id, 1, &objCount);
994
0
    (*db->sdb_FindObjectsFinal)(db, find);
995
996
0
    if (objCount == 0) {
997
0
        *id = CK_INVALID_HANDLE;
998
0
    }
999
0
    return CKR_OK;
1000
0
}
1001
1002
/*
1003
 * check to see if this template conflicts with others in our current database.
1004
 */
1005
static CK_RV
1006
sftkdb_checkConflicts(SDB *db, CK_OBJECT_CLASS objectType,
1007
                      const CK_ATTRIBUTE *ptemplate, CK_ULONG len,
1008
                      CK_OBJECT_HANDLE sourceID)
1009
0
{
1010
0
    CK_ATTRIBUTE findTemplate[2];
1011
0
    unsigned char objTypeData[SDB_ULONG_SIZE];
1012
    /* we may need to allocate some temporaries. Keep track of what was
1013
     * allocated so we can free it in the end */
1014
0
    unsigned char *temp1 = NULL;
1015
0
    unsigned char *temp2 = NULL;
1016
0
    CK_ULONG objCount = 0;
1017
0
    SDBFind *find = NULL;
1018
0
    CK_OBJECT_HANDLE id;
1019
0
    const CK_ATTRIBUTE *attr, *attr2;
1020
0
    CK_RV crv;
1021
0
    CK_ATTRIBUTE subject;
1022
1023
    /* Currently the only conflict is with nicknames pointing to the same
1024
     * subject when creating or modifying a certificate. */
1025
    /* If the object is not a cert, no problem. */
1026
0
    if (objectType != CKO_CERTIFICATE) {
1027
0
        return CKR_OK;
1028
0
    }
1029
    /* if not setting a nickname then there's still no problem */
1030
0
    attr = sftkdb_getAttributeFromConstTemplate(CKA_LABEL, ptemplate, len);
1031
0
    if ((attr == NULL) || (attr->ulValueLen == 0)) {
1032
0
        return CKR_OK;
1033
0
    }
1034
    /* fetch the subject of the source. For creation and merge, this should
1035
     * be found in the template */
1036
0
    attr2 = sftkdb_getAttributeFromConstTemplate(CKA_SUBJECT, ptemplate, len);
1037
0
    if (sourceID == CK_INVALID_HANDLE) {
1038
0
        if ((attr2 == NULL) || ((CK_LONG)attr2->ulValueLen < 0)) {
1039
0
            crv = CKR_TEMPLATE_INCOMPLETE;
1040
0
            goto done;
1041
0
        }
1042
0
    } else if ((attr2 == NULL) || ((CK_LONG)attr2->ulValueLen <= 0)) {
1043
        /* sourceID is set if we are trying to modify an existing entry instead
1044
         * of creating a new one. In this case the subject may not be (probably
1045
         * isn't) in the template, we have to read it from the database */
1046
0
        subject.type = CKA_SUBJECT;
1047
0
        subject.pValue = NULL;
1048
0
        subject.ulValueLen = 0;
1049
0
        crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1);
1050
0
        if (crv != CKR_OK) {
1051
0
            goto done;
1052
0
        }
1053
0
        if ((CK_LONG)subject.ulValueLen < 0) {
1054
0
            crv = CKR_DEVICE_ERROR; /* closest pkcs11 error to corrupted DB */
1055
0
            goto done;
1056
0
        }
1057
0
        temp1 = subject.pValue = PORT_Alloc(++subject.ulValueLen);
1058
0
        if (temp1 == NULL) {
1059
0
            crv = CKR_HOST_MEMORY;
1060
0
            goto done;
1061
0
        }
1062
0
        crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1);
1063
0
        if (crv != CKR_OK) {
1064
0
            goto done;
1065
0
        }
1066
0
        attr2 = &subject;
1067
0
    }
1068
1069
    /* check for another cert in the database with the same nickname */
1070
0
    sftk_ULong2SDBULong(objTypeData, objectType);
1071
0
    findTemplate[0].type = CKA_CLASS;
1072
0
    findTemplate[0].pValue = objTypeData;
1073
0
    findTemplate[0].ulValueLen = SDB_ULONG_SIZE;
1074
0
    findTemplate[1] = *attr;
1075
1076
0
    crv = (*db->sdb_FindObjectsInit)(db, findTemplate, 2, &find);
1077
0
    if (crv != CKR_OK) {
1078
0
        goto done;
1079
0
    }
1080
0
    (*db->sdb_FindObjects)(db, find, &id, 1, &objCount);
1081
0
    (*db->sdb_FindObjectsFinal)(db, find);
1082
1083
    /* object count == 0 means no conflicting certs found,
1084
     * go on with the operation */
1085
0
    if (objCount == 0) {
1086
0
        crv = CKR_OK;
1087
0
        goto done;
1088
0
    }
1089
1090
    /* There is a least one cert that shares the nickname, make sure it also
1091
     * matches the subject. */
1092
0
    findTemplate[0] = *attr2;
1093
    /* we know how big the source subject was. Use that length to create the
1094
     * space for the target. If it's not enough space, then it means the
1095
     * source subject is too big, and therefore not a match. GetAttributeValue
1096
     * will return CKR_BUFFER_TOO_SMALL. Otherwise it should be exactly enough
1097
     * space (or enough space to be able to compare the result. */
1098
0
    temp2 = findTemplate[0].pValue = PORT_Alloc(++findTemplate[0].ulValueLen);
1099
0
    if (temp2 == NULL) {
1100
0
        crv = CKR_HOST_MEMORY;
1101
0
        goto done;
1102
0
    }
1103
0
    crv = (*db->sdb_GetAttributeValue)(db, id, findTemplate, 1);
1104
0
    if (crv != CKR_OK) {
1105
0
        if (crv == CKR_BUFFER_TOO_SMALL) {
1106
            /* if our buffer is too small, then the Subjects clearly do
1107
             * not match */
1108
0
            crv = CKR_ATTRIBUTE_VALUE_INVALID;
1109
0
            goto loser;
1110
0
        }
1111
        /* otherwise we couldn't get the value, just fail */
1112
0
        goto done;
1113
0
    }
1114
1115
    /* Ok, we have both subjects, make sure they are the same.
1116
     * Compare the subjects */
1117
0
    if ((findTemplate[0].ulValueLen != attr2->ulValueLen) ||
1118
0
        (attr2->ulValueLen > 0 &&
1119
0
         PORT_Memcmp(findTemplate[0].pValue, attr2->pValue, attr2->ulValueLen) != 0)) {
1120
0
        crv = CKR_ATTRIBUTE_VALUE_INVALID;
1121
0
        goto loser;
1122
0
    }
1123
0
    crv = CKR_OK;
1124
1125
0
done:
1126
    /* If we've failed for some other reason than a conflict, make sure we
1127
     * return an error code other than CKR_ATTRIBUTE_VALUE_INVALID.
1128
     * (NOTE: neither sdb_FindObjectsInit nor sdb_GetAttributeValue should
1129
     * return CKR_ATTRIBUTE_VALUE_INVALID, so the following is paranoia).
1130
     */
1131
0
    if (crv == CKR_ATTRIBUTE_VALUE_INVALID) {
1132
0
        crv = CKR_GENERAL_ERROR; /* clearly a programming error */
1133
0
    }
1134
1135
/* exit point if we found a conflict */
1136
0
loser:
1137
0
    PORT_Free(temp1);
1138
0
    PORT_Free(temp2);
1139
0
    return crv;
1140
0
}
1141
1142
/*
1143
 * try to update the template to fix any errors. This is only done
1144
 * during update.
1145
 *
1146
 * NOTE: we must update the template or return an error, or the update caller
1147
 * will loop forever!
1148
 *
1149
 * Two copies of the source code for this algorithm exist in NSS.
1150
 * Changes must be made in both copies.
1151
 * The other copy is in pk11_IncrementNickname() in pk11wrap/pk11merge.c.
1152
 *
1153
 */
1154
static CK_RV
1155
sftkdb_resolveConflicts(PLArenaPool *arena, CK_OBJECT_CLASS objectType,
1156
                        CK_ATTRIBUTE *ptemplate, CK_ULONG *plen)
1157
0
{
1158
0
    CK_ATTRIBUTE *attr;
1159
0
    char *nickname, *newNickname;
1160
0
    unsigned int end, digit;
1161
1162
    /* sanity checks. We should never get here with these errors */
1163
0
    if (objectType != CKO_CERTIFICATE) {
1164
0
        return CKR_GENERAL_ERROR; /* shouldn't happen */
1165
0
    }
1166
0
    attr = sftkdb_getAttributeFromTemplate(CKA_LABEL, ptemplate, *plen);
1167
0
    if ((attr == NULL) || (attr->ulValueLen == 0)) {
1168
0
        return CKR_GENERAL_ERROR; /* shouldn't happen */
1169
0
    }
1170
1171
    /* update the nickname */
1172
    /* is there a number at the end of the nickname already?
1173
     * if so just increment that number  */
1174
0
    nickname = (char *)attr->pValue;
1175
1176
    /* does nickname end with " #n*" ? */
1177
0
    for (end = attr->ulValueLen - 1;
1178
0
         end >= 2 && (digit = nickname[end]) <= '9' && digit >= '0';
1179
0
         end--) /* just scan */
1180
0
        ;
1181
0
    if (attr->ulValueLen >= 3 &&
1182
0
        end < (attr->ulValueLen - 1) /* at least one digit */ &&
1183
0
        nickname[end] == '#' &&
1184
0
        nickname[end - 1] == ' ') {
1185
        /* Already has a suitable suffix string */
1186
0
    } else {
1187
        /* ... append " #2" to the name */
1188
0
        static const char num2[] = " #2";
1189
0
        newNickname = PORT_ArenaAlloc(arena, attr->ulValueLen + sizeof(num2));
1190
0
        if (!newNickname) {
1191
0
            return CKR_HOST_MEMORY;
1192
0
        }
1193
0
        PORT_Memcpy(newNickname, nickname, attr->ulValueLen);
1194
0
        PORT_Memcpy(&newNickname[attr->ulValueLen], num2, sizeof(num2));
1195
0
        attr->pValue = newNickname; /* modifies ptemplate */
1196
0
        attr->ulValueLen += 3;      /* 3 is strlen(num2)  */
1197
0
        return CKR_OK;
1198
0
    }
1199
1200
0
    for (end = attr->ulValueLen; end-- > 0;) {
1201
0
        digit = nickname[end];
1202
0
        if (digit > '9' || digit < '0') {
1203
0
            break;
1204
0
        }
1205
0
        if (digit < '9') {
1206
0
            nickname[end]++;
1207
0
            return CKR_OK;
1208
0
        }
1209
0
        nickname[end] = '0';
1210
0
    }
1211
1212
    /* we overflowed, insert a new '1' for a carry in front of the number */
1213
0
    newNickname = PORT_ArenaAlloc(arena, attr->ulValueLen + 1);
1214
0
    if (!newNickname) {
1215
0
        return CKR_HOST_MEMORY;
1216
0
    }
1217
    /* PORT_Memcpy should handle len of '0' */
1218
0
    PORT_Memcpy(newNickname, nickname, ++end);
1219
0
    newNickname[end] = '1';
1220
0
    PORT_Memset(&newNickname[end + 1], '0', attr->ulValueLen - end);
1221
0
    attr->pValue = newNickname;
1222
0
    attr->ulValueLen++;
1223
0
    return CKR_OK;
1224
0
}
1225
1226
/*
1227
 * set an attribute and sign it if necessary
1228
 */
1229
static CK_RV
1230
sftkdb_setAttributeValue(PLArenaPool *arena, SFTKDBHandle *handle,
1231
                         SDB *db, CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template,
1232
                         CK_ULONG count)
1233
0
{
1234
0
    CK_RV crv;
1235
0
    crv = (*db->sdb_SetAttributeValue)(db, objectID, template, count);
1236
0
    if (crv != CKR_OK) {
1237
0
        return crv;
1238
0
    }
1239
0
    crv = sftk_signTemplate(arena, handle, db == handle->update,
1240
0
                            objectID, template, count);
1241
0
    return crv;
1242
0
}
1243
1244
/*
1245
 * write a softoken object out to the database.
1246
 */
1247
CK_RV
1248
sftkdb_write(SFTKDBHandle *handle, SFTKObject *object,
1249
             CK_OBJECT_HANDLE *objectID)
1250
0
{
1251
0
    CK_ATTRIBUTE *template;
1252
0
    PLArenaPool *arena;
1253
0
    CK_ULONG count;
1254
0
    CK_RV crv;
1255
0
    SDB *db;
1256
0
    PRBool inTransaction = PR_FALSE;
1257
0
    CK_OBJECT_HANDLE id, candidateID;
1258
1259
0
    *objectID = CK_INVALID_HANDLE;
1260
1261
0
    if (handle == NULL) {
1262
0
        return CKR_TOKEN_WRITE_PROTECTED;
1263
0
    }
1264
0
    db = SFTK_GET_SDB(handle);
1265
1266
    /*
1267
     * we have opened a new database, but we have not yet updated it. We are
1268
     * still running pointing to the old database (so the application can
1269
     * still read). We don't want to write to the old database at this point,
1270
     * however, since it leads to user confusion. So at this point we simply
1271
     * require a user login. Let NSS know this so it can prompt the user.
1272
     */
1273
0
    if (db == handle->update) {
1274
0
        return CKR_USER_NOT_LOGGED_IN;
1275
0
    }
1276
1277
0
    arena = PORT_NewArena(256);
1278
0
    if (arena == NULL) {
1279
0
        return CKR_HOST_MEMORY;
1280
0
    }
1281
1282
0
    crv = (*db->sdb_Begin)(db);
1283
0
    if (crv != CKR_OK) {
1284
0
        goto loser;
1285
0
    }
1286
0
    inTransaction = PR_TRUE;
1287
1288
0
    crv = (*db->sdb_GetNewObjectID)(db, &candidateID);
1289
0
    if (crv != CKR_OK) {
1290
0
        goto loser;
1291
0
    }
1292
1293
0
    template = sftk_ExtractTemplate(arena, object, handle, candidateID, db, &count, &crv);
1294
0
    if (!template) {
1295
0
        goto loser;
1296
0
    }
1297
1298
    /*
1299
     * We want to make the base database as free from object specific knowledge
1300
     * as possible. To maintain compatibility, keep some of the desirable
1301
     * object specific semantics of the old database.
1302
     *
1303
     * These were 2 fold:
1304
     *  1) there were certain conflicts (like trying to set the same nickname
1305
     * on two different subjects) that would return an error.
1306
     *  2) Importing the 'same' object would silently update that object.
1307
     *
1308
     * The following 2 functions mimic the desirable effects of these two
1309
     * semantics without pushing any object knowledge to the underlying database
1310
     * code.
1311
     */
1312
1313
    /* make sure we don't have attributes that conflict with the existing DB */
1314
0
    crv = sftkdb_checkConflicts(db, object->objclass, template, count,
1315
0
                                CK_INVALID_HANDLE);
1316
0
    if (crv != CKR_OK) {
1317
0
        goto loser;
1318
0
    }
1319
    /* Find any copies that match this particular object */
1320
0
    crv = sftkdb_lookupObject(db, object->objclass, &id, template, count);
1321
0
    if (crv != CKR_OK) {
1322
0
        goto loser;
1323
0
    }
1324
0
    if (id == CK_INVALID_HANDLE) {
1325
0
        *objectID = candidateID;
1326
0
        crv = sftkdb_CreateObject(arena, handle, db, objectID, template, count);
1327
0
    } else {
1328
        /* object already exists, modify it's attributes */
1329
0
        *objectID = id;
1330
        /* The object ID changed from our candidate, we need to move any
1331
         * signature attribute signatures to the new object ID. */
1332
0
        crv = sftkdb_fixupSignatures(handle, db, candidateID, id,
1333
0
                                     template, count);
1334
0
        if (crv != CKR_OK) {
1335
0
            goto loser;
1336
0
        }
1337
0
        crv = sftkdb_setAttributeValue(arena, handle, db, id, template, count);
1338
0
    }
1339
0
    if (crv != CKR_OK) {
1340
0
        goto loser;
1341
0
    }
1342
0
    crv = (*db->sdb_Commit)(db);
1343
0
    inTransaction = PR_FALSE;
1344
1345
0
loser:
1346
0
    if (inTransaction) {
1347
0
        (*db->sdb_Abort)(db);
1348
        /* It is trivial to show the following code cannot
1349
         * happen unless something is horribly wrong with our compilier or
1350
         * hardware */
1351
0
        PORT_Assert(crv != CKR_OK);
1352
0
        if (crv == CKR_OK)
1353
0
            crv = CKR_GENERAL_ERROR;
1354
0
    }
1355
1356
0
    if (arena) {
1357
0
        PORT_FreeArena(arena, PR_TRUE);
1358
0
    }
1359
0
    if (crv == CKR_OK) {
1360
0
        *objectID |= (handle->type | SFTK_TOKEN_TYPE);
1361
0
    }
1362
0
    return crv;
1363
0
}
1364
1365
CK_RV
1366
sftkdb_FindObjectsInit(SFTKDBHandle *handle, const CK_ATTRIBUTE *template,
1367
                       CK_ULONG count, SDBFind **find)
1368
0
{
1369
0
    unsigned char *data = NULL;
1370
0
    CK_ATTRIBUTE *ntemplate = NULL;
1371
0
    CK_RV crv;
1372
0
    int dataSize;
1373
0
    SDB *db;
1374
1375
0
    if (handle == NULL) {
1376
0
        return CKR_OK;
1377
0
    }
1378
0
    db = SFTK_GET_SDB(handle);
1379
1380
0
    if (count != 0) {
1381
0
        ntemplate = sftkdb_fixupTemplateIn(template, count, &data, &dataSize);
1382
0
        if (ntemplate == NULL) {
1383
0
            return CKR_HOST_MEMORY;
1384
0
        }
1385
0
    }
1386
1387
0
    crv = (*db->sdb_FindObjectsInit)(db, ntemplate,
1388
0
                                     count, find);
1389
0
    if (data) {
1390
0
        PORT_Free(ntemplate);
1391
0
        PORT_ZFree(data, dataSize);
1392
0
    }
1393
0
    return crv;
1394
0
}
1395
1396
CK_RV
1397
sftkdb_FindObjects(SFTKDBHandle *handle, SDBFind *find,
1398
                   CK_OBJECT_HANDLE *ids, int arraySize, CK_ULONG *count)
1399
0
{
1400
0
    CK_RV crv;
1401
0
    SDB *db;
1402
1403
0
    if (handle == NULL) {
1404
0
        *count = 0;
1405
0
        return CKR_OK;
1406
0
    }
1407
0
    db = SFTK_GET_SDB(handle);
1408
1409
0
    crv = (*db->sdb_FindObjects)(db, find, ids,
1410
0
                                 arraySize, count);
1411
0
    if (crv == CKR_OK) {
1412
0
        unsigned int i;
1413
0
        for (i = 0; i < *count; i++) {
1414
0
            ids[i] |= (handle->type | SFTK_TOKEN_TYPE);
1415
0
        }
1416
0
    }
1417
0
    return crv;
1418
0
}
1419
1420
CK_RV
1421
sftkdb_FindObjectsFinal(SFTKDBHandle *handle, SDBFind *find)
1422
0
{
1423
0
    SDB *db;
1424
0
    if (handle == NULL) {
1425
0
        return CKR_OK;
1426
0
    }
1427
0
    db = SFTK_GET_SDB(handle);
1428
0
    return (*db->sdb_FindObjectsFinal)(db, find);
1429
0
}
1430
1431
CK_RV
1432
sftkdb_GetAttributeValue(SFTKDBHandle *handle, CK_OBJECT_HANDLE objectID,
1433
                         CK_ATTRIBUTE *template, CK_ULONG count)
1434
0
{
1435
0
    CK_RV crv, crv2;
1436
0
    CK_ATTRIBUTE *ntemplate;
1437
0
    unsigned char *data = NULL;
1438
0
    int dataSize = 0;
1439
0
    SDB *db;
1440
1441
0
    if (handle == NULL) {
1442
0
        return CKR_GENERAL_ERROR;
1443
0
    }
1444
1445
    /* short circuit common attributes */
1446
0
    if (count == 1 &&
1447
0
        (template[0].type == CKA_TOKEN ||
1448
0
         template[0].type == CKA_PRIVATE ||
1449
0
         template[0].type == CKA_SENSITIVE)) {
1450
0
        CK_BBOOL boolVal = CK_TRUE;
1451
1452
0
        if (template[0].pValue == NULL) {
1453
0
            template[0].ulValueLen = sizeof(CK_BBOOL);
1454
0
            return CKR_OK;
1455
0
        }
1456
0
        if (template[0].ulValueLen < sizeof(CK_BBOOL)) {
1457
0
            template[0].ulValueLen = -1;
1458
0
            return CKR_BUFFER_TOO_SMALL;
1459
0
        }
1460
1461
0
        if ((template[0].type == CKA_PRIVATE) &&
1462
0
            (handle->type != SFTK_KEYDB_TYPE)) {
1463
0
            boolVal = CK_FALSE;
1464
0
        }
1465
0
        if ((template[0].type == CKA_SENSITIVE) &&
1466
0
            (handle->type != SFTK_KEYDB_TYPE)) {
1467
0
            boolVal = CK_FALSE;
1468
0
        }
1469
0
        *(CK_BBOOL *)template[0].pValue = boolVal;
1470
0
        template[0].ulValueLen = sizeof(CK_BBOOL);
1471
0
        return CKR_OK;
1472
0
    }
1473
1474
0
    db = SFTK_GET_SDB(handle);
1475
    /* nothing to do */
1476
0
    if (count == 0) {
1477
0
        return CKR_OK;
1478
0
    }
1479
0
    ntemplate = sftkdb_fixupTemplateIn(template, count, &data, &dataSize);
1480
0
    if (ntemplate == NULL) {
1481
0
        return CKR_HOST_MEMORY;
1482
0
    }
1483
0
    objectID &= SFTK_OBJ_ID_MASK;
1484
0
    crv = (*db->sdb_GetAttributeValue)(db, objectID,
1485
0
                                       ntemplate, count);
1486
0
    crv2 = sftkdb_fixupTemplateOut(template, objectID, ntemplate,
1487
0
                                   count, handle);
1488
0
    if (crv == CKR_OK)
1489
0
        crv = crv2;
1490
0
    if (data) {
1491
0
        PORT_Free(ntemplate);
1492
0
        PORT_ZFree(data, dataSize);
1493
0
    }
1494
0
    return crv;
1495
0
}
1496
1497
CK_RV
1498
sftkdb_SetAttributeValue(SFTKDBHandle *handle, SFTKObject *object,
1499
                         const CK_ATTRIBUTE *template, CK_ULONG count)
1500
0
{
1501
0
    CK_ATTRIBUTE *ntemplate;
1502
0
    unsigned char *data = NULL;
1503
0
    PLArenaPool *arena = NULL;
1504
0
    SDB *db;
1505
0
    CK_RV crv = CKR_OK;
1506
0
    CK_OBJECT_HANDLE objectID = (object->handle & SFTK_OBJ_ID_MASK);
1507
0
    PRBool inTransaction = PR_FALSE;
1508
0
    int dataSize;
1509
1510
0
    if (handle == NULL) {
1511
0
        return CKR_TOKEN_WRITE_PROTECTED;
1512
0
    }
1513
1514
0
    db = SFTK_GET_SDB(handle);
1515
    /* nothing to do */
1516
0
    if (count == 0) {
1517
0
        return CKR_OK;
1518
0
    }
1519
    /*
1520
     * we have opened a new database, but we have not yet updated it. We are
1521
     * still running  pointing to the old database (so the application can
1522
     * still read). We don't want to write to the old database at this point,
1523
     * however, since it leads to user confusion. So at this point we simply
1524
     * require a user login. Let NSS know this so it can prompt the user.
1525
     */
1526
0
    if (db == handle->update) {
1527
0
        return CKR_USER_NOT_LOGGED_IN;
1528
0
    }
1529
1530
0
    ntemplate = sftkdb_fixupTemplateIn(template, count, &data, &dataSize);
1531
0
    if (ntemplate == NULL) {
1532
0
        return CKR_HOST_MEMORY;
1533
0
    }
1534
1535
    /* make sure we don't have attributes that conflict with the existing DB */
1536
0
    crv = sftkdb_checkConflicts(db, object->objclass, ntemplate, count,
1537
0
                                objectID);
1538
0
    if (crv != CKR_OK) {
1539
0
        goto loser;
1540
0
    }
1541
1542
0
    arena = PORT_NewArena(256);
1543
0
    if (arena == NULL) {
1544
0
        crv = CKR_HOST_MEMORY;
1545
0
        goto loser;
1546
0
    }
1547
1548
0
    crv = (*db->sdb_Begin)(db);
1549
0
    if (crv != CKR_OK) {
1550
0
        goto loser;
1551
0
    }
1552
0
    inTransaction = PR_TRUE;
1553
0
    crv = sftkdb_setAttributeValue(arena, handle, db, objectID, ntemplate,
1554
0
                                   count);
1555
0
    if (crv != CKR_OK) {
1556
0
        goto loser;
1557
0
    }
1558
0
    crv = (*db->sdb_Commit)(db);
1559
0
loser:
1560
0
    if (crv != CKR_OK && inTransaction) {
1561
0
        (*db->sdb_Abort)(db);
1562
0
    }
1563
0
    if (data) {
1564
0
        PORT_Free(ntemplate);
1565
0
        PORT_ZFree(data, dataSize);
1566
0
    }
1567
0
    if (arena) {
1568
0
        PORT_FreeArena(arena, PR_FALSE);
1569
0
    }
1570
0
    return crv;
1571
0
}
1572
1573
CK_RV
1574
sftkdb_DestroyObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE objectID,
1575
                     CK_OBJECT_CLASS objclass)
1576
0
{
1577
0
    CK_RV crv = CKR_OK;
1578
0
    SDB *db;
1579
1580
0
    if (handle == NULL) {
1581
0
        return CKR_TOKEN_WRITE_PROTECTED;
1582
0
    }
1583
0
    db = SFTK_GET_SDB(handle);
1584
0
    objectID &= SFTK_OBJ_ID_MASK;
1585
1586
0
    crv = (*db->sdb_Begin)(db);
1587
0
    if (crv != CKR_OK) {
1588
0
        return crv;
1589
0
    }
1590
0
    crv = (*db->sdb_DestroyObject)(db, objectID);
1591
0
    if (crv != CKR_OK) {
1592
0
        goto loser;
1593
0
    }
1594
    /* if the database supports meta data, delete any old signatures
1595
     * that we may have added */
1596
0
    if ((db->sdb_flags & SDB_HAS_META) == SDB_HAS_META) {
1597
0
        SDB *keydb = db;
1598
0
        if (handle->type == SFTK_KEYDB_TYPE) {
1599
            /* delete any private attribute signatures that might exist */
1600
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1601
0
                                                   CKA_VALUE);
1602
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1603
0
                                                   CKA_PRIVATE_EXPONENT);
1604
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1605
0
                                                   CKA_PRIME_1);
1606
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1607
0
                                                   CKA_PRIME_2);
1608
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1609
0
                                                   CKA_EXPONENT_1);
1610
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1611
0
                                                   CKA_EXPONENT_2);
1612
0
            (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1613
0
                                                   CKA_COEFFICIENT);
1614
0
        } else {
1615
0
            keydb = SFTK_GET_SDB(handle->peerDB);
1616
0
        }
1617
        /* now destroy any authenticated attributes that may exist */
1618
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1619
0
                                               CKA_MODULUS);
1620
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1621
0
                                               CKA_PUBLIC_EXPONENT);
1622
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1623
0
                                               CKA_NSS_CERT_SHA1_HASH);
1624
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1625
0
                                               CKA_NSS_CERT_MD5_HASH);
1626
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1627
0
                                               CKA_HASH_OF_CERTIFICATE);
1628
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1629
0
                                               CKA_NAME_HASH_ALGORITHM);
1630
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1631
0
                                               CKA_NSS_TRUST_SERVER_AUTH);
1632
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1633
0
                                               CKA_NSS_TRUST_CLIENT_AUTH);
1634
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1635
0
                                               CKA_NSS_TRUST_EMAIL_PROTECTION);
1636
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1637
0
                                               CKA_NSS_TRUST_CODE_SIGNING);
1638
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1639
0
                                               CKA_NSS_TRUST_STEP_UP_APPROVED);
1640
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1641
0
                                               CKA_PKCS_TRUST_SERVER_AUTH);
1642
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1643
0
                                               CKA_PKCS_TRUST_CLIENT_AUTH);
1644
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1645
0
                                               CKA_PKCS_TRUST_EMAIL_PROTECTION);
1646
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1647
0
                                               CKA_PKCS_TRUST_CODE_SIGNING);
1648
0
        (void)sftkdb_DestroyAttributeSignature(handle, keydb, objectID,
1649
0
                                               CKA_NSS_OVERRIDE_EXTENSIONS);
1650
0
    }
1651
0
    crv = (*db->sdb_Commit)(db);
1652
0
loser:
1653
0
    if (crv != CKR_OK) {
1654
0
        (*db->sdb_Abort)(db);
1655
0
    }
1656
0
    return crv;
1657
0
}
1658
1659
CK_RV
1660
sftkdb_CloseDB(SFTKDBHandle *handle)
1661
0
{
1662
0
#ifdef NO_FORK_CHECK
1663
0
    PRBool parentForkedAfterC_Initialize = PR_FALSE;
1664
0
#endif
1665
0
    if (handle == NULL) {
1666
0
        return CKR_OK;
1667
0
    }
1668
0
    if (handle->update) {
1669
0
        if (handle->db->sdb_SetForkState) {
1670
0
            (*handle->db->sdb_SetForkState)(parentForkedAfterC_Initialize);
1671
0
        }
1672
0
        (*handle->update->sdb_Close)(handle->update);
1673
0
    }
1674
0
    if (handle->db) {
1675
0
        if (handle->db->sdb_SetForkState) {
1676
0
            (*handle->db->sdb_SetForkState)(parentForkedAfterC_Initialize);
1677
0
        }
1678
0
        (*handle->db->sdb_Close)(handle->db);
1679
0
    }
1680
0
    if (handle->passwordLock) {
1681
0
        PZ_Lock(handle->passwordLock);
1682
0
    }
1683
0
    if (handle->passwordKey.data) {
1684
0
        SECITEM_ZfreeItem(&handle->passwordKey, PR_FALSE);
1685
0
    }
1686
0
    if (handle->passwordLock) {
1687
0
        PZ_Unlock(handle->passwordLock);
1688
0
        SKIP_AFTER_FORK(PZ_DestroyLock(handle->passwordLock));
1689
0
    }
1690
0
    if (handle->updatePasswordKey) {
1691
0
        SECITEM_ZfreeItem(handle->updatePasswordKey, PR_TRUE);
1692
0
    }
1693
0
    if (handle->updateID) {
1694
0
        PORT_Free(handle->updateID);
1695
0
    }
1696
0
    PORT_Free(handle);
1697
0
    return CKR_OK;
1698
0
}
1699
1700
/*
1701
 * reset a database to it's uninitialized state.
1702
 */
1703
static CK_RV
1704
sftkdb_ResetDB(SFTKDBHandle *handle)
1705
0
{
1706
0
    CK_RV crv = CKR_OK;
1707
0
    SDB *db;
1708
0
    if (handle == NULL) {
1709
0
        return CKR_TOKEN_WRITE_PROTECTED;
1710
0
    }
1711
0
    db = SFTK_GET_SDB(handle);
1712
0
    crv = (*db->sdb_Begin)(db);
1713
0
    if (crv != CKR_OK) {
1714
0
        goto loser;
1715
0
    }
1716
0
    crv = (*db->sdb_Reset)(db);
1717
0
    if (crv != CKR_OK) {
1718
0
        goto loser;
1719
0
    }
1720
0
    crv = (*db->sdb_Commit)(db);
1721
0
loser:
1722
0
    if (crv != CKR_OK) {
1723
0
        (*db->sdb_Abort)(db);
1724
0
    }
1725
0
    return crv;
1726
0
}
1727
1728
CK_RV
1729
sftkdb_Begin(SFTKDBHandle *handle)
1730
0
{
1731
0
    CK_RV crv = CKR_OK;
1732
0
    SDB *db;
1733
1734
0
    if (handle == NULL) {
1735
0
        return CKR_OK;
1736
0
    }
1737
0
    db = SFTK_GET_SDB(handle);
1738
0
    if (db) {
1739
0
        crv = (*db->sdb_Begin)(db);
1740
0
    }
1741
0
    return crv;
1742
0
}
1743
1744
CK_RV
1745
sftkdb_Commit(SFTKDBHandle *handle)
1746
0
{
1747
0
    CK_RV crv = CKR_OK;
1748
0
    SDB *db;
1749
1750
0
    if (handle == NULL) {
1751
0
        return CKR_OK;
1752
0
    }
1753
0
    db = SFTK_GET_SDB(handle);
1754
0
    if (db) {
1755
0
        (*db->sdb_Commit)(db);
1756
0
    }
1757
0
    return crv;
1758
0
}
1759
1760
CK_RV
1761
sftkdb_Abort(SFTKDBHandle *handle)
1762
0
{
1763
0
    CK_RV crv = CKR_OK;
1764
0
    SDB *db;
1765
1766
0
    if (handle == NULL) {
1767
0
        return CKR_OK;
1768
0
    }
1769
0
    db = SFTK_GET_SDB(handle);
1770
0
    if (db) {
1771
0
        crv = (db->sdb_Abort)(db);
1772
0
    }
1773
0
    return crv;
1774
0
}
1775
1776
/*
1777
 * functions to update the database from an old database
1778
 */
1779
1780
static CK_RV
1781
sftkdb_GetObjectTemplate(SDB *source, CK_OBJECT_HANDLE id,
1782
                         CK_ATTRIBUTE *ptemplate, CK_ULONG *max)
1783
0
{
1784
0
    unsigned int i, j;
1785
0
    CK_RV crv;
1786
1787
0
    if (*max < sftkdb_known_attributes_size) {
1788
0
        *max = sftkdb_known_attributes_size;
1789
0
        return CKR_BUFFER_TOO_SMALL;
1790
0
    }
1791
0
    for (i = 0; i < sftkdb_known_attributes_size; i++) {
1792
0
        ptemplate[i].type = sftkdb_known_attributes[i];
1793
0
        ptemplate[i].pValue = NULL;
1794
0
        ptemplate[i].ulValueLen = 0;
1795
0
    }
1796
1797
0
    crv = (*source->sdb_GetAttributeValue)(source, id,
1798
0
                                           ptemplate, sftkdb_known_attributes_size);
1799
1800
0
    if ((crv != CKR_OK) && (crv != CKR_ATTRIBUTE_TYPE_INVALID)) {
1801
0
        return crv;
1802
0
    }
1803
1804
0
    for (i = 0, j = 0; i < sftkdb_known_attributes_size; i++, j++) {
1805
0
        while (i < sftkdb_known_attributes_size && (ptemplate[i].ulValueLen == -1)) {
1806
0
            i++;
1807
0
        }
1808
0
        if (i >= sftkdb_known_attributes_size) {
1809
0
            break;
1810
0
        }
1811
        /* cheap optimization */
1812
0
        if (i == j) {
1813
0
            continue;
1814
0
        }
1815
0
        ptemplate[j] = ptemplate[i];
1816
0
    }
1817
0
    *max = j;
1818
0
    return CKR_OK;
1819
0
}
1820
1821
static const char SFTKDB_META_UPDATE_TEMPLATE[] = "upd_%s_%s";
1822
1823
/*
1824
 * check to see if we have already updated this database.
1825
 * a NULL updateID means we are trying to do an in place
1826
 * single database update. In that case we have already
1827
 * determined that an update was necessary.
1828
 */
1829
static PRBool
1830
sftkdb_hasUpdate(const char *typeString, SDB *db, const char *updateID)
1831
0
{
1832
0
    char *id;
1833
0
    CK_RV crv;
1834
0
    SECItem dummy = { 0, NULL, 0 };
1835
0
    unsigned char dummyData[SDB_MAX_META_DATA_LEN];
1836
1837
0
    if (!updateID) {
1838
0
        return PR_FALSE;
1839
0
    }
1840
0
    id = PR_smprintf(SFTKDB_META_UPDATE_TEMPLATE, typeString, updateID);
1841
0
    if (id == NULL) {
1842
0
        return PR_FALSE;
1843
0
    }
1844
0
    dummy.data = dummyData;
1845
0
    dummy.len = sizeof(dummyData);
1846
1847
0
    crv = (*db->sdb_GetMetaData)(db, id, &dummy, NULL);
1848
0
    PR_smprintf_free(id);
1849
0
    return crv == CKR_OK ? PR_TRUE : PR_FALSE;
1850
0
}
1851
1852
/*
1853
 * we just completed an update, store the update id
1854
 * so we don't need to do it again. If non was given,
1855
 * there is nothing to do.
1856
 */
1857
static CK_RV
1858
sftkdb_putUpdate(const char *typeString, SDB *db, const char *updateID)
1859
0
{
1860
0
    char *id;
1861
0
    CK_RV crv;
1862
0
    SECItem dummy = { 0, NULL, 0 };
1863
1864
    /* if no id was given, nothing to do */
1865
0
    if (updateID == NULL) {
1866
0
        return CKR_OK;
1867
0
    }
1868
1869
0
    dummy.data = (unsigned char *)updateID;
1870
0
    dummy.len = PORT_Strlen(updateID);
1871
1872
0
    id = PR_smprintf(SFTKDB_META_UPDATE_TEMPLATE, typeString, updateID);
1873
0
    if (id == NULL) {
1874
0
        return PR_FALSE;
1875
0
    }
1876
1877
0
    crv = (*db->sdb_PutMetaData)(db, id, &dummy, NULL);
1878
0
    PR_smprintf_free(id);
1879
0
    return crv;
1880
0
}
1881
1882
/*
1883
 * get a ULong attribute from a template:
1884
 * NOTE: this is a raw templated stored in database order!
1885
 */
1886
static CK_ULONG
1887
sftkdb_getULongFromTemplate(CK_ATTRIBUTE_TYPE type,
1888
                            CK_ATTRIBUTE *ptemplate, CK_ULONG len)
1889
0
{
1890
0
    CK_ATTRIBUTE *attr = sftkdb_getAttributeFromTemplate(type,
1891
0
                                                         ptemplate, len);
1892
1893
0
    if (attr && attr->pValue && attr->ulValueLen == SDB_ULONG_SIZE) {
1894
0
        return sftk_SDBULong2ULong(attr->pValue);
1895
0
    }
1896
0
    return (CK_ULONG)-1;
1897
0
}
1898
1899
static CK_RV
1900
sftkdb_setULongInTemplate(CK_ATTRIBUTE *ptemplate, CK_ULONG value)
1901
0
{
1902
0
    if ((ptemplate->ulValueLen < SDB_ULONG_SIZE) || !ptemplate->pValue) {
1903
0
        return CKR_TEMPLATE_INCOMPLETE;
1904
0
    }
1905
0
    ptemplate->ulValueLen = SDB_ULONG_SIZE;
1906
0
    sftk_ULong2SDBULong(ptemplate->pValue, value);
1907
0
    return CKR_OK;
1908
0
}
1909
1910
/*
1911
 * we need to find a unique CKA_ID.
1912
 *  The basic idea is to just increment the lowest byte.
1913
 *  This code also handles the following corner cases:
1914
 *   1) the single byte overflows. On overflow we increment the next byte up
1915
 *    and so forth until we have overflowed the entire CKA_ID.
1916
 *   2) If we overflow the entire CKA_ID we expand it by one byte.
1917
 *   3) the CKA_ID is non-existant, we create a new one with one byte.
1918
 *    This means no matter what CKA_ID is passed, the result of this function
1919
 *    is always a new CKA_ID, and this function will never return the same
1920
 *    CKA_ID the it has returned in the passed.
1921
 */
1922
static CK_RV
1923
sftkdb_incrementCKAID(PLArenaPool *arena, CK_ATTRIBUTE *ptemplate)
1924
0
{
1925
0
    unsigned char *buf = ptemplate->pValue;
1926
0
    CK_ULONG len = ptemplate->ulValueLen;
1927
1928
0
    if (buf == NULL || len == (CK_ULONG)-1) {
1929
        /* we have no valid CKAID, we'll create a basic one byte CKA_ID below */
1930
0
        len = 0;
1931
0
    } else {
1932
0
        CK_ULONG i;
1933
1934
        /* walk from the back to front, incrementing
1935
         * the CKA_ID until we no longer have a carry,
1936
         * or have hit the front of the id. */
1937
0
        for (i = len; i != 0; i--) {
1938
0
            buf[i - 1]++;
1939
0
            if (buf[i - 1] != 0) {
1940
                /* no more carries, the increment is complete */
1941
0
                return CKR_OK;
1942
0
            }
1943
0
        }
1944
        /* we've now overflowed, fall through and expand the CKA_ID by
1945
         * one byte */
1946
0
    }
1947
0
    buf = PORT_ArenaAlloc(arena, len + 1);
1948
0
    if (!buf) {
1949
0
        return CKR_HOST_MEMORY;
1950
0
    }
1951
0
    if (len > 0) {
1952
0
        PORT_Memcpy(buf, ptemplate->pValue, len);
1953
0
    }
1954
0
    buf[len] = 0;
1955
0
    ptemplate->pValue = buf;
1956
0
    ptemplate->ulValueLen = len + 1;
1957
0
    return CKR_OK;
1958
0
}
1959
1960
/*
1961
 * drop an attribute from a template.
1962
 */
1963
void
1964
sftkdb_dropAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE *ptemplate,
1965
                     CK_ULONG *plen)
1966
0
{
1967
0
    CK_ULONG count = *plen;
1968
0
    CK_ULONG i;
1969
1970
0
    for (i = 0; i < count; i++) {
1971
0
        if (attr->type == ptemplate[i].type) {
1972
0
            break;
1973
0
        }
1974
0
    }
1975
1976
0
    if (i == count) {
1977
        /* attribute not found */
1978
0
        return;
1979
0
    }
1980
1981
    /* copy the remaining attributes up */
1982
0
    for (i++; i < count; i++) {
1983
0
        ptemplate[i - 1] = ptemplate[i];
1984
0
    }
1985
1986
    /* decrement the template size */
1987
0
    *plen = count - 1;
1988
0
}
1989
1990
/*
1991
 * create some defines for the following functions to document the meaning
1992
 * of true/false. (make's it easier to remember what means what.
1993
 */
1994
typedef enum {
1995
    SFTKDB_DO_NOTHING = 0,
1996
    SFTKDB_ADD_OBJECT,
1997
    SFTKDB_MODIFY_OBJECT,
1998
    SFTKDB_DROP_ATTRIBUTE
1999
} sftkdbUpdateStatus;
2000
2001
/*
2002
 * helper function to reconcile a single trust entry.
2003
 *   Identify which trust entry we want to keep.
2004
 *   If we don't need to do anything (the records are already equal).
2005
 *       return SFTKDB_DO_NOTHING.
2006
 *   If we want to use the source version,
2007
 *       return SFTKDB_MODIFY_OBJECT
2008
 *   If we want to use the target version,
2009
 *       return SFTKDB_DROP_ATTRIBUTE
2010
 *
2011
 *   In the end the caller will remove any attributes in the source
2012
 *   template when SFTKDB_DROP_ATTRIBUTE is specified, then use do a
2013
 *   set attributes with that template on the target if we received
2014
 *   any SFTKDB_MODIFY_OBJECT returns.
2015
 */
2016
sftkdbUpdateStatus
2017
sftkdb_reconcileTrustEntry(PLArenaPool *arena, CK_ATTRIBUTE *target,
2018
                           CK_ATTRIBUTE *source)
2019
0
{
2020
0
    CK_ULONG targetTrust = sftkdb_getULongFromTemplate(target->type,
2021
0
                                                       target, 1);
2022
0
    CK_ULONG sourceTrust = sftkdb_getULongFromTemplate(target->type,
2023
0
                                                       source, 1);
2024
2025
    /*
2026
     * try to pick the best solution between the source and the
2027
     * target. Update the source template if we want the target value
2028
     * to win out. Prefer cases where we don't actually update the
2029
     * trust entry.
2030
     */
2031
2032
    /* they are the same, everything is already kosher */
2033
0
    if (targetTrust == sourceTrust) {
2034
0
        return SFTKDB_DO_NOTHING;
2035
0
    }
2036
2037
    /* handle the case where the source Trust attribute may be a bit
2038
     * flakey */
2039
0
    if (sourceTrust == (CK_ULONG)-1) {
2040
        /*
2041
         * The source Trust is invalid. We know that the target Trust
2042
         * must be valid here, otherwise the above
2043
         * targetTrust == sourceTrust check would have succeeded.
2044
         */
2045
0
        return SFTKDB_DROP_ATTRIBUTE;
2046
0
    }
2047
2048
    /* target is invalid, use the source's idea of the trust value */
2049
0
    if (targetTrust == (CK_ULONG)-1) {
2050
        /* overwriting the target in this case is OK */
2051
0
        return SFTKDB_MODIFY_OBJECT;
2052
0
    }
2053
2054
    /* at this point we know that both attributes exist and have the
2055
     * appropriate length (SDB_ULONG_SIZE). We no longer need to check
2056
     * ulValueLen for either attribute.
2057
     */
2058
0
    if (sourceTrust == CKT_TRUST_UNKNOWN) {
2059
0
        return SFTKDB_DROP_ATTRIBUTE;
2060
0
    }
2061
2062
    /* target has no idea, use the source's idea of the trust value */
2063
0
    if (targetTrust == CKT_TRUST_UNKNOWN) {
2064
        /* overwriting the target in this case is OK */
2065
0
        return SFTKDB_MODIFY_OBJECT;
2066
0
    }
2067
2068
    /* so both the target and the source have some idea of what this
2069
     * trust attribute should be, and neither agree exactly.
2070
     * At this point, we prefer 'hard' attributes over 'soft' ones.
2071
     * 'hard' ones are CKT_TRUSTED, CKT_TRUST_ANCHOR, and
2072
     * CKT_NSS_NOT_TRUTED. Soft ones are ones which don't change the
2073
     * actual trust of the cert (CKT_TRUST_MUST_VERIFY_TRUST).
2074
     */
2075
0
    if (sourceTrust == CKT_TRUST_MUST_VERIFY_TRUST) {
2076
0
        return SFTKDB_DROP_ATTRIBUTE;
2077
0
    }
2078
0
    if (targetTrust == CKT_TRUST_MUST_VERIFY_TRUST) {
2079
        /* again, overwriting the target in this case is OK */
2080
0
        return SFTKDB_MODIFY_OBJECT;
2081
0
    }
2082
2083
    /* both have hard attributes, we have a conflict, let the target win. */
2084
0
    return SFTKDB_DROP_ATTRIBUTE;
2085
0
}
2086
2087
/* map the attribute types */
2088
CK_TRUST
2089
sftkdb_mapNSSTrustValueToPKCS11TrustValue(CK_TRUST trust)
2090
0
{
2091
0
    switch (trust) {
2092
0
        case CKT_NSS_TRUSTED:
2093
0
            return CKT_TRUSTED;
2094
0
        case CKT_NSS_TRUSTED_DELEGATOR:
2095
0
            return CKT_TRUST_ANCHOR;
2096
0
        case CKT_NSS_VALID_DELEGATOR:
2097
0
        case CKT_NSS_MUST_VERIFY_TRUST:
2098
0
            return CKT_TRUST_MUST_VERIFY_TRUST;
2099
0
        case CKT_NSS_NOT_TRUSTED:
2100
0
            return CKT_NOT_TRUSTED;
2101
0
        case CKT_NSS_TRUST_UNKNOWN:
2102
0
            return CKT_TRUST_UNKNOWN;
2103
0
        default:
2104
0
            break;
2105
0
    }
2106
0
    return CKT_TRUST_UNKNOWN; /* everything else, just copy */
2107
0
}
2108
2109
/* map the attribute types */
2110
CK_ATTRIBUTE_TYPE
2111
sftkdb_mapNSSTrustAttributeTypeToTrustAttributeType(CK_ATTRIBUTE_TYPE type)
2112
0
{
2113
0
    switch (type) {
2114
0
        case CKA_NSS_CERT_SHA1_HASH:
2115
0
            return CKA_HASH_OF_CERTIFICATE;
2116
0
        case CKA_NSS_TRUST_SERVER_AUTH:
2117
0
            return CKA_PKCS_TRUST_SERVER_AUTH;
2118
0
        case CKA_NSS_TRUST_CLIENT_AUTH:
2119
0
            return CKA_PKCS_TRUST_CLIENT_AUTH;
2120
0
        case CKA_NSS_TRUST_CODE_SIGNING:
2121
0
            return CKA_PKCS_TRUST_CODE_SIGNING;
2122
0
        case CKA_NSS_TRUST_EMAIL_PROTECTION:
2123
0
            return CKA_PKCS_TRUST_EMAIL_PROTECTION;
2124
0
        case CKA_NSS_TRUST_IPSEC_TUNNEL:
2125
0
            return CKA_TRUST_IPSEC_IKE;
2126
0
        case CKA_NSS_TRUST_TIME_STAMPING:
2127
0
            return CKA_PKCS_TRUST_TIME_STAMPING;
2128
0
        default:
2129
0
            break;
2130
0
    }
2131
0
    return type; /* everything else, just copy */
2132
0
}
2133
2134
/* these attributes have no mappings, just drop them */
2135
PRBool
2136
sftkdb_dropTrustAttribute(CK_ATTRIBUTE_TYPE type)
2137
0
{
2138
0
    switch (type) {
2139
0
        case CKA_NSS_CERT_MD5_HASH:
2140
0
        case CKA_NSS_TRUST_DIGITAL_SIGNATURE:
2141
0
        case CKA_NSS_TRUST_NON_REPUDIATION:
2142
0
        case CKA_NSS_TRUST_KEY_ENCIPHERMENT:
2143
0
        case CKA_NSS_TRUST_DATA_ENCIPHERMENT:
2144
0
        case CKA_NSS_TRUST_KEY_AGREEMENT:
2145
0
        case CKA_NSS_TRUST_KEY_CERT_SIGN:
2146
0
        case CKA_NSS_TRUST_CRL_SIGN:
2147
0
        case CKA_NSS_TRUST_IPSEC_END_SYSTEM:
2148
0
        case CKA_NSS_TRUST_IPSEC_USER:
2149
0
        case CKA_NSS_TRUST_STEP_UP_APPROVED:
2150
0
            return PR_TRUE;
2151
0
    }
2152
0
    return PR_FALSE;
2153
0
}
2154
2155
CK_RV
2156
sftkdb_mapTrustAttribute(CK_ATTRIBUTE *attr)
2157
0
{
2158
0
    CK_ATTRIBUTE_TYPE oldType = attr->type;
2159
0
    attr->type = sftkdb_mapNSSTrustAttributeTypeToTrustAttributeType(attr->type);
2160
0
    if ((attr->type != oldType) && (attr->ulValueLen == SDB_ULONG_SIZE)) {
2161
0
        CK_TRUST oldTrust = sftkdb_getULongFromTemplate(attr->type, attr, 1);
2162
0
        CK_TRUST newTrust = sftkdb_mapNSSTrustValueToPKCS11TrustValue(oldTrust);
2163
0
        return sftkdb_setULongInTemplate(attr, newTrust);
2164
0
    }
2165
0
    return CKR_OK;
2166
0
}
2167
2168
/*
2169
 * take an NSS vendor specific trust object and map it to the
2170
 * standard PKCS trust object. If the template includes attributes
2171
 * that have not be mapped to PKCS then those attributes may be dropped.
2172
 */
2173
CK_RV
2174
sftkdb_mapNSSTrustToPKCS11Trust(CK_ATTRIBUTE *trustTemplate,
2175
                                CK_ULONG *templateCountPtr)
2176
0
{
2177
0
    CK_ULONG i;
2178
0
    CK_ULONG originalCount = *templateCountPtr;
2179
0
    void *space = NULL;
2180
0
    int hasCertificateHash = 0;
2181
0
    CK_RV crv;
2182
2183
0
    for (i = 0; i < *templateCountPtr; i++) {
2184
0
        CK_ATTRIBUTE *attr = &trustTemplate[i];
2185
0
        if (sftkdb_dropTrustAttribute(attr->type)) {
2186
            /* if there's a enough space to store a ulong, hang
2187
             * onto it. We will probably need it tostore
2188
             * CKA_NAME_HASH_ALGORITHM */
2189
0
            if (!space && attr->ulValueLen >= SDB_ULONG_SIZE) {
2190
0
                space = attr->pValue;
2191
0
            }
2192
0
            sftkdb_dropAttribute(attr, trustTemplate, templateCountPtr);
2193
0
            continue;
2194
0
        }
2195
0
        crv = sftkdb_mapTrustAttribute(attr);
2196
0
        if (crv != CKR_OK) {
2197
0
            return crv;
2198
0
        }
2199
0
        if (attr->type == CKA_HASH_OF_CERTIFICATE) {
2200
0
            hasCertificateHash++;
2201
0
        }
2202
0
    }
2203
    /* if we have CKA_HASH_OF_CERTIFICATE, then we need to add
2204
     * CKA_NAME_HASH_ALGORITHM. We can only do that if we have dropped
2205
     * an attribute because we can't expand the template. This shouldn't
2206
     * be a problem because in a normal template we'll have a CKA_CERT_HASH_MD5
2207
     * attribute and a CKA_NSS_TRUST_STEP_UP_APPROVED attribute */
2208
0
    if (hasCertificateHash) {
2209
0
        if ((*templateCountPtr >= originalCount) || !space) {
2210
0
            return CKR_TEMPLATE_INCOMPLETE;
2211
0
        }
2212
0
        i = (*templateCountPtr)++;
2213
0
        trustTemplate[i].type = CKA_NAME_HASH_ALGORITHM;
2214
0
        trustTemplate[i].pValue = space;
2215
0
        trustTemplate[i].ulValueLen = SDB_ULONG_SIZE;
2216
0
        return sftkdb_setULongInTemplate(&trustTemplate[i], CKM_SHA_1);
2217
0
    }
2218
0
    return CKR_OK;
2219
0
}
2220
2221
const CK_ATTRIBUTE_TYPE sftkdb_nssTrustList[] = { CKA_NSS_TRUST_SERVER_AUTH,
2222
                                                  CKA_NSS_TRUST_CLIENT_AUTH,
2223
                                                  CKA_NSS_TRUST_CODE_SIGNING,
2224
                                                  CKA_NSS_TRUST_EMAIL_PROTECTION,
2225
                                                  CKA_NSS_TRUST_IPSEC_TUNNEL,
2226
                                                  CKA_NSS_TRUST_TIME_STAMPING };
2227
2228
const CK_ATTRIBUTE_TYPE sftkdb_trustList[] = { CKA_PKCS_TRUST_SERVER_AUTH,
2229
                                               CKA_PKCS_TRUST_CLIENT_AUTH,
2230
                                               CKA_PKCS_TRUST_CODE_SIGNING,
2231
                                               CKA_PKCS_TRUST_EMAIL_PROTECTION,
2232
                                               CKA_TRUST_IPSEC_IKE,
2233
                                               CKA_PKCS_TRUST_TIME_STAMPING };
2234
2235
#define SFTK_TRUST_TEMPLATE_COUNT \
2236
0
    (sizeof(sftkdb_trustList) / sizeof(sftkdb_trustList[0]))
2237
/*
2238
 * Run through the list of known trust types, and reconcile each trust
2239
 * entry one by one. Keep track of we really need to write out the source
2240
 * trust object (overwriting the existing one).
2241
 */
2242
static sftkdbUpdateStatus
2243
sftkdb_reconcileTrust(PLArenaPool *arena, SDB *db, CK_OBJECT_HANDLE id,
2244
                      PRBool useLegacy, CK_ATTRIBUTE *ptemplate,
2245
                      CK_ULONG *plen)
2246
0
{
2247
0
    CK_ATTRIBUTE trustTemplate[SFTK_TRUST_TEMPLATE_COUNT];
2248
0
    unsigned char trustData[SFTK_TRUST_TEMPLATE_COUNT * SDB_ULONG_SIZE];
2249
0
    sftkdbUpdateStatus update = useLegacy ? SFTKDB_DO_NOTHING
2250
0
                                          : SFTKDB_MODIFY_OBJECT;
2251
0
    const CK_ULONG templateCount = PR_ARRAY_SIZE(sftkdb_trustList);
2252
0
    CK_ULONG i;
2253
0
    CK_RV crv;
2254
2255
    /* make sure the two arrays are the same size */
2256
0
    PR_STATIC_ASSERT(PR_ARRAY_SIZE(sftkdb_trustList) == PR_ARRAY_SIZE(sftkdb_nssTrustList));
2257
0
    for (i = 0; i < SFTK_TRUST_TEMPLATE_COUNT; i++) {
2258
0
        trustTemplate[i].type = useLegacy ? sftkdb_nssTrustList[i]
2259
0
                                          : sftkdb_trustList[i];
2260
0
        trustTemplate[i].pValue = &trustData[i * SDB_ULONG_SIZE];
2261
0
        trustTemplate[i].ulValueLen = SDB_ULONG_SIZE;
2262
0
    }
2263
0
    crv = (*db->sdb_GetAttributeValue)(db, id,
2264
0
                                       trustTemplate, templateCount);
2265
0
    if ((crv != CKR_OK) && (crv != CKR_ATTRIBUTE_TYPE_INVALID)) {
2266
        /* target trust has some problems, update it */
2267
0
        update = SFTKDB_MODIFY_OBJECT;
2268
0
        goto done;
2269
0
    }
2270
2271
0
    if (useLegacy) {
2272
0
        CK_ULONG count = templateCount;
2273
0
        crv = sftkdb_mapNSSTrustToPKCS11Trust(trustTemplate, &count);
2274
0
        PORT_Assert((count == templateCount) && (crv != CKR_OK));
2275
0
        if ((count == templateCount) && (crv != CKR_OK)) {
2276
0
            return SFTKDB_DO_NOTHING;
2277
0
        }
2278
0
    }
2279
2280
0
    for (i = 0; i < templateCount; i++) {
2281
0
        CK_ATTRIBUTE *attr = sftkdb_getAttributeFromTemplate(
2282
0
            trustTemplate[i].type, ptemplate, *plen);
2283
0
        sftkdbUpdateStatus status;
2284
2285
        /* if target trust value doesn't exist, nothing to merge */
2286
0
        if (trustTemplate[i].ulValueLen == (CK_ULONG)-1) {
2287
            /* if the source exists, then we want the source entry,
2288
             * go ahead and update */
2289
0
            if (attr && attr->ulValueLen != (CK_ULONG)-1) {
2290
0
                update = SFTKDB_MODIFY_OBJECT;
2291
0
            }
2292
0
            continue;
2293
0
        }
2294
2295
        /*
2296
         * the source doesn't have the attribute, go to the next attribute
2297
         */
2298
0
        if (attr == NULL) {
2299
0
            continue;
2300
0
        }
2301
0
        status = sftkdb_reconcileTrustEntry(arena, &trustTemplate[i], attr);
2302
0
        if (useLegacy) {
2303
            /* in the legacy case we are always modifying the object because
2304
             * we are updating to the new attribute type */
2305
0
            if (status == SFTKDB_DROP_ATTRIBUTE) {
2306
                /* rather than drop the attribute, we need to copy the
2307
                 * updated destination attribute */
2308
0
                *attr = trustTemplate[i];
2309
0
            }
2310
            /* SFTKDB_MODIFY_OBJECT - we are already modifying the object,
2311
             * do nothing */
2312
            /* SFTKDB_NO_NOTHING, both source and target already have the
2313
             * correct attribute, so no need to copy */
2314
0
        } else {
2315
            /* not legacy, so the target will be updated in place
2316
             * if necessary */
2317
0
            if (status == SFTKDB_MODIFY_OBJECT) {
2318
                /* we need to write the source version of this attribute
2319
                 * to the target, we need to modify the object */
2320
0
                update = SFTKDB_MODIFY_OBJECT;
2321
0
            } else if (status == SFTKDB_DROP_ATTRIBUTE) {
2322
                /* drop the source copy of the attribute, we are going with
2323
                 * the target's version. This allows us to modify other
2324
                 * attributes if we need to. */
2325
0
                sftkdb_dropAttribute(attr, ptemplate, plen);
2326
0
            }
2327
            /* SFTKDB_NO_NOTHING, both source and target already have the
2328
             * correct attribute, so no need to or drop anything */
2329
0
        }
2330
0
    }
2331
2332
    /* we don't support step-up in the PKCS version, so don't do anything with
2333
     * step-up */
2334
2335
0
done:
2336
0
    return update;
2337
0
}
2338
2339
static sftkdbUpdateStatus
2340
sftkdb_handleIDAndName(PLArenaPool *arena, SDB *db, CK_OBJECT_HANDLE id,
2341
                       CK_ATTRIBUTE *ptemplate, CK_ULONG *plen)
2342
0
{
2343
0
    sftkdbUpdateStatus update = SFTKDB_DO_NOTHING;
2344
0
    CK_ATTRIBUTE *attr1, *attr2;
2345
0
    CK_ATTRIBUTE ttemplate[2] = {
2346
0
        { CKA_ID, NULL, 0 },
2347
0
        { CKA_LABEL, NULL, 0 }
2348
0
    };
2349
2350
0
    attr1 = sftkdb_getAttributeFromTemplate(CKA_LABEL, ptemplate, *plen);
2351
0
    attr2 = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, *plen);
2352
2353
    /* if the source has neither an id nor label, don't bother updating */
2354
0
    if ((!attr1 || attr1->ulValueLen == 0) &&
2355
0
        (!attr2 || attr2->ulValueLen == 0)) {
2356
0
        return SFTKDB_DO_NOTHING;
2357
0
    }
2358
2359
    /* the source has either an id or a label, see what the target has */
2360
0
    (void)(*db->sdb_GetAttributeValue)(db, id, ttemplate, 2);
2361
2362
    /* if the target has neither, update from the source */
2363
0
    if (((ttemplate[0].ulValueLen == 0) ||
2364
0
         (ttemplate[0].ulValueLen == (CK_ULONG)-1)) &&
2365
0
        ((ttemplate[1].ulValueLen == 0) ||
2366
0
         (ttemplate[1].ulValueLen == (CK_ULONG)-1))) {
2367
0
        return SFTKDB_MODIFY_OBJECT;
2368
0
    }
2369
2370
    /* check the CKA_ID */
2371
0
    if ((ttemplate[0].ulValueLen != 0) &&
2372
0
        (ttemplate[0].ulValueLen != (CK_ULONG)-1)) {
2373
        /* we have a CKA_ID in the target, don't overwrite
2374
         * the target with an empty CKA_ID from the source*/
2375
0
        if (attr1 && attr1->ulValueLen == 0) {
2376
0
            sftkdb_dropAttribute(attr1, ptemplate, plen);
2377
0
        }
2378
0
    } else if (attr1 && attr1->ulValueLen != 0) {
2379
        /* source has a CKA_ID, but the target doesn't, update the target */
2380
0
        update = SFTKDB_MODIFY_OBJECT;
2381
0
    }
2382
2383
    /* check the nickname */
2384
0
    if ((ttemplate[1].ulValueLen != 0) &&
2385
0
        (ttemplate[1].ulValueLen != (CK_ULONG)-1)) {
2386
2387
        /* we have a nickname in the target, and we don't have to update
2388
         * the CKA_ID. We are done. NOTE: if we add addition attributes
2389
         * in this check, this shortcut can only go on the last of them. */
2390
0
        if (update == SFTKDB_DO_NOTHING) {
2391
0
            return update;
2392
0
        }
2393
        /* we have a nickname in the target, don't overwrite
2394
         * the target with an empty nickname from the source */
2395
0
        if (attr2 && attr2->ulValueLen == 0) {
2396
0
            sftkdb_dropAttribute(attr2, ptemplate, plen);
2397
0
        }
2398
0
    } else if (attr2 && attr2->ulValueLen != 0) {
2399
        /* source has a nickname, but the target doesn't, update the target */
2400
0
        update = SFTKDB_MODIFY_OBJECT;
2401
0
    }
2402
2403
0
    return update;
2404
0
}
2405
2406
/*
2407
 * This function updates the template before we write the object out.
2408
 *
2409
 * If we are going to skip updating this object, return PR_FALSE.
2410
 * If it should be updated we return PR_TRUE.
2411
 * To help readability, these have been defined
2412
 * as SFTK_DONT_UPDATE and SFTK_UPDATE respectively.
2413
 */
2414
static PRBool
2415
sftkdb_updateObjectTemplate(PLArenaPool *arena, SDB *db,
2416
                            CK_OBJECT_CLASS objectType,
2417
                            CK_ATTRIBUTE *ptemplate, CK_ULONG *plen,
2418
                            CK_OBJECT_HANDLE *targetID)
2419
0
{
2420
0
    PRBool done; /* should we repeat the loop? */
2421
0
    CK_OBJECT_HANDLE id;
2422
0
    CK_RV crv = CKR_OK;
2423
2424
0
    do {
2425
0
        crv = sftkdb_checkConflicts(db, objectType, ptemplate,
2426
0
                                    *plen, CK_INVALID_HANDLE);
2427
0
        if (crv != CKR_ATTRIBUTE_VALUE_INVALID) {
2428
0
            break;
2429
0
        }
2430
0
        crv = sftkdb_resolveConflicts(arena, objectType, ptemplate, plen);
2431
0
    } while (crv == CKR_OK);
2432
2433
0
    if (crv != CKR_OK) {
2434
0
        return SFTKDB_DO_NOTHING;
2435
0
    }
2436
2437
0
    if (objectType == CKO_NSS_TRUST) {
2438
0
        sftkdb_mapNSSTrustToPKCS11Trust(ptemplate, plen);
2439
0
        objectType = CKO_TRUST;
2440
0
    }
2441
2442
0
    do {
2443
0
        done = PR_TRUE;
2444
0
        crv = sftkdb_lookupObject(db, objectType, &id, ptemplate, *plen);
2445
0
        if (crv != CKR_OK) {
2446
0
            if (objectType == CKO_TRUST && id == CK_INVALID_HANDLE) {
2447
0
                objectType = CKO_NSS_TRUST;
2448
                /* didn't find a new PKCS #11 Trust object, look for
2449
                 * and NSS Vendor specific Trust Object */
2450
0
                crv = sftkdb_lookupObject(db, CKO_NSS_TRUST, &id,
2451
0
                                          ptemplate, *plen);
2452
0
            }
2453
0
            if (crv != CKR_OK) {
2454
0
                return SFTKDB_DO_NOTHING;
2455
0
            }
2456
0
        }
2457
2458
        /* This object already exists, merge it, don't update */
2459
0
        if (id != CK_INVALID_HANDLE) {
2460
0
            CK_ATTRIBUTE *attr = NULL;
2461
            /* special post processing for attributes */
2462
0
            switch (objectType) {
2463
0
                case CKO_CERTIFICATE:
2464
0
                case CKO_PUBLIC_KEY:
2465
0
                case CKO_PRIVATE_KEY:
2466
                    /* update target's CKA_ID and labels if they don't already
2467
                     * exist */
2468
0
                    *targetID = id;
2469
0
                    return sftkdb_handleIDAndName(arena, db, id, ptemplate, plen);
2470
0
                case CKO_NSS_TRUST:
2471
                    /* if we have conflicting trust object types,
2472
                     * we need to reconcile them */
2473
0
                    *targetID = id;
2474
0
                    return sftkdb_reconcileTrust(arena, db, id, PR_TRUE,
2475
0
                                                 ptemplate, plen);
2476
0
                case CKO_TRUST:
2477
                    /* if we have conflicting trust object types,
2478
                     * we need to reconcile them */
2479
0
                    *targetID = id;
2480
0
                    return sftkdb_reconcileTrust(arena, db, id, PR_FALSE,
2481
0
                                                 ptemplate, plen);
2482
0
                case CKO_SECRET_KEY:
2483
                    /* secret keys in the old database are all sdr keys,
2484
                     * unfortunately they all appear to have the same CKA_ID,
2485
                     * even though they are truly different keys, so we always
2486
                     * want to update these keys, but we need to
2487
                     * give them a new CKA_ID */
2488
                    /* NOTE: this changes ptemplate */
2489
0
                    attr = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, *plen);
2490
0
                    crv = attr ? sftkdb_incrementCKAID(arena, attr)
2491
0
                               : CKR_HOST_MEMORY;
2492
                    /* in the extremely rare event that we needed memory and
2493
                     * couldn't get it, just drop the key */
2494
0
                    if (crv != CKR_OK) {
2495
0
                        return SFTKDB_DO_NOTHING;
2496
0
                    }
2497
0
                    done = PR_FALSE; /* repeat this find loop */
2498
0
                    break;
2499
0
                default:
2500
                    /* for all other objects, if we found the equivalent object,
2501
                     * don't update it */
2502
0
                    return SFTKDB_DO_NOTHING;
2503
0
            }
2504
0
        }
2505
0
    } while (!done);
2506
2507
    /* this object doesn't exist, update it */
2508
0
    return SFTKDB_ADD_OBJECT;
2509
0
}
2510
2511
static CK_RV
2512
sftkdb_updateIntegrity(PLArenaPool *arena, SFTKDBHandle *handle,
2513
                       SDB *source, CK_OBJECT_HANDLE sourceID,
2514
                       SDB *target, CK_OBJECT_HANDLE targetID,
2515
                       CK_ATTRIBUTE *ptemplate, CK_ULONG max_attributes)
2516
0
{
2517
0
    unsigned int i;
2518
0
    CK_RV global_crv = CKR_OK;
2519
2520
    /* if the target doesn't have META data, don't need to do anything */
2521
0
    if ((target->sdb_flags & SDB_HAS_META) == 0) {
2522
0
        return CKR_OK;
2523
0
    }
2524
    /* if the source doesn't have meta data, then the record won't require
2525
     * integrity */
2526
0
    if ((source->sdb_flags & SDB_HAS_META) == 0) {
2527
0
        return CKR_OK;
2528
0
    }
2529
0
    for (i = 0; i < max_attributes; i++) {
2530
0
        CK_ATTRIBUTE *att = &ptemplate[i];
2531
0
        CK_ATTRIBUTE_TYPE type = att->type;
2532
0
        if (sftkdb_isPrivateAttribute(type)) {
2533
            /* copy integrity signatures associated with this record (if any) */
2534
0
            SECItem signature;
2535
0
            unsigned char signData[SDB_MAX_META_DATA_LEN];
2536
0
            CK_RV crv;
2537
2538
0
            signature.data = signData;
2539
0
            signature.len = sizeof(signData);
2540
0
            crv = sftkdb_getRawAttributeSignature(handle, source, sourceID, type,
2541
0
                                                  &signature);
2542
0
            if (crv != CKR_OK) {
2543
                /* old databases don't have signature IDs because they are
2544
                 * 3DES encrypted. Since we know not to look for integrity
2545
                 * for 3DES records it's OK not to find one here. A new record
2546
                 * will be created when we reencrypt using AES CBC */
2547
0
                continue;
2548
0
            }
2549
0
            crv = sftkdb_PutAttributeSignature(handle, target, targetID, type,
2550
0
                                               &signature);
2551
0
            if (crv != CKR_OK) {
2552
                /* we had a signature in the source db, but we couldn't store
2553
                 * it in the target, remember the error so we can report it. */
2554
0
                global_crv = crv;
2555
0
            }
2556
0
        }
2557
0
    }
2558
0
    return global_crv;
2559
0
}
2560
2561
0
#define MAX_ATTRIBUTES 500
2562
static CK_RV
2563
sftkdb_mergeObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE id,
2564
                   SECItem *key)
2565
0
{
2566
0
    CK_ATTRIBUTE template[MAX_ATTRIBUTES];
2567
0
    CK_ATTRIBUTE *ptemplate;
2568
0
    CK_ULONG max_attributes = MAX_ATTRIBUTES;
2569
0
    CK_OBJECT_CLASS objectType;
2570
0
    SDB *source = handle->update;
2571
0
    SDB *target = handle->db;
2572
0
    unsigned int i;
2573
0
    CK_OBJECT_HANDLE newID = CK_INVALID_HANDLE;
2574
0
    CK_RV crv;
2575
0
    PLArenaPool *arena = NULL;
2576
2577
0
    arena = PORT_NewArena(256);
2578
0
    if (arena == NULL) {
2579
0
        return CKR_HOST_MEMORY;
2580
0
    }
2581
2582
0
    ptemplate = &template[0];
2583
0
    id &= SFTK_OBJ_ID_MASK;
2584
0
    crv = sftkdb_GetObjectTemplate(source, id, ptemplate, &max_attributes);
2585
0
    if (crv == CKR_BUFFER_TOO_SMALL) {
2586
0
        ptemplate = PORT_ArenaNewArray(arena, CK_ATTRIBUTE, max_attributes);
2587
0
        if (ptemplate == NULL) {
2588
0
            crv = CKR_HOST_MEMORY;
2589
0
        } else {
2590
0
            crv = sftkdb_GetObjectTemplate(source, id,
2591
0
                                           ptemplate, &max_attributes);
2592
0
        }
2593
0
    }
2594
0
    if (crv != CKR_OK) {
2595
0
        goto loser;
2596
0
    }
2597
2598
0
    for (i = 0; i < max_attributes; i++) {
2599
0
        ptemplate[i].pValue = PORT_ArenaAlloc(arena, ptemplate[i].ulValueLen);
2600
0
        if (ptemplate[i].pValue == NULL) {
2601
0
            crv = CKR_HOST_MEMORY;
2602
0
            goto loser;
2603
0
        }
2604
0
    }
2605
0
    crv = (*source->sdb_GetAttributeValue)(source, id,
2606
0
                                           ptemplate, max_attributes);
2607
0
    if (crv != CKR_OK) {
2608
0
        goto loser;
2609
0
    }
2610
2611
0
    objectType = sftkdb_getULongFromTemplate(CKA_CLASS, ptemplate,
2612
0
                                             max_attributes);
2613
    /*
2614
     * Update Object updates the object template if necessary then returns
2615
     * whether or not we need to actually write the object out to our target
2616
     * database.
2617
     */
2618
0
    if (!handle->updateID) {
2619
0
        crv = sftkdb_CreateObject(arena, handle, target, &newID,
2620
0
                                  ptemplate, max_attributes);
2621
0
    } else {
2622
0
        sftkdbUpdateStatus update_status;
2623
0
        update_status = sftkdb_updateObjectTemplate(arena, target,
2624
0
                                                    objectType, ptemplate, &max_attributes, &newID);
2625
0
        switch (update_status) {
2626
0
            case SFTKDB_ADD_OBJECT:
2627
0
                crv = sftkdb_CreateObject(arena, handle, target, &newID,
2628
0
                                          ptemplate, max_attributes);
2629
0
                break;
2630
0
            case SFTKDB_MODIFY_OBJECT:
2631
0
                crv = sftkdb_setAttributeValue(arena, handle, target,
2632
0
                                               newID, ptemplate, max_attributes);
2633
0
                break;
2634
0
            case SFTKDB_DO_NOTHING:
2635
0
            case SFTKDB_DROP_ATTRIBUTE:
2636
0
                break;
2637
0
        }
2638
0
    }
2639
2640
    /* if keyDB copy any meta data hashes to target, Update for the new
2641
     * object ID */
2642
0
    if (crv == CKR_OK) {
2643
0
        crv = sftkdb_updateIntegrity(arena, handle, source, id, target, newID,
2644
0
                                     ptemplate, max_attributes);
2645
0
    }
2646
2647
0
loser:
2648
0
    if (arena) {
2649
0
        PORT_FreeArena(arena, PR_TRUE);
2650
0
    }
2651
0
    return crv;
2652
0
}
2653
2654
0
#define MAX_IDS 10
2655
/*
2656
 * update a new database from an old one, now that we have the key
2657
 */
2658
CK_RV
2659
sftkdb_Update(SFTKDBHandle *handle, SECItem *key)
2660
0
{
2661
0
    SDBFind *find = NULL;
2662
0
    CK_ULONG idCount = MAX_IDS;
2663
0
    CK_OBJECT_HANDLE ids[MAX_IDS];
2664
0
    SECItem *updatePasswordKey = NULL;
2665
0
    CK_RV crv, crv2;
2666
0
    PRBool inTransaction = PR_FALSE;
2667
0
    unsigned int i;
2668
2669
0
    if (handle == NULL) {
2670
0
        return CKR_OK;
2671
0
    }
2672
0
    if (handle->update == NULL) {
2673
0
        return CKR_OK;
2674
0
    }
2675
    /*
2676
     * put the whole update under a transaction. This allows us to handle
2677
     * any possible race conditions between with the updateID check.
2678
     */
2679
0
    crv = (*handle->db->sdb_Begin)(handle->db);
2680
0
    if (crv != CKR_OK) {
2681
0
        return crv;
2682
0
    }
2683
0
    inTransaction = PR_TRUE;
2684
2685
    /* some one else has already updated this db */
2686
0
    if (sftkdb_hasUpdate(sftkdb_TypeString(handle),
2687
0
                         handle->db, handle->updateID)) {
2688
0
        crv = CKR_OK;
2689
0
        goto done;
2690
0
    }
2691
2692
0
    updatePasswordKey = sftkdb_GetUpdatePasswordKey(handle);
2693
0
    if (updatePasswordKey) {
2694
        /* pass the source DB key to the legacy code,
2695
         * so it can decrypt things */
2696
0
        handle->oldKey = updatePasswordKey;
2697
0
    }
2698
2699
    /* find all the objects */
2700
0
    crv = sftkdb_FindObjectsInit(handle, NULL, 0, &find);
2701
2702
0
    if (crv != CKR_OK) {
2703
0
        goto loser;
2704
0
    }
2705
0
    while ((crv == CKR_OK) && (idCount == MAX_IDS)) {
2706
0
        crv = sftkdb_FindObjects(handle, find, ids, MAX_IDS, &idCount);
2707
0
        for (i = 0; (crv == CKR_OK) && (i < idCount); i++) {
2708
0
            crv = sftkdb_mergeObject(handle, ids[i], key);
2709
0
        }
2710
0
    }
2711
0
    crv2 = sftkdb_FindObjectsFinal(handle, find);
2712
0
    if (crv == CKR_OK)
2713
0
        crv = crv2;
2714
2715
0
loser:
2716
    /* no longer need the old key value */
2717
0
    handle->oldKey = NULL;
2718
2719
    /* update the password - even if we didn't update objects */
2720
0
    if (handle->type == SFTK_KEYDB_TYPE) {
2721
0
        SECItem item1, item2;
2722
0
        unsigned char data1[SDB_MAX_META_DATA_LEN];
2723
0
        unsigned char data2[SDB_MAX_META_DATA_LEN];
2724
2725
0
        item1.data = data1;
2726
0
        item1.len = sizeof(data1);
2727
0
        item2.data = data2;
2728
0
        item2.len = sizeof(data2);
2729
2730
        /* if the target db already has a password, skip this. */
2731
0
        crv = (*handle->db->sdb_GetMetaData)(handle->db, "password",
2732
0
                                             &item1, &item2);
2733
0
        if (crv == CKR_OK) {
2734
0
            goto done;
2735
0
        }
2736
2737
        /* nope, update it from the source */
2738
0
        crv = (*handle->update->sdb_GetMetaData)(handle->update, "password",
2739
0
                                                 &item1, &item2);
2740
0
        if (crv != CKR_OK) {
2741
            /* if we get here, neither the source, nor the target has been initialized
2742
             * with a password entry. Create a metadata table now so that we don't
2743
             * mistake this for a partially updated database */
2744
0
            item1.data[0] = 0;
2745
0
            item2.data[0] = 0;
2746
0
            item1.len = item2.len = 1;
2747
0
            crv = (*handle->db->sdb_PutMetaData)(handle->db, "empty", &item1, &item2);
2748
0
            goto done;
2749
0
        }
2750
0
        crv = (*handle->db->sdb_PutMetaData)(handle->db, "password", &item1,
2751
0
                                             &item2);
2752
0
        if (crv != CKR_OK) {
2753
0
            goto done;
2754
0
        }
2755
0
    }
2756
2757
0
done:
2758
    /* finally mark this up to date db up to date */
2759
    /* some one else has already updated this db */
2760
0
    if (crv == CKR_OK) {
2761
0
        crv = sftkdb_putUpdate(sftkdb_TypeString(handle),
2762
0
                               handle->db, handle->updateID);
2763
0
    }
2764
2765
0
    if (inTransaction) {
2766
0
        if (crv == CKR_OK) {
2767
0
            crv = (*handle->db->sdb_Commit)(handle->db);
2768
0
        } else {
2769
0
            (*handle->db->sdb_Abort)(handle->db);
2770
0
        }
2771
0
    }
2772
0
    if (handle->update) {
2773
0
        (*handle->update->sdb_Close)(handle->update);
2774
0
        handle->update = NULL;
2775
0
    }
2776
0
    if (handle->updateID) {
2777
0
        PORT_Free(handle->updateID);
2778
0
        handle->updateID = NULL;
2779
0
    }
2780
0
    sftkdb_FreeUpdatePasswordKey(handle);
2781
0
    if (updatePasswordKey) {
2782
0
        SECITEM_ZfreeItem(updatePasswordKey, PR_TRUE);
2783
0
    }
2784
0
    handle->updateDBIsInit = PR_FALSE;
2785
0
    return crv;
2786
0
}
2787
2788
/******************************************************************
2789
 * DB handle managing functions.
2790
 *
2791
 * These functions are called by softoken to initialize, acquire,
2792
 * and release database handles.
2793
 */
2794
2795
const char *
2796
sftkdb_GetUpdateID(SFTKDBHandle *handle)
2797
0
{
2798
0
    return handle->updateID;
2799
0
}
2800
2801
/* release a database handle */
2802
void
2803
sftk_freeDB(SFTKDBHandle *handle)
2804
0
{
2805
0
    PRInt32 ref;
2806
2807
0
    if (!handle)
2808
0
        return;
2809
0
    ref = PR_ATOMIC_DECREMENT(&handle->ref);
2810
0
    if (ref == 0) {
2811
0
        sftkdb_CloseDB(handle);
2812
0
    }
2813
0
    return;
2814
0
}
2815
2816
/*
2817
 * acquire a database handle for a certificate db
2818
 * (database for public objects)
2819
 */
2820
SFTKDBHandle *
2821
sftk_getCertDB(SFTKSlot *slot)
2822
0
{
2823
0
    SFTKDBHandle *dbHandle;
2824
2825
0
    PZ_Lock(slot->slotLock);
2826
0
    dbHandle = slot->certDB;
2827
0
    if (dbHandle) {
2828
0
        (void)PR_ATOMIC_INCREMENT(&dbHandle->ref);
2829
0
    }
2830
0
    PZ_Unlock(slot->slotLock);
2831
0
    return dbHandle;
2832
0
}
2833
2834
/*
2835
 * acquire a database handle for a key database
2836
 * (database for private objects)
2837
 */
2838
SFTKDBHandle *
2839
sftk_getKeyDB(SFTKSlot *slot)
2840
0
{
2841
0
    SFTKDBHandle *dbHandle;
2842
2843
0
    SKIP_AFTER_FORK(PZ_Lock(slot->slotLock));
2844
0
    dbHandle = slot->keyDB;
2845
0
    if (dbHandle) {
2846
0
        (void)PR_ATOMIC_INCREMENT(&dbHandle->ref);
2847
0
    }
2848
0
    SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock));
2849
0
    return dbHandle;
2850
0
}
2851
2852
/*
2853
 * acquire the database for a specific object. NOTE: objectID must point
2854
 * to a Token object!
2855
 */
2856
SFTKDBHandle *
2857
sftk_getDBForTokenObject(SFTKSlot *slot, CK_OBJECT_HANDLE objectID)
2858
0
{
2859
0
    SFTKDBHandle *dbHandle;
2860
2861
0
    PZ_Lock(slot->slotLock);
2862
0
    dbHandle = objectID & SFTK_KEYDB_TYPE ? slot->keyDB : slot->certDB;
2863
0
    if (dbHandle) {
2864
0
        (void)PR_ATOMIC_INCREMENT(&dbHandle->ref);
2865
0
    }
2866
0
    PZ_Unlock(slot->slotLock);
2867
0
    return dbHandle;
2868
0
}
2869
2870
/*
2871
 * initialize a new database handle
2872
 */
2873
static SFTKDBHandle *
2874
sftk_NewDBHandle(SDB *sdb, int type, PRBool legacy)
2875
0
{
2876
0
    SFTKDBHandle *handle = PORT_New(SFTKDBHandle);
2877
0
    handle->ref = 1;
2878
0
    handle->db = sdb;
2879
0
    handle->update = NULL;
2880
0
    handle->peerDB = NULL;
2881
0
    handle->newKey = NULL;
2882
0
    handle->oldKey = NULL;
2883
0
    handle->updatePasswordKey = NULL;
2884
0
    handle->updateID = NULL;
2885
0
    handle->type = type;
2886
0
    handle->usesLegacyStorage = legacy;
2887
0
    handle->passwordKey.data = NULL;
2888
0
    handle->passwordKey.len = 0;
2889
0
    handle->passwordLock = NULL;
2890
0
    if (type == SFTK_KEYDB_TYPE) {
2891
0
        handle->passwordLock = PZ_NewLock(nssILockAttribute);
2892
0
    }
2893
0
    sdb->app_private = handle;
2894
0
    return handle;
2895
0
}
2896
2897
/*
2898
 * reset the key database to it's uninitialized state. This call
2899
 * will clear all the key entried.
2900
 */
2901
SECStatus
2902
sftkdb_ResetKeyDB(SFTKDBHandle *handle)
2903
0
{
2904
0
    CK_RV crv;
2905
2906
    /* only rest the key db */
2907
0
    if (handle->type != SFTK_KEYDB_TYPE) {
2908
0
        return SECFailure;
2909
0
    }
2910
0
    crv = sftkdb_ResetDB(handle);
2911
0
    if (crv != CKR_OK) {
2912
        /* set error */
2913
0
        return SECFailure;
2914
0
    }
2915
0
    PZ_Lock(handle->passwordLock);
2916
0
    if (handle->passwordKey.data) {
2917
0
        SECITEM_ZfreeItem(&handle->passwordKey, PR_FALSE);
2918
0
        handle->passwordKey.data = NULL;
2919
0
    }
2920
0
    PZ_Unlock(handle->passwordLock);
2921
0
    return SECSuccess;
2922
0
}
2923
2924
#ifndef NSS_DISABLE_DBM
2925
static PRBool
2926
sftk_oldVersionExists(const char *dir, int version)
2927
{
2928
    int i;
2929
    PRStatus exists = PR_FAILURE;
2930
    char *file = NULL;
2931
2932
    for (i = version; i > 1; i--) {
2933
        file = PR_smprintf("%s%d.db", dir, i);
2934
        if (file == NULL) {
2935
            continue;
2936
        }
2937
        exists = PR_Access(file, PR_ACCESS_EXISTS);
2938
        PR_smprintf_free(file);
2939
        if (exists == PR_SUCCESS) {
2940
            return PR_TRUE;
2941
        }
2942
    }
2943
    return PR_FALSE;
2944
}
2945
2946
#if defined(_WIN32)
2947
/*
2948
 * Convert an sdb path (encoded in UTF-8) to a legacy path (encoded in the
2949
 * current system codepage). Fails if the path contains a character outside
2950
 * the current system codepage.
2951
 */
2952
static char *
2953
sftk_legacyPathFromSDBPath(const char *confdir)
2954
{
2955
    wchar_t *confdirWide;
2956
    DWORD size;
2957
    char *nconfdir;
2958
    BOOL unmappable;
2959
2960
    if (!confdir) {
2961
        return NULL;
2962
    }
2963
    confdirWide = _NSSUTIL_UTF8ToWide(confdir);
2964
    if (!confdirWide) {
2965
        return NULL;
2966
    }
2967
2968
    size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, confdirWide, -1,
2969
                               NULL, 0, NULL, &unmappable);
2970
    if (size == 0 || unmappable) {
2971
        PORT_Free(confdirWide);
2972
        return NULL;
2973
    }
2974
    nconfdir = PORT_Alloc(sizeof(char) * size);
2975
    if (!nconfdir) {
2976
        PORT_Free(confdirWide);
2977
        return NULL;
2978
    }
2979
    size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, confdirWide, -1,
2980
                               nconfdir, size, NULL, &unmappable);
2981
    PORT_Free(confdirWide);
2982
    if (size == 0 || unmappable) {
2983
        PORT_Free(nconfdir);
2984
        return NULL;
2985
    }
2986
2987
    return nconfdir;
2988
}
2989
#else
2990
#define sftk_legacyPathFromSDBPath(confdir) PORT_Strdup((confdir))
2991
#endif
2992
2993
static PRBool
2994
sftk_hasLegacyDB(const char *confdir, const char *certPrefix,
2995
                 const char *keyPrefix, int certVersion, int keyVersion)
2996
{
2997
    char *dir;
2998
    PRBool exists;
2999
3000
    if (certPrefix == NULL) {
3001
        certPrefix = "";
3002
    }
3003
3004
    if (keyPrefix == NULL) {
3005
        keyPrefix = "";
3006
    }
3007
3008
    dir = PR_smprintf("%s/%scert", confdir, certPrefix);
3009
    if (dir == NULL) {
3010
        return PR_FALSE;
3011
    }
3012
3013
    exists = sftk_oldVersionExists(dir, certVersion);
3014
    PR_smprintf_free(dir);
3015
    if (exists) {
3016
        return PR_TRUE;
3017
    }
3018
3019
    dir = PR_smprintf("%s/%skey", confdir, keyPrefix);
3020
    if (dir == NULL) {
3021
        return PR_FALSE;
3022
    }
3023
3024
    exists = sftk_oldVersionExists(dir, keyVersion);
3025
    PR_smprintf_free(dir);
3026
    return exists;
3027
}
3028
#endif /* NSS_DISABLE_DBM */
3029
3030
/*
3031
 * initialize certificate and key database handles as a pair.
3032
 *
3033
 * This function figures out what type of database we are opening and
3034
 * calls the appropriate low level function to open the database.
3035
 * It also figures out whether or not to setup up automatic update.
3036
 */
3037
CK_RV
3038
sftk_DBInit(const char *configdir, const char *certPrefix,
3039
            const char *keyPrefix, const char *updatedir,
3040
            const char *updCertPrefix, const char *updKeyPrefix,
3041
            const char *updateID, PRBool readOnly, PRBool noCertDB,
3042
            PRBool noKeyDB, PRBool forceOpen, PRBool isFIPS,
3043
            SFTKDBHandle **certDB, SFTKDBHandle **keyDB)
3044
0
{
3045
0
    const char *confdir;
3046
0
    NSSDBType dbType = NSS_DB_TYPE_NONE;
3047
0
    char *appName = NULL;
3048
0
    SDB *keySDB, *certSDB;
3049
0
    CK_RV crv = CKR_OK;
3050
0
    int flags = SDB_RDONLY;
3051
0
    PRBool newInit = PR_FALSE;
3052
#ifndef NSS_DISABLE_DBM
3053
    PRBool needUpdate = PR_FALSE;
3054
#endif /* NSS_DISABLE_DBM */
3055
0
    char *nconfdir = NULL;
3056
0
    PRBool legacy = PR_TRUE;
3057
3058
0
    if (!readOnly) {
3059
0
        flags = SDB_CREATE;
3060
0
    }
3061
0
    if (isFIPS) {
3062
0
        flags |= SDB_FIPS;
3063
0
    }
3064
3065
0
    *certDB = NULL;
3066
0
    *keyDB = NULL;
3067
3068
0
    if (noKeyDB && noCertDB) {
3069
0
        return CKR_OK;
3070
0
    }
3071
0
    confdir = _NSSUTIL_EvaluateConfigDir(configdir, &dbType, &appName);
3072
3073
    /*
3074
     * now initialize the appropriate database
3075
     */
3076
0
    switch (dbType) {
3077
#ifndef NSS_DISABLE_DBM
3078
        case NSS_DB_TYPE_LEGACY:
3079
            crv = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags,
3080
                                  noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB);
3081
            break;
3082
        case NSS_DB_TYPE_MULTIACCESS:
3083
            crv = sftkdbCall_open(configdir, certPrefix, keyPrefix, 8, 3, flags,
3084
                                  noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB);
3085
            break;
3086
#endif /* NSS_DISABLE_DBM */
3087
0
        case NSS_DB_TYPE_SQL:
3088
0
        case NSS_DB_TYPE_EXTERN: /* SHOULD open a loadable db */
3089
0
            crv = s_open(confdir, certPrefix, keyPrefix, 9, 4, flags,
3090
0
                         noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB, &newInit);
3091
0
            legacy = PR_FALSE;
3092
3093
#ifndef NSS_DISABLE_DBM
3094
            /*
3095
             * if we failed to open the DB's read only, use the old ones if
3096
             * the exists.
3097
             */
3098
            if (crv != CKR_OK) {
3099
                legacy = PR_TRUE;
3100
                if ((flags & SDB_RDONLY) == SDB_RDONLY) {
3101
                    nconfdir = sftk_legacyPathFromSDBPath(confdir);
3102
                }
3103
                if (nconfdir &&
3104
                    sftk_hasLegacyDB(nconfdir, certPrefix, keyPrefix, 8, 3)) {
3105
                    /* we have legacy databases, if we failed to open the new format
3106
                     * DB's read only, just use the legacy ones */
3107
                    crv = sftkdbCall_open(nconfdir, certPrefix,
3108
                                          keyPrefix, 8, 3, flags,
3109
                                          noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB);
3110
                }
3111
                /* Handle the database merge case.
3112
                 *
3113
                 * For the merge case, we need help from the application. Only
3114
                 * the application knows where the old database is, and what unique
3115
                 * identifier it has associated with it.
3116
                 *
3117
                 * If the client supplies these values, we use them to determine
3118
                 * if we need to update.
3119
                 */
3120
            } else if (
3121
                /* both update params have been supplied */
3122
                updatedir && *updatedir && updateID && *updateID
3123
                /* old dbs exist? */
3124
                && sftk_hasLegacyDB(updatedir, updCertPrefix, updKeyPrefix, 8, 3)
3125
                /* and they have not yet been updated? */
3126
                && ((noKeyDB || !sftkdb_hasUpdate("key", keySDB, updateID)) || (noCertDB || !sftkdb_hasUpdate("cert", certSDB, updateID)))) {
3127
                /* we need to update */
3128
                confdir = updatedir;
3129
                certPrefix = updCertPrefix;
3130
                keyPrefix = updKeyPrefix;
3131
                needUpdate = PR_TRUE;
3132
            } else if (newInit) {
3133
                /* if the new format DB was also a newly created DB, and we
3134
                 * succeeded, then need to update that new database with data
3135
                 * from the existing legacy DB */
3136
                nconfdir = sftk_legacyPathFromSDBPath(confdir);
3137
                if (nconfdir &&
3138
                    sftk_hasLegacyDB(nconfdir, certPrefix, keyPrefix, 8, 3)) {
3139
                    confdir = nconfdir;
3140
                    needUpdate = PR_TRUE;
3141
                }
3142
            }
3143
#endif /* NSS_DISABLE_DBM */
3144
0
            break;
3145
0
        default:
3146
0
            crv = CKR_GENERAL_ERROR; /* can't happen, EvaluationConfigDir MUST
3147
                                      * return one of the types we already
3148
                                      * specified. */
3149
0
    }
3150
0
    if (crv != CKR_OK) {
3151
0
        goto done;
3152
0
    }
3153
0
    if (!noCertDB) {
3154
0
        *certDB = sftk_NewDBHandle(certSDB, SFTK_CERTDB_TYPE, legacy);
3155
0
    } else {
3156
0
        *certDB = NULL;
3157
0
    }
3158
0
    if (!noKeyDB) {
3159
0
        *keyDB = sftk_NewDBHandle(keySDB, SFTK_KEYDB_TYPE, legacy);
3160
0
    } else {
3161
0
        *keyDB = NULL;
3162
0
    }
3163
3164
    /* link them together */
3165
0
    if (*certDB) {
3166
0
        (*certDB)->peerDB = *keyDB;
3167
0
    }
3168
0
    if (*keyDB) {
3169
0
        (*keyDB)->peerDB = *certDB;
3170
0
    }
3171
3172
#ifndef NSS_DISABLE_DBM
3173
    /*
3174
     * if we need to update, open the legacy database and
3175
     * mark the handle as needing update.
3176
     */
3177
    if (needUpdate) {
3178
        SDB *updateCert = NULL;
3179
        SDB *updateKey = NULL;
3180
        CK_RV crv2;
3181
3182
        crv2 = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags,
3183
                               noCertDB ? NULL : &updateCert,
3184
                               noKeyDB ? NULL : &updateKey);
3185
        if (crv2 == CKR_OK) {
3186
            if (*certDB) {
3187
                (*certDB)->update = updateCert;
3188
                (*certDB)->updateID = updateID && *updateID
3189
                                          ? PORT_Strdup(updateID)
3190
                                          : NULL;
3191
                updateCert->app_private = (*certDB);
3192
            }
3193
            if (*keyDB) {
3194
                PRBool tokenRemoved = PR_FALSE;
3195
                (*keyDB)->update = updateKey;
3196
                (*keyDB)->updateID = updateID && *updateID ? PORT_Strdup(updateID) : NULL;
3197
                updateKey->app_private = (*keyDB);
3198
                (*keyDB)->updateDBIsInit = PR_TRUE;
3199
                (*keyDB)->updateDBIsInit =
3200
                    (sftkdb_HasPasswordSet(*keyDB) == SECSuccess) ? PR_TRUE : PR_FALSE;
3201
                /* if the password on the key db is NULL, kick off our update
3202
                 * chain of events */
3203
                sftkdb_CheckPasswordNull((*keyDB), &tokenRemoved);
3204
            } else {
3205
                /* we don't have a key DB, update the certificate DB now */
3206
                sftkdb_Update(*certDB, NULL);
3207
            }
3208
        }
3209
    }
3210
#endif /* NSS_DISABLE_DBM */
3211
3212
0
done:
3213
0
    if (appName) {
3214
0
        PORT_Free(appName);
3215
0
    }
3216
0
    if (nconfdir) {
3217
0
        PORT_Free(nconfdir);
3218
0
    }
3219
0
    return forceOpen ? CKR_OK : crv;
3220
0
}
3221
3222
CK_RV
3223
sftkdb_Shutdown(void)
3224
0
{
3225
0
    s_shutdown();
3226
#ifndef NSS_DISABLE_DBM
3227
    sftkdbCall_Shutdown();
3228
#endif /* NSS_DISABLE_DBM */
3229
0
    return CKR_OK;
3230
0
}