Coverage Report

Created: 2026-11-15 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/softoken/pkcs11u.c
Line
Count
Source
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
 * Internal PKCS #11 functions. Should only be called by pkcs11.c
6
 */
7
#include "pkcs11.h"
8
#include "pkcs11i.h"
9
#include "lowkeyi.h"
10
#include "secasn1.h"
11
#include "blapi.h"
12
#include "secerr.h"
13
#include "prnetdb.h" /* for PR_ntohl */
14
#include "sftkdb.h"
15
#include "softoken.h"
16
#include "secoid.h"
17
#include "softkver.h"
18
19
#if !defined(NSS_FIPS_DISABLED) && defined(NSS_ENABLE_FIPS_INDICATORS)
20
/* handle special cases. Classes require existing code to already be
21
 * in place for that class */
22
typedef enum {
23
    SFTKFIPSNone = 0,
24
    SFTKFIPSDH,           /* allow only specific primes */
25
    SFTKFIPSECC,          /* not just keys but specific curves */
26
    SFTKFIPSAEAD,         /* single shot AEAD functions not allowed in FIPS mode */
27
    SFTKFIPSRSAPSS,       /* make sure salt isn't too big */
28
    SFTKFIPSPBKDF2,       /* handle pbkdf2 FIPS restrictions */
29
    SFTKFIPSTlsKeyCheck,  /* check the output of TLS prf functions */
30
    SFTKFIPSChkHash,      /* make sure the base hash of KDF functions is FIPS */
31
    SFTKFIPSChkHashTls,   /* make sure the base hash of TLS KDF functions is FIPS */
32
    SFTKFIPSChkHashSp800, /* make sure the base hash of SP-800-108 KDF functions is FIPS */
33
    SFTKFIPSRSAOAEP,      /* make sure that both hashes use the same FIPS compliant algorithm */
34
} SFTKFIPSSpecialClass;
35
36
typedef struct SFTKFIPSAlgorithmListStr SFTKFIPSAlgorithmList;
37
struct SFTKFIPSAlgorithmListStr {
38
    CK_MECHANISM_TYPE type;
39
    CK_MECHANISM_INFO info;
40
    CK_ULONG step;
41
    SFTKFIPSSpecialClass special;
42
    size_t offset;
43
};
44
/* this file should be supplied by the vendor and include all the
45
 * algorithms which have Algorithm certs and have been reviewed by
46
 * the lab. A blank file is included for the base so that FIPS mode
47
 * will still be compiled and run, but FIPS indicators will always
48
 * return PR_FALSE
49
 */
50
#include "fips_algorithms.h"
51
52
#ifndef SFTKFIPS_PBKDF2_MIN_PW_LEN /* allow fips_algorithms.h to override */
53
#define SFTKFIPS_PBKDF2_MIN_PW_LEN 8
54
#endif
55
#define NSS_HAS_FIPS_INDICATORS 1
56
#endif
57
58
/*
59
 * ******************** Error mapping *******************************
60
 */
61
/*
62
 * map all the SEC_ERROR_xxx error codes that may be returned by freebl
63
 * functions to CKR_xxx.  return CKR_DEVICE_ERROR by default for backward
64
 * compatibility.
65
 */
66
CK_RV
67
sftk_MapCryptError(int error)
68
98.8k
{
69
98.8k
    switch (error) {
70
67.6k
        case SEC_ERROR_INVALID_ARGS:
71
67.6k
        case SEC_ERROR_BAD_DATA: /* MP_RANGE gets mapped to this */
72
67.6k
            return CKR_ARGUMENTS_BAD;
73
143
        case SEC_ERROR_INPUT_LEN:
74
143
            return CKR_DATA_LEN_RANGE;
75
144
        case SEC_ERROR_OUTPUT_LEN:
76
144
            return CKR_BUFFER_TOO_SMALL;
77
301
        case SEC_ERROR_LIBRARY_FAILURE:
78
301
            return CKR_GENERAL_ERROR;
79
0
        case SEC_ERROR_NO_MEMORY:
80
0
            return CKR_HOST_MEMORY;
81
26.3k
        case SEC_ERROR_BAD_SIGNATURE:
82
26.3k
            return CKR_SIGNATURE_INVALID;
83
0
        case SEC_ERROR_INVALID_KEY:
84
0
            return CKR_KEY_SIZE_RANGE;
85
3.49k
        case SEC_ERROR_BAD_KEY:        /* an EC public key that fails validation */
86
3.49k
            return CKR_KEY_SIZE_RANGE; /* the closest error code */
87
0
        case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM:
88
0
            return CKR_TEMPLATE_INCONSISTENT;
89
0
        case SEC_ERROR_UNSUPPORTED_KEYALG:
90
0
            return CKR_MECHANISM_INVALID;
91
410
        case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE:
92
410
            return CKR_DOMAIN_PARAMS_INVALID;
93
        /* key pair generation failed after max number of attempts */
94
0
        case SEC_ERROR_NEED_RANDOM:
95
0
            return CKR_FUNCTION_FAILED;
96
98.8k
    }
97
386
    return CKR_DEVICE_ERROR;
98
98.8k
}
99
100
/*
101
 * functions which adjust the mapping based on different contexts
102
 * (Decrypt or Verify).
103
 */
104
105
/* used by Decrypt and UnwrapKey (indirectly) and Decrypt message */
106
CK_RV
107
sftk_MapDecryptError(int error)
108
85.7k
{
109
85.7k
    switch (error) {
110
        /* usually a padding error, or aead tag mismatch */
111
18.4k
        case SEC_ERROR_BAD_DATA:
112
18.4k
            return CKR_ENCRYPTED_DATA_INVALID;
113
67.2k
        default:
114
67.2k
            return sftk_MapCryptError(error);
115
85.7k
    }
116
85.7k
}
117
118
/*
119
 * return CKR_SIGNATURE_INVALID instead of CKR_DEVICE_ERROR by default for
120
 * backward compatibilty.
121
 */
122
CK_RV
123
sftk_MapVerifyError(int error)
124
9.79k
{
125
9.79k
    CK_RV crv = sftk_MapCryptError(error);
126
9.79k
    if (crv == CKR_DEVICE_ERROR)
127
0
        crv = CKR_SIGNATURE_INVALID;
128
9.79k
    return crv;
129
9.79k
}
130
131
/*
132
 * ******************** Attribute Utilities *******************************
133
 */
134
135
/*
136
 * create a new attribute with type, value, and length. Space is allocated
137
 * to hold value.
138
 */
139
static SFTKAttribute *
140
sftk_InitAttribute(SFTKSessionObject *so, int index,
141
                   CK_ATTRIBUTE_TYPE type, const void *value, CK_ULONG len)
142
57.5M
{
143
57.5M
    SFTKAttribute *attribute;
144
145
57.5M
    PORT_Assert(index < MAX_OBJS_ATTRS);
146
57.5M
    if (index >= MAX_OBJS_ATTRS)
147
0
        return NULL;
148
149
57.5M
    attribute = &so->attrList[index];
150
57.5M
    attribute->attrib.type = type;
151
57.5M
    attribute->freeAttr = PR_FALSE;
152
57.5M
    attribute->freeData = PR_FALSE;
153
57.5M
    if (value) {
154
46.8M
        if (len <= ATTR_SPACE) {
155
46.6M
            attribute->attrib.pValue = attribute->space;
156
46.6M
        } else {
157
263k
            attribute->attrib.pValue = PORT_Alloc(len);
158
263k
            attribute->freeData = PR_TRUE;
159
263k
        }
160
46.8M
        if (attribute->attrib.pValue == NULL) {
161
0
            return NULL;
162
0
        }
163
46.8M
        PORT_Memcpy(attribute->attrib.pValue, value, len);
164
46.8M
        attribute->attrib.ulValueLen = len;
165
46.8M
    } else {
166
10.6M
        attribute->attrib.pValue = NULL;
167
10.6M
        attribute->attrib.ulValueLen = 0;
168
10.6M
    }
169
57.5M
    attribute->attrib.type = type;
170
57.5M
    attribute->handle = type;
171
57.5M
    attribute->next = attribute->prev = NULL;
172
57.5M
    return attribute;
173
57.5M
}
174
175
static SFTKAttribute *
176
sftk_NewAttribute(SFTKObject *object,
177
                  CK_ATTRIBUTE_TYPE type, const void *value, CK_ULONG len)
178
55.2M
{
179
55.2M
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
180
55.2M
    int index;
181
182
55.2M
    if (so == NULL) {
183
        /* allocate new attribute in a buffer */
184
0
        PORT_Assert(0);
185
0
        return NULL;
186
0
    }
187
    /*
188
     * We attempt to keep down contention on Malloc and Arena locks by
189
     * limiting the number of these calls on high traversed paths. This
190
     * is done for attributes by 'allocating' them from a pool already
191
     * allocated by the parent object.
192
     */
193
55.2M
    PR_Lock(so->attributeLock);
194
55.2M
    index = so->nextAttr++;
195
55.2M
    PR_Unlock(so->attributeLock);
196
55.2M
    return sftk_InitAttribute(so, index, type, value, len);
197
55.2M
}
198
199
/*
200
 * Return whether a non-NULL attribute value must be passed to PORT_Free,
201
 * judged by where pValue points; abort if freeData disagrees. Freeing an
202
 * inline value would hand the allocator a pointer into a live structure,
203
 * which it may treat as freeing the whole structure. If so is not NULL, a
204
 * heap value must also lie outside its attrList.
205
 */
206
static PRBool
207
sftk_attributeOwnsHeapValue(const SFTKSessionObject *so,
208
                            const SFTKAttribute *attribute)
209
69.9M
{
210
69.9M
    uintptr_t value = (uintptr_t)attribute->attrib.pValue;
211
69.9M
    PRBool freeData = attribute->freeData;
212
213
69.9M
    if (value == (uintptr_t)attribute->space) {
214
69.3M
        PORT_ReleaseAssert(freeData == PR_FALSE &&
215
69.3M
                           attribute->attrib.ulValueLen <= ATTR_SPACE);
216
69.3M
        return PR_FALSE;
217
69.3M
    }
218
595k
    PORT_ReleaseAssert(freeData == PR_TRUE);
219
595k
    if (so) {
220
263k
        uintptr_t start = (uintptr_t)so->attrList;
221
263k
        PORT_ReleaseAssert(value < start ||
222
263k
                           value >= start + sizeof(so->attrList));
223
263k
    }
224
595k
    return PR_TRUE;
225
69.9M
}
226
227
/*
228
 * Free up all the memory associated with an attribute. Reference count
229
 * must be zero to call this.
230
 */
231
static void
232
sftk_DestroyAttribute(SFTKAttribute *attribute)
233
18.3M
{
234
18.3M
    if (attribute->attrib.pValue) {
235
18.1M
        PRBool ownsHeapValue = sftk_attributeOwnsHeapValue(NULL, attribute);
236
        /* clear out the data in the attribute value... it may have been
237
         * sensitive data */
238
18.1M
        PORT_Memset(attribute->attrib.pValue, 0, attribute->attrib.ulValueLen);
239
18.1M
        if (ownsHeapValue) {
240
332k
            PORT_Free(attribute->attrib.pValue);
241
332k
            attribute->attrib.pValue = NULL;
242
332k
            attribute->freeData = PR_FALSE;
243
332k
        }
244
18.1M
    }
245
18.3M
    if (attribute->freeAttr) {
246
18.3M
        PORT_Free(attribute);
247
18.3M
    }
248
18.3M
}
249
250
/*
251
 * release a reference to an attribute structure
252
 */
253
void
254
sftk_FreeAttribute(SFTKAttribute *attribute)
255
18.3M
{
256
18.3M
    if (attribute && attribute->freeAttr) {
257
18.3M
        sftk_DestroyAttribute(attribute);
258
18.3M
        return;
259
18.3M
    }
260
18.3M
}
261
262
static SFTKAttribute *
263
sftk_FindTokenAttribute(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type)
264
4.30k
{
265
4.30k
    SFTKAttribute *myattribute = NULL;
266
4.30k
    SFTKDBHandle *dbHandle = NULL;
267
4.30k
    CK_RV crv = CKR_HOST_MEMORY;
268
269
4.30k
    if (object == NULL) {
270
0
        return NULL;
271
0
    }
272
4.30k
    myattribute = (SFTKAttribute *)PORT_Alloc(sizeof(SFTKAttribute));
273
4.30k
    if (myattribute == NULL) {
274
0
        goto loser;
275
0
    }
276
277
4.30k
    dbHandle = sftk_getDBForTokenObject(object->obj.slot, object->obj.handle);
278
279
4.30k
    myattribute->handle = type;
280
4.30k
    myattribute->attrib.type = type;
281
4.30k
    myattribute->attrib.pValue = myattribute->space;
282
4.30k
    myattribute->attrib.ulValueLen = ATTR_SPACE;
283
4.30k
    myattribute->next = myattribute->prev = NULL;
284
4.30k
    myattribute->freeAttr = PR_TRUE;
285
4.30k
    myattribute->freeData = PR_FALSE;
286
287
4.30k
    crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
288
4.30k
                                   &myattribute->attrib, 1);
289
290
    /* attribute is bigger than our attribute space buffer, malloc it */
291
4.30k
    if (crv == CKR_BUFFER_TOO_SMALL) {
292
2.34k
        myattribute->attrib.pValue = NULL;
293
2.34k
        crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
294
2.34k
                                       &myattribute->attrib, 1);
295
2.34k
        if (crv != CKR_OK) {
296
0
            goto loser;
297
0
        }
298
2.34k
        myattribute->attrib.pValue = PORT_Alloc(myattribute->attrib.ulValueLen);
299
2.34k
        if (myattribute->attrib.pValue == NULL) {
300
0
            crv = CKR_HOST_MEMORY;
301
0
            goto loser;
302
0
        }
303
2.34k
        myattribute->freeData = PR_TRUE;
304
2.34k
        crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
305
2.34k
                                       &myattribute->attrib, 1);
306
2.34k
    }
307
4.30k
loser:
308
4.30k
    if (dbHandle) {
309
4.30k
        sftk_freeDB(dbHandle);
310
4.30k
    }
311
4.30k
    if (crv != CKR_OK) {
312
0
        if (myattribute) {
313
0
            myattribute->attrib.ulValueLen = 0;
314
0
            sftk_FreeAttribute(myattribute);
315
0
            myattribute = NULL;
316
0
        }
317
0
    }
318
4.30k
    return myattribute;
319
4.30k
}
320
321
/*
322
 * Make a detached, owned copy of a session object's attribute. Must be
323
 * called with sessObject->attributeLock held so the (pValue, ulValueLen)
324
 * pair is captured atomically with respect to sftk_forceAttribute() and
325
 * friends. The copy carries freeAttr = PR_TRUE, so sftk_FreeAttribute()
326
 * releases it; callers may read it without holding any lock.
327
 */
328
static SFTKAttribute *
329
sftk_CopyAttribute(const SFTKAttribute *attribute)
330
18.3M
{
331
18.3M
    SFTKAttribute *copy = (SFTKAttribute *)PORT_Alloc(sizeof(SFTKAttribute));
332
18.3M
    if (copy == NULL) {
333
0
        return NULL;
334
0
    }
335
18.3M
    copy->next = copy->prev = NULL;
336
18.3M
    copy->freeAttr = PR_TRUE;
337
18.3M
    copy->freeData = PR_FALSE;
338
18.3M
    copy->handle = attribute->handle;
339
18.3M
    copy->attrib.type = attribute->attrib.type;
340
18.3M
    if (attribute->attrib.pValue == NULL) {
341
133k
        copy->attrib.pValue = NULL;
342
133k
        copy->attrib.ulValueLen = 0;
343
133k
        return copy;
344
133k
    }
345
18.1M
    if (attribute->attrib.ulValueLen <= ATTR_SPACE) {
346
17.8M
        copy->attrib.pValue = copy->space;
347
17.8M
    } else {
348
330k
        copy->attrib.pValue = PORT_Alloc(attribute->attrib.ulValueLen);
349
330k
        if (copy->attrib.pValue == NULL) {
350
0
            PORT_Free(copy);
351
0
            return NULL;
352
0
        }
353
330k
        copy->freeData = PR_TRUE;
354
330k
    }
355
18.1M
    PORT_Memcpy(copy->attrib.pValue, attribute->attrib.pValue,
356
18.1M
                attribute->attrib.ulValueLen);
357
18.1M
    copy->attrib.ulValueLen = attribute->attrib.ulValueLen;
358
18.1M
    return copy;
359
18.1M
}
360
361
/*
362
 * look up and attribute structure from a type and Object structure.
363
 * The returned attribute is referenced and needs to be freed when
364
 * it is no longer needed.
365
 */
366
SFTKAttribute *
367
sftk_FindAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
368
21.1M
{
369
21.1M
    SFTKAttribute *attribute;
370
21.1M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
371
372
    /* validation flags are stored as FIPS indicators */
373
21.1M
    if (type == CKA_OBJECT_VALIDATION_FLAGS) {
374
0
        return &object->validation_attribute;
375
0
    }
376
377
21.1M
    if (sessObject == NULL) {
378
4.30k
        return sftk_FindTokenAttribute(sftk_narrowToTokenObject(object), type);
379
4.30k
    }
380
381
    /* Return a detached copy rather than the live pool entry: callers
382
     * dereference attrib.pValue after the lock is dropped, while a
383
     * concurrent sftk_forceAttribute() may free and reassign it.
384
     * Snapshotting under the lock gives the caller a stable,
385
     * private value (this matches the token-object path above). */
386
21.1M
    PR_Lock(sessObject->attributeLock);
387
21.1M
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
388
21.1M
    if (attribute != NULL) {
389
18.3M
        attribute = sftk_CopyAttribute(attribute);
390
18.3M
    }
391
21.1M
    PR_Unlock(sessObject->attributeLock);
392
393
21.1M
    return (attribute);
394
21.1M
}
395
396
/*
397
 * Look up an attribute while the caller holds the object's attributeLock.
398
 * Returns a BORROWED reference to the live node in sessObject->head[] (or
399
 * the object's embedded validation attribute): valid only until the lock is
400
 * released, and never to be passed to sftk_FreeAttribute().
401
 *
402
 * This is only valid for session objects (and CKA_OBJECT_VALIDATION_FLAGS).
403
 * Token objects have no live node; callers that may see one must fall back
404
 * to sftk_FindAttribute(). Returns NULL if the attribute is absent.
405
 *
406
 * The lock is NOT reentrant: while holding it, the caller must not call any
407
 * attribute API that takes it itself (sftk_FindAttribute,
408
 * sftk_AddAttributeType, sftk_forceAttribute, sftk_DeleteAttributeType).
409
 */
410
static SFTKAttribute *
411
sftk_FindAttributeLocked(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
412
20.8M
{
413
20.8M
    SFTKSessionObject *sessObject;
414
20.8M
    SFTKAttribute *attribute;
415
416
    /* validation flags are stored as FIPS indicators */
417
20.8M
    if (type == CKA_OBJECT_VALIDATION_FLAGS) {
418
0
        return &object->validation_attribute;
419
0
    }
420
421
20.8M
    sessObject = sftk_narrowToSessionObject(object);
422
20.8M
    PORT_Assert(sessObject != NULL);
423
20.8M
    if (sessObject == NULL) {
424
0
        return NULL;
425
0
    }
426
427
20.8M
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
428
20.8M
    return attribute;
429
20.8M
}
430
431
/*
432
 * Take a buffer and it's length and return it's true size in bits;
433
 */
434
unsigned int
435
sftk_GetLengthInBits(unsigned char *buf, unsigned int bufLen)
436
123k
{
437
123k
    unsigned int size = bufLen * 8;
438
123k
    unsigned int i;
439
440
    /* Get the real length in bytes */
441
129k
    for (i = 0; i < bufLen; i++) {
442
128k
        unsigned char c = *buf++;
443
128k
        if (c != 0) {
444
123k
            unsigned char m;
445
405k
            for (m = 0x80; m > 0; m = m >> 1) {
446
405k
                if ((c & m) != 0) {
447
123k
                    break;
448
123k
                }
449
282k
                size--;
450
282k
            }
451
123k
            break;
452
123k
        }
453
5.48k
        size -= 8;
454
5.48k
    }
455
123k
    return size;
456
123k
}
457
458
/*
459
 * Constrain a big num attribute. to size and padding
460
 * minLength means length of the object must be greater than equal to minLength
461
 * maxLength means length of the object must be less than equal to maxLength
462
 * minMultiple means that object length mod minMultiple must equal 0.
463
 * all input sizes are in bits.
464
 * if any constraint is '0' that constraint is not checked.
465
 */
466
CK_RV
467
sftk_ConstrainAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
468
                        int minLength, int maxLength, int minMultiple)
469
110k
{
470
110k
    SFTKAttribute *attribute;
471
110k
    int size = 0;
472
110k
    unsigned char *ptr;
473
110k
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
474
110k
    CK_RV crv = CKR_OK;
475
476
110k
    if (sessObject != NULL) {
477
110k
        PR_Lock(sessObject->attributeLock);
478
110k
        attribute = sftk_FindAttributeLocked(object, type);
479
110k
    } else {
480
0
        attribute = sftk_FindAttribute(object, type);
481
0
    }
482
483
110k
    if (!attribute) {
484
0
        crv = CKR_TEMPLATE_INCOMPLETE;
485
110k
    } else {
486
110k
        ptr = (unsigned char *)attribute->attrib.pValue;
487
110k
        if (ptr == NULL) {
488
0
            crv = CKR_ATTRIBUTE_VALUE_INVALID;
489
110k
        } else {
490
110k
            size = sftk_GetLengthInBits(ptr, attribute->attrib.ulValueLen);
491
110k
        }
492
110k
    }
493
494
110k
    if (sessObject != NULL) {
495
110k
        PR_Unlock(sessObject->attributeLock);
496
110k
    } else {
497
0
        sftk_FreeAttribute(attribute);
498
0
    }
499
110k
    if (crv != CKR_OK) {
500
0
        return crv;
501
0
    }
502
503
110k
    if ((minLength != 0) && (size < minLength)) {
504
4.89k
        return CKR_ATTRIBUTE_VALUE_INVALID;
505
4.89k
    }
506
105k
    if ((maxLength != 0) && (size > maxLength)) {
507
181
        return CKR_ATTRIBUTE_VALUE_INVALID;
508
181
    }
509
105k
    if ((minMultiple != 0) && ((size % minMultiple) != 0)) {
510
38
        return CKR_ATTRIBUTE_VALUE_INVALID;
511
38
    }
512
105k
    return CKR_OK;
513
105k
}
514
515
PRBool
516
sftk_hasAttributeToken(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type)
517
200
{
518
200
    CK_ATTRIBUTE template;
519
200
    CK_RV crv;
520
200
    SFTKDBHandle *dbHandle;
521
522
200
    if (object == NULL) {
523
0
        return PR_FALSE;
524
0
    }
525
200
    dbHandle = sftk_getDBForTokenObject(object->obj.slot, object->obj.handle);
526
200
    template.type = type;
527
200
    template.pValue = NULL;
528
200
    template.ulValueLen = 0;
529
530
200
    crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, &template, 1);
531
200
    sftk_freeDB(dbHandle);
532
533
    /* attribute is bigger than our attribute space buffer, malloc it */
534
200
    return (crv == CKR_OK) ? PR_TRUE : PR_FALSE;
535
200
}
536
537
/*
538
 * return true if object has attribute
539
 */
540
PRBool
541
sftk_hasAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
542
47.8M
{
543
47.8M
    SFTKAttribute *attribute;
544
47.8M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
545
546
47.8M
    if (sessObject == NULL) {
547
200
        return sftk_hasAttributeToken(sftk_narrowToTokenObject(object), type);
548
200
    }
549
550
47.8M
    PR_Lock(sessObject->attributeLock);
551
47.8M
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
552
47.8M
    PR_Unlock(sessObject->attributeLock);
553
554
47.8M
    return (PRBool)(attribute != NULL);
555
47.8M
}
556
557
/*
558
 * add an attribute to an object
559
 */
560
static void
561
sftk_AddAttribute(SFTKObject *object, SFTKAttribute *attribute)
562
55.2M
{
563
55.2M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
564
565
55.2M
    if (sessObject == NULL)
566
0
        return;
567
55.2M
    PR_Lock(sessObject->attributeLock);
568
55.2M
    sftkqueue_add(attribute, attribute->handle,
569
55.2M
                  sessObject->head, sessObject->hashSize);
570
55.2M
    PR_Unlock(sessObject->attributeLock);
571
55.2M
}
572
573
/*
574
 * copy an unsigned attribute into a SECItem. Secitem is allocated in
575
 * the specified arena.
576
 */
577
CK_RV
578
sftk_Attribute2SSecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object,
579
                        CK_ATTRIBUTE_TYPE type)
580
613k
{
581
613k
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
582
613k
    SFTKAttribute *attribute;
583
613k
    CK_RV crv = CKR_OK;
584
585
613k
    item->data = NULL;
586
587
613k
    if (sessObject != NULL) {
588
613k
        PR_Lock(sessObject->attributeLock);
589
613k
        attribute = sftk_FindAttributeLocked(object, type);
590
613k
    } else {
591
600
        attribute = sftk_FindAttribute(object, type);
592
600
    }
593
594
613k
    if (attribute == NULL) {
595
0
        crv = CKR_TEMPLATE_INCOMPLETE;
596
613k
    } else {
597
613k
        (void)SECITEM_AllocItem(arena, item, attribute->attrib.ulValueLen);
598
613k
        if (item->data == NULL) {
599
11
            crv = CKR_HOST_MEMORY;
600
613k
        } else {
601
613k
            PORT_Memcpy(item->data, attribute->attrib.pValue, item->len);
602
613k
        }
603
613k
    }
604
605
613k
    if (sessObject != NULL) {
606
613k
        PR_Unlock(sessObject->attributeLock);
607
613k
    } else {
608
600
        sftk_FreeAttribute(attribute);
609
600
    }
610
613k
    return crv;
611
613k
}
612
613
/*
614
 * fetch multiple attributes into  SECItems. Secitem data is allocated in
615
 * the specified arena.
616
 */
617
CK_RV
618
sftk_MultipleAttribute2SecItem(PLArenaPool *arena, SFTKObject *object,
619
                               SFTKItemTemplate *itemTemplate, int itemTemplateCount)
620
11.1k
{
621
622
11.1k
    CK_RV crv = CKR_OK;
623
11.1k
    CK_ATTRIBUTE templateSpace[SFTK_MAX_ITEM_TEMPLATE];
624
11.1k
    CK_ATTRIBUTE *template;
625
11.1k
    SFTKTokenObject *tokObject;
626
11.1k
    SFTKDBHandle *dbHandle = NULL;
627
11.1k
    int i;
628
629
11.1k
    tokObject = sftk_narrowToTokenObject(object);
630
631
    /* session objects, just loop through the list */
632
11.1k
    if (tokObject == NULL) {
633
40.7k
        for (i = 0; i < itemTemplateCount; i++) {
634
31.2k
            crv = sftk_Attribute2SecItem(arena, itemTemplate[i].item, object,
635
31.2k
                                         itemTemplate[i].type);
636
31.2k
            if (crv != CKR_OK) {
637
0
                return crv;
638
0
            }
639
31.2k
        }
640
9.47k
        return CKR_OK;
641
9.47k
    }
642
643
    /* don't do any work if none is required */
644
1.70k
    if (itemTemplateCount == 0) {
645
0
        return CKR_OK;
646
0
    }
647
648
    /* don't allocate the template unless we need it */
649
1.70k
    if (itemTemplateCount > SFTK_MAX_ITEM_TEMPLATE) {
650
0
        template = PORT_NewArray(CK_ATTRIBUTE, itemTemplateCount);
651
1.70k
    } else {
652
1.70k
        template = templateSpace;
653
1.70k
    }
654
655
1.70k
    if (template == NULL) {
656
0
        crv = CKR_HOST_MEMORY;
657
0
        goto loser;
658
0
    }
659
660
1.70k
    dbHandle = sftk_getDBForTokenObject(object->slot, object->handle);
661
1.70k
    if (dbHandle == NULL) {
662
0
        crv = CKR_OBJECT_HANDLE_INVALID;
663
0
        goto loser;
664
0
    }
665
666
    /* set up the PKCS #11 template */
667
15.3k
    for (i = 0; i < itemTemplateCount; i++) {
668
13.6k
        template[i].type = itemTemplate[i].type;
669
13.6k
        template[i].pValue = NULL;
670
13.6k
        template[i].ulValueLen = 0;
671
13.6k
    }
672
673
    /* fetch the attribute lengths */
674
1.70k
    crv = sftkdb_GetAttributeValue(dbHandle, object->handle,
675
1.70k
                                   template, itemTemplateCount);
676
1.70k
    if (crv != CKR_OK) {
677
0
        goto loser;
678
0
    }
679
680
    /* allocate space for the attributes */
681
15.3k
    for (i = 0; i < itemTemplateCount; i++) {
682
13.6k
        template[i].pValue = PORT_ArenaAlloc(arena, template[i].ulValueLen);
683
13.6k
        if (template[i].pValue == NULL) {
684
0
            crv = CKR_HOST_MEMORY;
685
0
            goto loser;
686
0
        }
687
13.6k
    }
688
689
    /* fetch the attributes */
690
1.70k
    crv = sftkdb_GetAttributeValue(dbHandle, object->handle,
691
1.70k
                                   template, itemTemplateCount);
692
1.70k
    if (crv != CKR_OK) {
693
0
        goto loser;
694
0
    }
695
696
    /* Fill in the items */
697
15.3k
    for (i = 0; i < itemTemplateCount; i++) {
698
13.6k
        itemTemplate[i].item->data = template[i].pValue;
699
13.6k
        itemTemplate[i].item->len = template[i].ulValueLen;
700
13.6k
    }
701
702
1.70k
loser:
703
1.70k
    if (template != templateSpace) {
704
0
        PORT_Free(template);
705
0
    }
706
1.70k
    if (dbHandle) {
707
1.70k
        sftk_freeDB(dbHandle);
708
1.70k
    }
709
710
1.70k
    return crv;
711
1.70k
}
712
713
/*
714
 * this is only valid for CK_BBOOL type attributes. Return the state
715
 * of that attribute.
716
 */
717
PRBool
718
sftk_isTrue(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
719
16.8M
{
720
16.8M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
721
16.8M
    SFTKAttribute *attribute;
722
16.8M
    PRBool tok = PR_FALSE;
723
724
    /* For a session object read the live single-byte value under the lock
725
     * rather than copying it out (this is a very hot path); for a token
726
     * object fall back to a freed copy. */
727
16.8M
    if (sessObject != NULL) {
728
16.8M
        PR_Lock(sessObject->attributeLock);
729
16.8M
        attribute = sftk_FindAttributeLocked(object, type);
730
16.8M
    } else {
731
1.75k
        attribute = sftk_FindAttribute(object, type);
732
1.75k
    }
733
734
16.8M
    if (attribute != NULL && attribute->attrib.pValue != NULL) {
735
14.8M
        tok = (PRBool)(*(CK_BBOOL *)attribute->attrib.pValue);
736
14.8M
    }
737
738
16.8M
    if (sessObject != NULL) {
739
16.8M
        PR_Unlock(sessObject->attributeLock);
740
16.8M
    } else {
741
1.75k
        sftk_FreeAttribute(attribute);
742
1.75k
    }
743
744
16.8M
    return tok;
745
16.8M
}
746
747
static CK_RV
748
sftk_forceTokenAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
749
                         const void *value, unsigned int len)
750
6
{
751
6
    CK_ATTRIBUTE attribute;
752
6
    SFTKDBHandle *dbHandle = NULL;
753
6
    SFTKTokenObject *to = sftk_narrowToTokenObject(object);
754
6
    CK_RV crv;
755
756
6
    PORT_Assert(to);
757
6
    if (to == NULL) {
758
0
        return CKR_DEVICE_ERROR;
759
0
    }
760
761
6
    dbHandle = sftk_getDBForTokenObject(object->slot, object->handle);
762
763
6
    attribute.type = type;
764
6
    attribute.pValue = (void *)value;
765
6
    attribute.ulValueLen = len;
766
767
6
    crv = sftkdb_SetAttributeValue(dbHandle, object, &attribute, 1);
768
6
    sftk_freeDB(dbHandle);
769
6
    return crv;
770
6
}
771
772
/*
773
 * force an attribute to a specifc value.
774
 */
775
CK_RV
776
sftk_forceAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
777
                    const void *value, unsigned int len)
778
13.3M
{
779
13.3M
    SFTKAttribute *attribute;
780
13.3M
    void *att_val = NULL;
781
13.3M
    PRBool freeData = PR_FALSE;
782
13.3M
    PRBool oldOwnsHeapValue;
783
784
13.3M
    PORT_Assert(object);
785
13.3M
    PORT_Assert(object->refCount);
786
13.3M
    PORT_Assert(object->slot);
787
13.3M
    if (!object ||
788
13.3M
        !object->refCount ||
789
13.3M
        !object->slot) {
790
0
        return CKR_DEVICE_ERROR;
791
0
    }
792
    /* validation flags are stored as FIPS indicators,
793
     * don't send them through the general attribute
794
     * parsing */
795
13.3M
    if (type == CKA_OBJECT_VALIDATION_FLAGS) {
796
0
        CK_FLAGS validation;
797
0
        if (len != sizeof(CK_FLAGS)) {
798
0
            return CKR_ATTRIBUTE_VALUE_INVALID;
799
0
        }
800
0
        validation = *(CK_FLAGS *)value;
801
        /* we only understand FIPS currently, don't allow setting
802
         * other flags */
803
0
        if ((validation & ~SFTK_VALIDATION_FIPS_FLAG) != 0) {
804
0
            return CKR_ATTRIBUTE_VALUE_INVALID;
805
0
        }
806
0
        object->validation_value = validation;
807
0
        return CKR_OK;
808
0
    }
809
13.3M
    if (sftk_isToken(object->handle)) {
810
6
        return sftk_forceTokenAttribute(object, type, value, len);
811
6
    }
812
    /* After the token/validation dispatch above, this is a session
813
     * object. Look up and mutate the live node under attributeLock so the
814
     * (pValue, ulValueLen) pair stays consistent for concurrent readers,
815
     * which snapshot it under the same lock in sftk_FindAttribute(). */
816
13.3M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
817
13.3M
    PORT_Assert(sessObject);
818
13.3M
    if (sessObject == NULL) {
819
0
        return CKR_DEVICE_ERROR;
820
0
    }
821
822
13.3M
    PR_Lock(sessObject->attributeLock);
823
13.3M
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
824
13.3M
    if (attribute == NULL) {
825
8.41M
        PR_Unlock(sessObject->attributeLock);
826
8.41M
        return sftk_AddAttributeType(object, type, value, len);
827
8.41M
    }
828
4.91M
    oldOwnsHeapValue = attribute->attrib.pValue != NULL &&
829
4.82M
                       sftk_attributeOwnsHeapValue(sessObject, attribute);
830
831
4.91M
    if (value) {
832
4.91M
        if (len <= ATTR_SPACE) {
833
4.91M
            att_val = attribute->space;
834
4.91M
        } else {
835
16
            att_val = PORT_Alloc(len);
836
16
            freeData = PR_TRUE;
837
16
        }
838
4.91M
        if (att_val == NULL) {
839
0
            PR_Unlock(sessObject->attributeLock);
840
0
            return CKR_HOST_MEMORY;
841
0
        }
842
4.91M
        if (attribute->attrib.pValue == att_val) {
843
4.82M
            PORT_Memset(attribute->attrib.pValue, 0,
844
4.82M
                        attribute->attrib.ulValueLen);
845
4.82M
        }
846
4.91M
        PORT_Memcpy(att_val, value, len);
847
4.91M
    }
848
4.91M
    if (attribute->attrib.pValue != NULL) {
849
4.82M
        if (attribute->attrib.pValue != att_val) {
850
16
            PORT_Memset(attribute->attrib.pValue, 0,
851
16
                        attribute->attrib.ulValueLen);
852
16
        }
853
4.82M
        if (oldOwnsHeapValue) {
854
16
            PORT_ReleaseAssert(attribute->attrib.pValue != att_val);
855
16
            PORT_Free(attribute->attrib.pValue);
856
16
        }
857
4.82M
        attribute->freeData = PR_FALSE;
858
4.82M
        attribute->attrib.pValue = NULL;
859
4.82M
        attribute->attrib.ulValueLen = 0;
860
4.82M
    }
861
4.91M
    if (att_val) {
862
4.91M
        attribute->attrib.pValue = att_val;
863
4.91M
        attribute->attrib.ulValueLen = len;
864
4.91M
        attribute->freeData = freeData;
865
4.91M
    }
866
4.91M
    PR_Unlock(sessObject->attributeLock);
867
4.91M
    return CKR_OK;
868
4.91M
}
869
870
/*
871
 * decode when a particular attribute may be modified
872
 *  SFTK_NEVER: This attribute must be set at object creation time and
873
 *  can never be modified.
874
 *  SFTK_ONCOPY: This attribute may be modified only when you copy the
875
 *  object.
876
 *  SFTK_SENSITIVE: The CKA_SENSITIVE attribute can only be changed from
877
 *  CK_FALSE to CK_TRUE.
878
 *  SFTK_ALWAYS: This attribute can always be modified.
879
 * Some attributes vary their modification type based on the class of the
880
 *   object.
881
 */
882
SFTKModifyType
883
sftk_modifyType(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass)
884
92.3k
{
885
    /* if we don't know about it, user user defined, always allow modify */
886
92.3k
    SFTKModifyType mtype = SFTK_ALWAYS;
887
888
92.3k
    switch (type) {
889
        /* NEVER */
890
0
        case CKA_CLASS:
891
0
        case CKA_CERTIFICATE_TYPE:
892
0
        case CKA_KEY_TYPE:
893
0
        case CKA_MODULUS:
894
0
        case CKA_MODULUS_BITS:
895
0
        case CKA_PUBLIC_EXPONENT:
896
0
        case CKA_PRIVATE_EXPONENT:
897
0
        case CKA_PRIME:
898
0
        case CKA_BASE:
899
0
        case CKA_PRIME_1:
900
0
        case CKA_PRIME_2:
901
0
        case CKA_EXPONENT_1:
902
0
        case CKA_EXPONENT_2:
903
0
        case CKA_COEFFICIENT:
904
0
        case CKA_SEED:
905
0
        case CKA_PARAMETER_SET:
906
0
        case CKA_VALUE_LEN:
907
0
        case CKA_ALWAYS_SENSITIVE:
908
0
        case CKA_NEVER_EXTRACTABLE:
909
0
        case CKA_NSS_DB:
910
0
            mtype = SFTK_NEVER;
911
0
            break;
912
913
        /* ONCOPY */
914
16
        case CKA_TOKEN:
915
16
        case CKA_PRIVATE:
916
16
        case CKA_MODIFIABLE:
917
16
            mtype = SFTK_ONCOPY;
918
16
            break;
919
920
        /* SENSITIVE */
921
0
        case CKA_SENSITIVE:
922
0
        case CKA_EXTRACTABLE:
923
0
            mtype = SFTK_SENSITIVE;
924
0
            break;
925
926
        /* ALWAYS */
927
2
        case CKA_LABEL:
928
2
        case CKA_APPLICATION:
929
92.3k
        case CKA_ID:
930
92.3k
        case CKA_SERIAL_NUMBER:
931
92.3k
        case CKA_START_DATE:
932
92.3k
        case CKA_END_DATE:
933
92.3k
        case CKA_DERIVE:
934
92.3k
        case CKA_ENCRYPT:
935
92.3k
        case CKA_DECRYPT:
936
92.3k
        case CKA_SIGN:
937
92.3k
        case CKA_VERIFY:
938
92.3k
        case CKA_SIGN_RECOVER:
939
92.3k
        case CKA_VERIFY_RECOVER:
940
92.3k
        case CKA_WRAP:
941
92.3k
        case CKA_UNWRAP:
942
92.3k
            mtype = SFTK_ALWAYS;
943
92.3k
            break;
944
945
        /* DEPENDS ON CLASS */
946
0
        case CKA_VALUE:
947
0
            mtype = (inClass == CKO_DATA) ? SFTK_ALWAYS : SFTK_NEVER;
948
0
            break;
949
950
0
        case CKA_SUBPRIME:
951
            /* allow the CKA_SUBPRIME to be added to dh private keys */
952
0
            mtype = (inClass == CKO_PRIVATE_KEY) ? SFTK_ALWAYS : SFTK_NEVER;
953
0
            break;
954
955
2
        case CKA_SUBJECT:
956
2
            mtype = (inClass == CKO_CERTIFICATE) ? SFTK_NEVER : SFTK_ALWAYS;
957
2
            break;
958
0
        default:
959
0
            break;
960
92.3k
    }
961
92.3k
    return mtype;
962
92.3k
}
963
964
/* decode if a particular attribute is sensitive (cannot be read
965
 * back to the user of if the object is set to SENSITIVE) */
966
PRBool
967
sftk_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass)
968
10.8k
{
969
10.8k
    switch (type) {
970
        /* ALWAYS */
971
0
        case CKA_PRIVATE_EXPONENT:
972
0
        case CKA_PRIME_1:
973
0
        case CKA_PRIME_2:
974
0
        case CKA_EXPONENT_1:
975
0
        case CKA_EXPONENT_2:
976
0
        case CKA_COEFFICIENT:
977
0
        case CKA_SEED:
978
0
            return PR_TRUE;
979
980
        /* DEPENDS ON CLASS */
981
0
        case CKA_VALUE:
982
            /* PRIVATE and SECRET KEYS have SENSITIVE values */
983
0
            return (PRBool)((inClass == CKO_PRIVATE_KEY) || (inClass == CKO_SECRET_KEY));
984
985
10.8k
        default:
986
10.8k
            break;
987
10.8k
    }
988
10.8k
    return PR_FALSE;
989
10.8k
}
990
991
/*
992
 * copy an attribute into a SECItem. Secitem is allocated in the specified
993
 * arena.
994
 */
995
CK_RV
996
sftk_Attribute2SecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object,
997
                       CK_ATTRIBUTE_TYPE type)
998
41.8k
{
999
41.8k
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
1000
41.8k
    SFTKAttribute *attribute;
1001
41.8k
    CK_RV crv = CKR_OK;
1002
41.8k
    int len;
1003
1004
41.8k
    if (sessObject != NULL) {
1005
41.8k
        PR_Lock(sessObject->attributeLock);
1006
41.8k
        attribute = sftk_FindAttributeLocked(object, type);
1007
41.8k
    } else {
1008
0
        attribute = sftk_FindAttribute(object, type);
1009
0
    }
1010
1011
41.8k
    if (attribute == NULL) {
1012
0
        crv = CKR_TEMPLATE_INCOMPLETE;
1013
41.8k
    } else {
1014
41.8k
        len = attribute->attrib.ulValueLen;
1015
41.8k
        if (arena) {
1016
31.2k
            item->data = (unsigned char *)PORT_ArenaAlloc(arena, len);
1017
31.2k
        } else {
1018
10.5k
            item->data = (unsigned char *)PORT_Alloc(len);
1019
10.5k
        }
1020
41.8k
        if (item->data == NULL) {
1021
0
            crv = CKR_HOST_MEMORY;
1022
41.8k
        } else {
1023
41.8k
            item->len = len;
1024
41.8k
            PORT_Memcpy(item->data, attribute->attrib.pValue, len);
1025
41.8k
        }
1026
41.8k
    }
1027
1028
41.8k
    if (sessObject != NULL) {
1029
41.8k
        PR_Unlock(sessObject->attributeLock);
1030
41.8k
    } else {
1031
0
        sftk_FreeAttribute(attribute);
1032
0
    }
1033
41.8k
    return crv;
1034
41.8k
}
1035
1036
CK_RV
1037
sftk_GetULongAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
1038
                       CK_ULONG *longData)
1039
3.28M
{
1040
3.28M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
1041
3.28M
    SFTKAttribute *attribute;
1042
3.28M
    CK_RV crv = CKR_OK;
1043
1044
    /* For a session object read the live value under the lock instead of
1045
     * copying it out; for a token object fall back to a freed copy. */
1046
3.28M
    if (sessObject != NULL) {
1047
3.28M
        PR_Lock(sessObject->attributeLock);
1048
3.28M
        attribute = sftk_FindAttributeLocked(object, type);
1049
3.28M
    } else {
1050
0
        attribute = sftk_FindAttribute(object, type);
1051
0
    }
1052
1053
3.28M
    if (attribute == NULL) {
1054
0
        crv = CKR_TEMPLATE_INCOMPLETE;
1055
3.28M
    } else if (attribute->attrib.ulValueLen != sizeof(CK_ULONG)) {
1056
0
        crv = CKR_ATTRIBUTE_VALUE_INVALID;
1057
3.28M
    } else {
1058
3.28M
        *longData = *(CK_ULONG *)attribute->attrib.pValue;
1059
3.28M
    }
1060
1061
3.28M
    if (sessObject != NULL) {
1062
3.28M
        PR_Unlock(sessObject->attributeLock);
1063
3.28M
    } else {
1064
0
        sftk_FreeAttribute(attribute);
1065
0
    }
1066
3.28M
    return crv;
1067
3.28M
}
1068
1069
CK_RV
1070
sftk_ReadAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
1071
                   unsigned char *data, unsigned int maxLen, unsigned int *lenp)
1072
155
{
1073
155
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
1074
155
    SFTKAttribute *attribute;
1075
155
    CK_RV crv = CKR_OK;
1076
1077
    /* For a session object read the live value under the lock instead of
1078
     * copying it out; for a token object fall back to a freed copy. */
1079
155
    if (sessObject != NULL) {
1080
155
        PR_Lock(sessObject->attributeLock);
1081
155
        attribute = sftk_FindAttributeLocked(object, type);
1082
155
    } else {
1083
0
        attribute = sftk_FindAttribute(object, type);
1084
0
    }
1085
1086
155
    if (attribute == NULL) {
1087
0
        crv = CKR_TEMPLATE_INCOMPLETE;
1088
155
    } else {
1089
155
        *lenp = attribute->attrib.ulValueLen;
1090
155
        if (*lenp > maxLen) {
1091
            /* normally would be CKR_BUFFER_TOO_SMALL, but
1092
             * it used with internal buffers, so if the value is
1093
             * to long, the original attribute was invalid */
1094
0
            crv = CKR_ATTRIBUTE_VALUE_INVALID;
1095
155
        } else {
1096
155
            PORT_Memcpy(data, attribute->attrib.pValue, *lenp);
1097
155
        }
1098
155
    }
1099
1100
155
    if (sessObject != NULL) {
1101
155
        PR_Unlock(sessObject->attributeLock);
1102
155
    } else {
1103
0
        sftk_FreeAttribute(attribute);
1104
0
    }
1105
155
    return crv;
1106
155
}
1107
1108
void
1109
sftk_DeleteAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
1110
1.21M
{
1111
1.21M
    SFTKAttribute *attribute;
1112
1.21M
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
1113
1114
1.21M
    if (sessObject == NULL) {
1115
0
        return;
1116
0
    }
1117
1118
    /* Find, unlink, and destroy the live node atomically under the lock.
1119
     * Once unlinked from head[] the node is unreachable by any other
1120
     * thread (readers snapshot copies under the same lock), so destroying
1121
     * it here cannot race a concurrent reader or a second deleter. */
1122
1.21M
    PR_Lock(sessObject->attributeLock);
1123
1.21M
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
1124
1.21M
    if (attribute != NULL) {
1125
17.7k
        if (sftkqueue_is_queued(attribute, attribute->handle,
1126
17.7k
                                sessObject->head, sessObject->hashSize)) {
1127
17.7k
            sftkqueue_delete(attribute, attribute->handle,
1128
17.7k
                             sessObject->head, sessObject->hashSize);
1129
17.7k
        }
1130
17.7k
        sftk_DestroyAttribute(attribute);
1131
17.7k
    }
1132
1.21M
    PR_Unlock(sessObject->attributeLock);
1133
1.21M
}
1134
1135
CK_RV
1136
sftk_AddAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
1137
                      const void *valPtr, CK_ULONG length)
1138
55.2M
{
1139
55.2M
    SFTKAttribute *attribute;
1140
55.2M
    attribute = sftk_NewAttribute(object, type, valPtr, length);
1141
55.2M
    if (attribute == NULL) {
1142
0
        return CKR_HOST_MEMORY;
1143
0
    }
1144
55.2M
    sftk_AddAttribute(object, attribute);
1145
55.2M
    return CKR_OK;
1146
55.2M
}
1147
1148
/*
1149
 * ******************** Object Utilities *******************************
1150
 */
1151
1152
/* must be called holding sftk_tokenKeyLock(slot) */
1153
static SECItem *
1154
sftk_lookupTokenKeyByHandle(SFTKSlot *slot, CK_OBJECT_HANDLE handle)
1155
6
{
1156
6
    return (SECItem *)PL_HashTableLookup(slot->tokObjHashTable, (void *)(uintptr_t)handle);
1157
6
}
1158
1159
/*
1160
 * use the refLock. This operations should be very rare, so the added
1161
 * contention on the ref lock should be lower than the overhead of adding
1162
 * a new lock. We use separate functions for this just in case I'm wrong.
1163
 */
1164
static void
1165
sftk_tokenKeyLock(SFTKSlot *slot)
1166
38
{
1167
38
    SKIP_AFTER_FORK(PR_Lock(slot->objectLock));
1168
38
}
1169
1170
static void
1171
sftk_tokenKeyUnlock(SFTKSlot *slot)
1172
38
{
1173
38
    SKIP_AFTER_FORK(PR_Unlock(slot->objectLock));
1174
38
}
1175
1176
static PRIntn
1177
sftk_freeHashItem(PLHashEntry *entry, PRIntn index, void *arg)
1178
0
{
1179
0
    SECItem *item = (SECItem *)entry->value;
1180
1181
0
    SECITEM_FreeItem(item, PR_TRUE);
1182
0
    return HT_ENUMERATE_NEXT;
1183
0
}
1184
1185
CK_RV
1186
SFTK_ClearTokenKeyHashTable(SFTKSlot *slot)
1187
32
{
1188
32
    sftk_tokenKeyLock(slot);
1189
32
    PORT_Assert(!slot->present);
1190
32
    PL_HashTableEnumerateEntries(slot->tokObjHashTable, sftk_freeHashItem, NULL);
1191
32
    sftk_tokenKeyUnlock(slot);
1192
32
    return CKR_OK;
1193
32
}
1194
1195
/* allocation hooks that allow us to recycle old object structures */
1196
static SFTKObjectFreeList sessionObjectList = { NULL, NULL, 0 };
1197
static SFTKObjectFreeList tokenObjectList = { NULL, NULL, 0 };
1198
1199
SFTKObject *
1200
sftk_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace,
1201
                       SFTKObjectFreeList *list, unsigned int hashSize, PRBool isSessionObject)
1202
3.07M
{
1203
3.07M
    SFTKObject *object;
1204
3.07M
    int size = 0;
1205
1206
3.07M
    if (!optimizeSpace) {
1207
1.94k
        PR_Lock(list->lock);
1208
1.94k
        object = list->head;
1209
1.94k
        if (object) {
1210
1.94k
            list->head = object->next;
1211
1.94k
            list->count--;
1212
1.94k
        }
1213
1.94k
        PR_Unlock(list->lock);
1214
1.94k
        if (object) {
1215
            /* A live object on the free list means it was destroyed
1216
             * twice; some other thread still holds a pointer to it and
1217
             * will corrupt it if it is handed out again. */
1218
1.94k
            PORT_ReleaseAssert(object->refCount == 0);
1219
1.94k
            object->next = object->prev = NULL;
1220
1.94k
            *hasLocks = PR_TRUE;
1221
1.94k
            return object;
1222
1.94k
        }
1223
1.94k
    }
1224
3.07M
    size = isSessionObject ? sizeof(SFTKSessionObject) + hashSize * sizeof(SFTKAttribute *) : sizeof(SFTKTokenObject);
1225
1226
3.07M
    object = (SFTKObject *)PORT_ZAlloc(size);
1227
3.07M
    if (isSessionObject && object) {
1228
3.07M
        ((SFTKSessionObject *)object)->hashSize = hashSize;
1229
3.07M
    }
1230
3.07M
    *hasLocks = PR_FALSE;
1231
3.07M
    return object;
1232
3.07M
}
1233
1234
static void
1235
sftk_PutObjectToList(SFTKObject *object, SFTKObjectFreeList *list,
1236
                     PRBool isSessionObject)
1237
3.07M
{
1238
1239
    /* the code below is equivalent to :
1240
     *     optimizeSpace = isSessionObject ? object->optimizeSpace : PR_FALSE;
1241
     * just faster.
1242
     */
1243
3.07M
    PRBool optimizeSpace = isSessionObject &&
1244
3.07M
                           ((SFTKSessionObject *)object)->optimizeSpace;
1245
3.07M
    if (object->refLock && !optimizeSpace) {
1246
1.95k
        PR_Lock(list->lock);
1247
1.95k
        if (list->count < MAX_OBJECT_LIST_SIZE) {
1248
1.95k
            object->next = list->head;
1249
1.95k
            list->head = object;
1250
1.95k
            list->count++;
1251
1.95k
            PR_Unlock(list->lock);
1252
1.95k
            return;
1253
1.95k
        }
1254
0
        PR_Unlock(list->lock);
1255
0
    }
1256
3.07M
    if (isSessionObject) {
1257
3.07M
        SFTKSessionObject *so = (SFTKSessionObject *)object;
1258
3.07M
        PR_DestroyLock(so->attributeLock);
1259
3.07M
        so->attributeLock = NULL;
1260
3.07M
    }
1261
3.07M
    if (object->refLock) {
1262
3.07M
        PR_DestroyLock(object->refLock);
1263
3.07M
        object->refLock = NULL;
1264
3.07M
    }
1265
3.07M
    PORT_Free(object);
1266
3.07M
}
1267
1268
static SFTKObject *
1269
sftk_freeObjectData(SFTKObject *object)
1270
6
{
1271
6
    SFTKObject *next = object->next;
1272
1273
6
    PORT_Free(object);
1274
6
    return next;
1275
6
}
1276
1277
static void
1278
sftk_InitFreeList(SFTKObjectFreeList *list)
1279
36
{
1280
36
    if (!list->lock) {
1281
36
        list->lock = PR_NewLock();
1282
36
    }
1283
36
}
1284
1285
void
1286
sftk_InitFreeLists(void)
1287
18
{
1288
18
    sftk_InitFreeList(&sessionObjectList);
1289
18
    sftk_InitFreeList(&tokenObjectList);
1290
18
}
1291
1292
static void
1293
sftk_CleanupFreeList(SFTKObjectFreeList *list, PRBool isSessionList)
1294
32
{
1295
32
    SFTKObject *object;
1296
1297
32
    if (!list->lock) {
1298
0
        return;
1299
0
    }
1300
32
    SKIP_AFTER_FORK(PR_Lock(list->lock));
1301
38
    for (object = list->head; object != NULL;
1302
32
         object = sftk_freeObjectData(object)) {
1303
6
        PR_DestroyLock(object->refLock);
1304
6
        if (isSessionList) {
1305
0
            PR_DestroyLock(((SFTKSessionObject *)object)->attributeLock);
1306
0
        }
1307
6
    }
1308
32
    list->count = 0;
1309
32
    list->head = NULL;
1310
32
    SKIP_AFTER_FORK(PR_Unlock(list->lock));
1311
32
    SKIP_AFTER_FORK(PR_DestroyLock(list->lock));
1312
32
    list->lock = NULL;
1313
32
}
1314
1315
void
1316
sftk_CleanupFreeLists(void)
1317
16
{
1318
16
    sftk_CleanupFreeList(&sessionObjectList, PR_TRUE);
1319
16
    sftk_CleanupFreeList(&tokenObjectList, PR_FALSE);
1320
16
}
1321
1322
/*
1323
 * Create a new object
1324
 */
1325
SFTKObject *
1326
sftk_NewObject(SFTKSlot *slot)
1327
3.07M
{
1328
3.07M
    SFTKObject *object;
1329
3.07M
    SFTKSessionObject *sessObject;
1330
3.07M
    PRBool hasLocks = PR_FALSE;
1331
3.07M
    unsigned int i;
1332
3.07M
    unsigned int hashSize = 0;
1333
1334
3.07M
    hashSize = (slot->optimizeSpace) ? SPACE_ATTRIBUTE_HASH_SIZE : TIME_ATTRIBUTE_HASH_SIZE;
1335
1336
3.07M
    object = sftk_GetObjectFromList(&hasLocks, slot->optimizeSpace,
1337
3.07M
                                    &sessionObjectList, hashSize, PR_TRUE);
1338
3.07M
    if (object == NULL) {
1339
0
        return NULL;
1340
0
    }
1341
3.07M
    sessObject = (SFTKSessionObject *)object;
1342
3.07M
    sessObject->nextAttr = 0;
1343
1344
141M
    for (i = 0; i < MAX_OBJS_ATTRS; i++) {
1345
138M
        sessObject->attrList[i].attrib.pValue = NULL;
1346
138M
        sessObject->attrList[i].freeData = PR_FALSE;
1347
138M
    }
1348
3.07M
    sessObject->optimizeSpace = slot->optimizeSpace;
1349
1350
3.07M
    object->handle = 0;
1351
3.07M
    object->next = object->prev = NULL;
1352
3.07M
    object->slot = slot;
1353
    /* set up the validation flags */
1354
3.07M
    object->validation_value = 0;
1355
3.07M
    object->validation_attribute.next = NULL;
1356
3.07M
    object->validation_attribute.prev = NULL;
1357
3.07M
    object->validation_attribute.freeAttr = PR_FALSE;
1358
3.07M
    object->validation_attribute.freeData = PR_FALSE;
1359
3.07M
    object->validation_attribute.handle = CKA_OBJECT_VALIDATION_FLAGS;
1360
3.07M
    object->validation_attribute.attrib.type = CKA_OBJECT_VALIDATION_FLAGS;
1361
3.07M
    object->validation_attribute.attrib.pValue = &object->validation_value;
1362
3.07M
    object->validation_attribute.attrib.ulValueLen = sizeof(object->validation_value);
1363
    /* initialize the FIPS flag properly */
1364
3.07M
    sftk_setFIPS(object, sftk_isFIPS(slot->slotID));
1365
3.07M
    object->source = SFTK_SOURCE_DEFAULT;
1366
1367
3.07M
    object->refCount = 1;
1368
3.07M
    object->type = SFTK_SESSION_OBJECT_TYPE;
1369
3.07M
    sessObject->sessionList.next = NULL;
1370
3.07M
    sessObject->sessionList.prev = NULL;
1371
3.07M
    sessObject->sessionList.parent = object;
1372
3.07M
    sessObject->session = NULL;
1373
3.07M
    sessObject->wasDerived = PR_FALSE;
1374
3.07M
    if (!hasLocks)
1375
3.07M
        object->refLock = PR_NewLock();
1376
3.07M
    if (object->refLock == NULL) {
1377
0
        PORT_Free(object);
1378
0
        return NULL;
1379
0
    }
1380
3.07M
    if (!hasLocks)
1381
3.07M
        sessObject->attributeLock = PR_NewLock();
1382
3.07M
    if (sessObject->attributeLock == NULL) {
1383
0
        PR_DestroyLock(object->refLock);
1384
0
        PORT_Free(object);
1385
0
        return NULL;
1386
0
    }
1387
101M
    for (i = 0; i < sessObject->hashSize; i++) {
1388
98.3M
        sessObject->head[i] = NULL;
1389
98.3M
    }
1390
3.07M
    object->objectInfo = NULL;
1391
3.07M
    object->infoFree = NULL;
1392
3.07M
    return object;
1393
3.07M
}
1394
1395
static CK_RV
1396
sftk_DestroySessionObjectData(SFTKSessionObject *so)
1397
3.07M
{
1398
3.07M
    int i;
1399
1400
141M
    for (i = 0; i < MAX_OBJS_ATTRS; i++) {
1401
138M
        SFTKAttribute *attribute = &so->attrList[i];
1402
138M
        unsigned char *value = attribute->attrib.pValue;
1403
138M
        if (value) {
1404
            /* Aborts rather than zeroize or free through a wild pointer if
1405
             * this object's memory was already destroyed and reused, or has
1406
             * been corrupted. */
1407
46.9M
            PRBool ownsHeapValue = sftk_attributeOwnsHeapValue(so, attribute);
1408
46.9M
            PORT_Memset(value, 0, attribute->attrib.ulValueLen);
1409
46.9M
            if (ownsHeapValue) {
1410
263k
                PORT_Free(value);
1411
263k
            }
1412
46.9M
            attribute->attrib.pValue = NULL;
1413
46.9M
            attribute->attrib.ulValueLen = 0;
1414
46.9M
            attribute->freeData = PR_FALSE;
1415
46.9M
        }
1416
138M
    }
1417
    /*  PR_DestroyLock(so->attributeLock);*/
1418
3.07M
    return CKR_OK;
1419
3.07M
}
1420
1421
/*
1422
 * free all the data associated with an object. Object reference count must
1423
 * be 'zero'.
1424
 */
1425
static CK_RV
1426
sftk_DestroyObject(SFTKObject *object)
1427
3.07M
{
1428
3.07M
    CK_RV crv = CKR_OK;
1429
3.07M
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1430
3.07M
    SFTKTokenObject *to = sftk_narrowToTokenObject(object);
1431
1432
3.07M
    PORT_Assert(object->refCount == 0);
1433
1434
    /* delete the database value */
1435
3.07M
    if (to) {
1436
1.95k
        if (to->dbKey.data) {
1437
0
            PORT_Free(to->dbKey.data);
1438
0
            to->dbKey.data = NULL;
1439
0
        }
1440
1.95k
    }
1441
3.07M
    if (so) {
1442
3.07M
        sftk_DestroySessionObjectData(so);
1443
3.07M
    }
1444
3.07M
    if (object->objectInfo) {
1445
237k
        (*object->infoFree)(object->objectInfo);
1446
237k
        object->objectInfo = NULL;
1447
237k
        object->infoFree = NULL;
1448
237k
    }
1449
3.07M
    if (so) {
1450
3.07M
        sftk_PutObjectToList(object, &sessionObjectList, PR_TRUE);
1451
3.07M
    } else {
1452
1.95k
        sftk_PutObjectToList(object, &tokenObjectList, PR_FALSE);
1453
1.95k
    }
1454
3.07M
    return crv;
1455
3.07M
}
1456
1457
void
1458
sftk_ReferenceObject(SFTKObject *object)
1459
12.0M
{
1460
12.0M
    PR_Lock(object->refLock);
1461
    /* A zero count means this object has already been destroyed; abort
1462
     * before the new reference is used to operate on freed memory. */
1463
12.0M
    PORT_ReleaseAssert(object->refCount > 0);
1464
12.0M
    object->refCount++;
1465
12.0M
    PR_Unlock(object->refLock);
1466
12.0M
}
1467
1468
static SFTKObject *
1469
sftk_ObjectFromHandleOnSlot(CK_OBJECT_HANDLE handle, SFTKSlot *slot)
1470
9.12M
{
1471
9.12M
    SFTKObject *object;
1472
9.12M
    PRUint32 index = sftk_hash(handle, slot->sessObjHashSize);
1473
1474
9.12M
    if (sftk_isToken(handle)) {
1475
1.94k
        return sftk_NewTokenObject(slot, NULL, handle);
1476
1.94k
    }
1477
1478
9.12M
    PR_Lock(slot->objectLock);
1479
9.12M
    sftkqueue_find2(object, handle, index, slot->sessObjHashTable);
1480
9.12M
    if (object) {
1481
9.12M
        sftk_ReferenceObject(object);
1482
9.12M
    }
1483
9.12M
    PR_Unlock(slot->objectLock);
1484
1485
9.12M
    return (object);
1486
9.12M
}
1487
/*
1488
 * look up and object structure from a handle. OBJECT_Handles only make
1489
 * sense in terms of a given session.  make a reference to that object
1490
 * structure returned.
1491
 */
1492
SFTKObject *
1493
sftk_ObjectFromHandle(CK_OBJECT_HANDLE handle, SFTKSession *session)
1494
9.12M
{
1495
9.12M
    SFTKSlot *slot = sftk_SlotFromSession(session);
1496
1497
9.12M
    return sftk_ObjectFromHandleOnSlot(handle, slot);
1498
9.12M
}
1499
1500
/*
1501
 * release a reference to an object handle
1502
 */
1503
SFTKFreeStatus
1504
sftk_FreeObject(SFTKObject *object)
1505
15.1M
{
1506
15.1M
    PRBool destroy = PR_FALSE;
1507
15.1M
    CK_RV crv;
1508
1509
15.1M
    PR_Lock(object->refLock);
1510
    /* A zero count means this object has already been destroyed. Abort,
1511
     * like an allocator that detects a double free, rather than tear the
1512
     * object down a second time. */
1513
15.1M
    PORT_ReleaseAssert(object->refCount > 0);
1514
15.1M
    if (object->refCount == 1)
1515
3.07M
        destroy = PR_TRUE;
1516
15.1M
    object->refCount--;
1517
15.1M
    PR_Unlock(object->refLock);
1518
1519
15.1M
    if (destroy) {
1520
3.07M
        crv = sftk_DestroyObject(object);
1521
3.07M
        if (crv != CKR_OK) {
1522
0
            return SFTK_DestroyFailure;
1523
0
        }
1524
3.07M
        return SFTK_Destroyed;
1525
3.07M
    }
1526
12.0M
    return SFTK_Busy;
1527
15.1M
}
1528
1529
/* find the next available object handle that isn't currently in use */
1530
/* NOTE: This function could loop forever if we've exhausted all
1531
 * 3^31-1 handles. This is highly unlikely (NSS has been running for
1532
 * decades with this code) uless we start increasing the size of the
1533
 * SFTK_TOKEN_MASK (which is just the high bit currently). */
1534
CK_OBJECT_HANDLE
1535
sftk_getNextHandle(SFTKSlot *slot)
1536
2.92M
{
1537
2.92M
    CK_OBJECT_HANDLE handle;
1538
2.92M
    SFTKObject *duplicateObject = NULL;
1539
2.92M
    do {
1540
2.92M
        PRUint32 wrappedAround;
1541
1542
2.92M
        duplicateObject = NULL;
1543
2.92M
        PR_Lock(slot->objectLock);
1544
2.92M
        wrappedAround = slot->sessionObjectHandleCount & SFTK_TOKEN_MASK;
1545
2.92M
        handle = slot->sessionObjectHandleCount & ~SFTK_TOKEN_MASK;
1546
2.92M
        if (!handle) /* don't allow zero handle */
1547
0
            handle = NSC_MIN_SESSION_OBJECT_HANDLE;
1548
2.92M
        slot->sessionObjectHandleCount = (handle + 1U) | wrappedAround;
1549
        /* Is there already a session object with this handle? */
1550
2.92M
        if (wrappedAround) {
1551
0
            sftkqueue_find(duplicateObject, handle, slot->sessObjHashTable,
1552
0
                           slot->sessObjHashSize);
1553
0
        }
1554
2.92M
        PR_Unlock(slot->objectLock);
1555
2.92M
    } while (duplicateObject != NULL);
1556
2.92M
    return handle;
1557
2.92M
}
1558
1559
/*
1560
 * Claim the right to remove a session object from the slot's object hash.
1561
 * Must be called with slot->objectLock held.
1562
 *
1563
 * Several threads can reach the same object: handles are slot-global, so any
1564
 * session can resolve one through sftk_ObjectFromHandle, and
1565
 * sftk_ClearSession claims removals too when the owning session is closed.
1566
 * Only the thread that finds the object still queued unlinks it; without that,
1567
 * each would unlink again and drop the queues' reference a second time.
1568
 *
1569
 * Returns PR_TRUE if this caller owns the removal, and with it the reference
1570
 * the queues held. Drop that reference with sftk_FreeObject() after releasing
1571
 * slot->objectLock.
1572
 */
1573
static PRBool
1574
sftk_ClaimObjectRemovalLocked(SFTKSlot *slot, SFTKObject *object)
1575
2.91M
{
1576
2.91M
    PRUint32 index = sftk_hash(object->handle, slot->sessObjHashSize);
1577
1578
2.91M
    if (!object->next && !object->prev &&
1579
2.07M
        slot->sessObjHashTable[index] != object) {
1580
0
        return PR_FALSE;
1581
0
    }
1582
2.91M
    sftkqueue_delete2(object, object->handle, index, slot->sessObjHashTable);
1583
    /* sftkqueue_delete2 patches the neighbours but leaves object->next/prev
1584
     * pointing at them. Clear them here so the next thread to take the lock
1585
     * sees an unqueued object and does not re-claim the removal. */
1586
2.91M
    sftkqueue_clear_deleted_element(object);
1587
2.91M
    return PR_TRUE;
1588
2.91M
}
1589
1590
/*
1591
 * add an object to the slot's object hash and to its session's object list
1592
 */
1593
void
1594
sftk_AddObject(SFTKSession *session, SFTKObject *object)
1595
2.91M
{
1596
2.91M
    SFTKSlot *slot = sftk_SlotFromSession(session);
1597
2.91M
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1598
2.91M
    PRUint32 index = sftk_hash(object->handle, slot->sessObjHashSize);
1599
1600
    /* the reference the queues hold, taken before the object is reachable */
1601
2.91M
    sftk_ReferenceObject(object);
1602
1603
    /* Both queues are linked under slot->objectLock in one critical section.
1604
     * That gives the invariant the teardown paths depend on: a session object
1605
     * is on its owning session's list if and only if it is in the slot's
1606
     * object hash. See sftk_DeleteObject(). */
1607
2.91M
    sftkqueue_init_element(object);
1608
2.91M
    PR_Lock(slot->objectLock);
1609
2.91M
    if (so) {
1610
2.91M
        so->session = session;
1611
2.91M
        sftkqueue_add(&so->sessionList, 0, session->objects, 0);
1612
2.91M
    }
1613
2.91M
    sftkqueue_add2(object, object->handle, index, slot->sessObjHashTable);
1614
2.91M
    PR_Unlock(slot->objectLock);
1615
2.91M
}
1616
1617
/*
1618
 * delete an object from a slot and session queue
1619
 */
1620
CK_RV
1621
sftk_DeleteObject(SFTKSession *session, SFTKObject *object)
1622
2.91M
{
1623
2.91M
    SFTKSlot *slot = sftk_SlotFromSession(session);
1624
2.91M
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1625
2.91M
    CK_RV crv = CKR_OK;
1626
1627
    /* Handle Token case */
1628
2.91M
    if (so && so->session) {
1629
2.91M
        PRBool ownsRemove;
1630
1631
        /* so->session is the session that created the object; it need not be
1632
         * the caller's session, and we hold no reference on it. Winning the
1633
         * claim is what makes it safe to touch: the object was still in the
1634
         * slot hash, so by the invariant in sftk_AddObject() it is still on
1635
         * so->session's list, so sftk_ClearSession() has not run for that
1636
         * session and the session has not been freed. */
1637
2.91M
        PR_Lock(slot->objectLock);
1638
2.91M
        ownsRemove = sftk_ClaimObjectRemovalLocked(slot, object);
1639
2.91M
        if (ownsRemove) {
1640
2.91M
            PORT_Assert(sftkqueue_is_queued(&so->sessionList, 0,
1641
2.91M
                                            so->session->objects, 0));
1642
2.91M
            sftkqueue_delete(&so->sessionList, 0, so->session->objects, 0);
1643
2.91M
        }
1644
2.91M
        PR_Unlock(slot->objectLock);
1645
1646
2.91M
        if (ownsRemove) {
1647
2.91M
            sftk_FreeObject(object); /* drop the queues' reference */
1648
2.91M
        }
1649
2.91M
    } else {
1650
0
        SFTKDBHandle *handle = sftk_getDBForTokenObject(slot, object->handle);
1651
0
#ifdef DEBUG
1652
0
        SFTKTokenObject *to = sftk_narrowToTokenObject(object);
1653
0
        PORT_Assert(to);
1654
0
#endif
1655
0
        crv = sftkdb_DestroyObject(handle, object->handle, object->objclass);
1656
0
        sftk_freeDB(handle);
1657
0
    }
1658
2.91M
    return crv;
1659
2.91M
}
1660
1661
/*
1662
 * Token objects don't explicitly store their attributes, so we need to know
1663
 * what attributes make up a particular token object before we can copy it.
1664
 * below are the tables by object type.
1665
 */
1666
static const CK_ATTRIBUTE_TYPE commonAttrs[] = {
1667
    CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_MODIFIABLE
1668
};
1669
static const CK_ULONG commonAttrsCount =
1670
    sizeof(commonAttrs) / sizeof(commonAttrs[0]);
1671
1672
static const CK_ATTRIBUTE_TYPE commonKeyAttrs[] = {
1673
    CKA_ID, CKA_START_DATE, CKA_END_DATE, CKA_DERIVE, CKA_LOCAL, CKA_KEY_TYPE
1674
};
1675
static const CK_ULONG commonKeyAttrsCount =
1676
    sizeof(commonKeyAttrs) / sizeof(commonKeyAttrs[0]);
1677
1678
static const CK_ATTRIBUTE_TYPE secretKeyAttrs[] = {
1679
    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN,
1680
    CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_VALUE
1681
};
1682
static const CK_ULONG secretKeyAttrsCount =
1683
    sizeof(secretKeyAttrs) / sizeof(secretKeyAttrs[0]);
1684
1685
static const CK_ATTRIBUTE_TYPE commonPubKeyAttrs[] = {
1686
    CKA_ENCRYPT, CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_WRAP, CKA_SUBJECT
1687
};
1688
static const CK_ULONG commonPubKeyAttrsCount =
1689
    sizeof(commonPubKeyAttrs) / sizeof(commonPubKeyAttrs[0]);
1690
1691
static const CK_ATTRIBUTE_TYPE rsaPubKeyAttrs[] = {
1692
    CKA_MODULUS, CKA_PUBLIC_EXPONENT
1693
};
1694
static const CK_ULONG rsaPubKeyAttrsCount =
1695
    sizeof(rsaPubKeyAttrs) / sizeof(rsaPubKeyAttrs[0]);
1696
1697
static const CK_ATTRIBUTE_TYPE dsaPubKeyAttrs[] = {
1698
    CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE
1699
};
1700
static const CK_ULONG dsaPubKeyAttrsCount =
1701
    sizeof(dsaPubKeyAttrs) / sizeof(dsaPubKeyAttrs[0]);
1702
1703
static const CK_ATTRIBUTE_TYPE dhPubKeyAttrs[] = {
1704
    CKA_PRIME, CKA_BASE, CKA_VALUE
1705
};
1706
static const CK_ULONG dhPubKeyAttrsCount =
1707
    sizeof(dhPubKeyAttrs) / sizeof(dhPubKeyAttrs[0]);
1708
static const CK_ATTRIBUTE_TYPE ecPubKeyAttrs[] = {
1709
    CKA_EC_PARAMS, CKA_EC_POINT
1710
};
1711
static const CK_ULONG ecPubKeyAttrsCount =
1712
    sizeof(ecPubKeyAttrs) / sizeof(ecPubKeyAttrs[0]);
1713
1714
static const CK_ATTRIBUTE_TYPE mldsaPubKeyAttrs[] = {
1715
    CKA_PARAMETER_SET, CKA_VALUE
1716
};
1717
static const CK_ULONG mldsaPubKeyAttrsCount = PR_ARRAY_SIZE(mldsaPubKeyAttrs);
1718
1719
/* the vendor ML-KEM key types carry CKA_NSS_PARAMETER_SET rather than
1720
 * CKA_PARAMETER_SET; list both and let the missing one be skipped */
1721
static const CK_ATTRIBUTE_TYPE mlkemPubKeyAttrs[] = {
1722
    CKA_PARAMETER_SET, CKA_NSS_PARAMETER_SET, CKA_VALUE
1723
};
1724
static const CK_ULONG mlkemPubKeyAttrsCount = PR_ARRAY_SIZE(mlkemPubKeyAttrs);
1725
1726
static const CK_ATTRIBUTE_TYPE commonPrivKeyAttrs[] = {
1727
    CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER, CKA_UNWRAP, CKA_SUBJECT,
1728
    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_NSS_DB, CKA_PUBLIC_KEY_INFO
1729
};
1730
static const CK_ULONG commonPrivKeyAttrsCount =
1731
    sizeof(commonPrivKeyAttrs) / sizeof(commonPrivKeyAttrs[0]);
1732
1733
static const CK_ATTRIBUTE_TYPE rsaPrivKeyAttrs[] = {
1734
    CKA_MODULUS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
1735
    CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT
1736
};
1737
static const CK_ULONG rsaPrivKeyAttrsCount =
1738
    sizeof(rsaPrivKeyAttrs) / sizeof(rsaPrivKeyAttrs[0]);
1739
1740
static const CK_ATTRIBUTE_TYPE dsaPrivKeyAttrs[] = {
1741
    CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE
1742
};
1743
static const CK_ULONG dsaPrivKeyAttrsCount =
1744
    sizeof(dsaPrivKeyAttrs) / sizeof(dsaPrivKeyAttrs[0]);
1745
1746
static const CK_ATTRIBUTE_TYPE dhPrivKeyAttrs[] = {
1747
    CKA_PRIME, CKA_BASE, CKA_VALUE
1748
};
1749
static const CK_ULONG dhPrivKeyAttrsCount =
1750
    sizeof(dhPrivKeyAttrs) / sizeof(dhPrivKeyAttrs[0]);
1751
static const CK_ATTRIBUTE_TYPE ecPrivKeyAttrs[] = {
1752
    CKA_EC_PARAMS, CKA_VALUE
1753
};
1754
static const CK_ULONG ecPrivKeyAttrsCount =
1755
    sizeof(ecPrivKeyAttrs) / sizeof(ecPrivKeyAttrs[0]);
1756
1757
static const CK_ATTRIBUTE_TYPE mldsaPrivKeyAttrs[] = {
1758
    CKA_PARAMETER_SET, CKA_VALUE, CKA_SEED
1759
};
1760
static const CK_ULONG mldsaPrivKeyAttrsCount = PR_ARRAY_SIZE(mldsaPrivKeyAttrs);
1761
1762
static const CK_ATTRIBUTE_TYPE mlkemPrivKeyAttrs[] = {
1763
    CKA_PARAMETER_SET, CKA_NSS_PARAMETER_SET, CKA_VALUE, CKA_SEED
1764
};
1765
static const CK_ULONG mlkemPrivKeyAttrsCount = PR_ARRAY_SIZE(mlkemPrivKeyAttrs);
1766
1767
static const CK_ATTRIBUTE_TYPE certAttrs[] = {
1768
    CKA_CERTIFICATE_TYPE, CKA_VALUE, CKA_SUBJECT, CKA_ISSUER, CKA_SERIAL_NUMBER
1769
};
1770
static const CK_ULONG certAttrsCount =
1771
    sizeof(certAttrs) / sizeof(certAttrs[0]);
1772
1773
static const CK_ATTRIBUTE_TYPE nssTrustAttrs[] = {
1774
    CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_NSS_CERT_SHA1_HASH,
1775
    CKA_NSS_CERT_MD5_HASH, CKA_NSS_TRUST_SERVER_AUTH, CKA_NSS_TRUST_CLIENT_AUTH,
1776
    CKA_NSS_TRUST_EMAIL_PROTECTION, CKA_NSS_TRUST_CODE_SIGNING,
1777
    CKA_NSS_TRUST_STEP_UP_APPROVED
1778
};
1779
static const CK_ULONG nssTrustAttrsCount =
1780
    sizeof(nssTrustAttrs) / sizeof(nssTrustAttrs[0]);
1781
1782
static const CK_ATTRIBUTE_TYPE trustAttrs[] = {
1783
    CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_HASH_OF_CERTIFICATE,
1784
    CKA_NAME_HASH_ALGORITHM, CKA_PKCS_TRUST_SERVER_AUTH,
1785
    CKA_PKCS_TRUST_CLIENT_AUTH, CKA_PKCS_TRUST_EMAIL_PROTECTION,
1786
    CKA_PKCS_TRUST_CODE_SIGNING
1787
};
1788
static const CK_ULONG trustAttrsCount =
1789
    sizeof(trustAttrs) / sizeof(trustAttrs[0]);
1790
1791
static const CK_ATTRIBUTE_TYPE smimeAttrs[] = {
1792
    CKA_SUBJECT, CKA_NSS_EMAIL, CKA_NSS_SMIME_TIMESTAMP, CKA_VALUE
1793
};
1794
static const CK_ULONG smimeAttrsCount =
1795
    sizeof(smimeAttrs) / sizeof(smimeAttrs[0]);
1796
1797
static const CK_ATTRIBUTE_TYPE crlAttrs[] = {
1798
    CKA_SUBJECT, CKA_VALUE, CKA_NSS_URL, CKA_NSS_KRL
1799
};
1800
static const CK_ULONG crlAttrsCount =
1801
    sizeof(crlAttrs) / sizeof(crlAttrs[0]);
1802
1803
/* copy an object based on it's table */
1804
CK_RV
1805
stfk_CopyTokenAttributes(SFTKObject *destObject, SFTKTokenObject *src_to,
1806
                         const CK_ATTRIBUTE_TYPE *attrArray, CK_ULONG attrCount)
1807
0
{
1808
0
    SFTKAttribute *attribute;
1809
0
    SFTKAttribute *newAttribute;
1810
0
    CK_RV crv = CKR_OK;
1811
0
    unsigned int i;
1812
1813
0
    for (i = 0; i < attrCount; i++) {
1814
0
        if (!sftk_hasAttribute(destObject, attrArray[i])) {
1815
0
            attribute = sftk_FindAttribute(&src_to->obj, attrArray[i]);
1816
0
            if (!attribute) {
1817
0
                continue; /* return CKR_ATTRIBUTE_VALUE_INVALID; */
1818
0
            }
1819
            /* we need to copy the attribute since each attribute
1820
             * only has one set of link list pointers */
1821
0
            newAttribute = sftk_NewAttribute(destObject,
1822
0
                                             sftk_attr_expand(&attribute->attrib));
1823
0
            sftk_FreeAttribute(attribute); /* free the old attribute */
1824
0
            if (!newAttribute) {
1825
0
                return CKR_HOST_MEMORY;
1826
0
            }
1827
0
            sftk_AddAttribute(destObject, newAttribute);
1828
0
        }
1829
0
    }
1830
0
    return crv;
1831
0
}
1832
1833
CK_RV
1834
stfk_CopyTokenPrivateKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1835
0
{
1836
0
    CK_RV crv;
1837
0
    CK_KEY_TYPE key_type;
1838
0
    SFTKAttribute *attribute;
1839
1840
    /* copy the common attributes for all keys first */
1841
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1842
0
                                   commonKeyAttrsCount);
1843
0
    if (crv != CKR_OK) {
1844
0
        goto fail;
1845
0
    }
1846
    /* copy the common attributes for all private keys next */
1847
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonPrivKeyAttrs,
1848
0
                                   commonPrivKeyAttrsCount);
1849
0
    if (crv != CKR_OK) {
1850
0
        goto fail;
1851
0
    }
1852
0
    attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE);
1853
0
    PORT_Assert(attribute); /* if it wasn't here, ww should have failed
1854
                             * copying the common attributes */
1855
0
    if (!attribute) {
1856
        /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but
1857
         * the fact is, the only reason we couldn't get the attribute would
1858
         * be a memory error or database error (an error in the 'device').
1859
         * if we have a database error code, we could return it here */
1860
0
        crv = CKR_DEVICE_ERROR;
1861
0
        goto fail;
1862
0
    }
1863
0
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1864
0
    sftk_FreeAttribute(attribute);
1865
1866
    /* finally copy the attributes for various private key types */
1867
0
    switch (key_type) {
1868
0
        case CKK_RSA:
1869
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPrivKeyAttrs,
1870
0
                                           rsaPrivKeyAttrsCount);
1871
0
            break;
1872
0
        case CKK_DSA:
1873
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPrivKeyAttrs,
1874
0
                                           dsaPrivKeyAttrsCount);
1875
0
            break;
1876
0
        case CKK_ML_DSA:
1877
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, mldsaPrivKeyAttrs,
1878
0
                                           mldsaPrivKeyAttrsCount);
1879
0
            break;
1880
0
        case CKK_NSS_ML_KEM:
1881
0
        case CKK_ML_KEM:
1882
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, mlkemPrivKeyAttrs,
1883
0
                                           mlkemPrivKeyAttrsCount);
1884
0
            break;
1885
0
        case CKK_DH:
1886
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dhPrivKeyAttrs,
1887
0
                                           dhPrivKeyAttrsCount);
1888
0
            break;
1889
0
        case CKK_EC:
1890
0
        case CKK_EC_EDWARDS:
1891
0
        case CKK_EC_MONTGOMERY:
1892
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, ecPrivKeyAttrs,
1893
0
                                           ecPrivKeyAttrsCount);
1894
0
            break;
1895
0
        default:
1896
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
1897
                                     * of token keys into our database. */
1898
0
    }
1899
0
fail:
1900
0
    return crv;
1901
0
}
1902
1903
CK_RV
1904
stfk_CopyTokenPublicKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1905
0
{
1906
0
    CK_RV crv;
1907
0
    CK_KEY_TYPE key_type;
1908
0
    SFTKAttribute *attribute;
1909
1910
    /* copy the common attributes for all keys first */
1911
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1912
0
                                   commonKeyAttrsCount);
1913
0
    if (crv != CKR_OK) {
1914
0
        goto fail;
1915
0
    }
1916
1917
    /* copy the common attributes for all public keys next */
1918
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonPubKeyAttrs,
1919
0
                                   commonPubKeyAttrsCount);
1920
0
    if (crv != CKR_OK) {
1921
0
        goto fail;
1922
0
    }
1923
0
    attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE);
1924
0
    PORT_Assert(attribute); /* if it wasn't here, ww should have failed
1925
                             * copying the common attributes */
1926
0
    if (!attribute) {
1927
        /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but
1928
         * the fact is, the only reason we couldn't get the attribute would
1929
         * be a memory error or database error (an error in the 'device').
1930
         * if we have a database error code, we could return it here */
1931
0
        crv = CKR_DEVICE_ERROR;
1932
0
        goto fail;
1933
0
    }
1934
0
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1935
0
    sftk_FreeAttribute(attribute);
1936
1937
    /* finally copy the attributes for various public key types */
1938
0
    switch (key_type) {
1939
0
        case CKK_RSA:
1940
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPubKeyAttrs,
1941
0
                                           rsaPubKeyAttrsCount);
1942
0
            break;
1943
0
        case CKK_DSA:
1944
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPubKeyAttrs,
1945
0
                                           dsaPubKeyAttrsCount);
1946
0
            break;
1947
0
        case CKK_ML_DSA:
1948
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, mldsaPubKeyAttrs,
1949
0
                                           mldsaPubKeyAttrsCount);
1950
0
            break;
1951
0
        case CKK_NSS_ML_KEM:
1952
0
        case CKK_ML_KEM:
1953
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, mlkemPubKeyAttrs,
1954
0
                                           mlkemPubKeyAttrsCount);
1955
0
            break;
1956
0
        case CKK_DH:
1957
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dhPubKeyAttrs,
1958
0
                                           dhPubKeyAttrsCount);
1959
0
            break;
1960
0
        case CKK_EC:
1961
0
        case CKK_EC_EDWARDS:
1962
0
        case CKK_EC_MONTGOMERY:
1963
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, ecPubKeyAttrs,
1964
0
                                           ecPubKeyAttrsCount);
1965
0
            break;
1966
0
        default:
1967
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
1968
                                     * of token keys into our database. */
1969
0
    }
1970
0
fail:
1971
0
    return crv;
1972
0
}
1973
CK_RV
1974
stfk_CopyTokenSecretKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1975
0
{
1976
0
    CK_RV crv;
1977
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1978
0
                                   commonKeyAttrsCount);
1979
0
    if (crv != CKR_OK) {
1980
0
        goto fail;
1981
0
    }
1982
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, secretKeyAttrs,
1983
0
                                   secretKeyAttrsCount);
1984
0
fail:
1985
0
    return crv;
1986
0
}
1987
1988
/*
1989
 * Copy a token object. We need to explicitly copy the relevant
1990
 * attributes since token objects don't store those attributes in
1991
 * the token itself.
1992
 */
1993
CK_RV
1994
sftk_CopyTokenObject(SFTKObject *destObject, SFTKObject *srcObject)
1995
0
{
1996
0
    SFTKTokenObject *src_to = sftk_narrowToTokenObject(srcObject);
1997
0
    CK_RV crv;
1998
1999
0
    PORT_Assert(src_to);
2000
0
    if (src_to == NULL) {
2001
0
        return CKR_DEVICE_ERROR; /* internal state inconsistant */
2002
0
    }
2003
2004
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonAttrs,
2005
0
                                   commonAttrsCount);
2006
0
    if (crv != CKR_OK) {
2007
0
        goto fail;
2008
0
    }
2009
0
    switch (src_to->obj.objclass) {
2010
0
        case CKO_CERTIFICATE:
2011
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, certAttrs,
2012
0
                                           certAttrsCount);
2013
0
            break;
2014
0
        case CKO_NSS_TRUST:
2015
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, nssTrustAttrs,
2016
0
                                           nssTrustAttrsCount);
2017
0
            break;
2018
0
        case CKO_TRUST:
2019
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, trustAttrs,
2020
0
                                           trustAttrsCount);
2021
0
            break;
2022
0
        case CKO_NSS_SMIME:
2023
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, smimeAttrs,
2024
0
                                           smimeAttrsCount);
2025
0
            break;
2026
0
        case CKO_NSS_CRL:
2027
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, crlAttrs,
2028
0
                                           crlAttrsCount);
2029
0
            break;
2030
0
        case CKO_PRIVATE_KEY:
2031
0
            crv = stfk_CopyTokenPrivateKey(destObject, src_to);
2032
0
            break;
2033
0
        case CKO_PUBLIC_KEY:
2034
0
            crv = stfk_CopyTokenPublicKey(destObject, src_to);
2035
0
            break;
2036
0
        case CKO_SECRET_KEY:
2037
0
            crv = stfk_CopyTokenSecretKey(destObject, src_to);
2038
0
            break;
2039
0
        default:
2040
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
2041
                                     * of token keys into our database. */
2042
0
    }
2043
0
fail:
2044
0
    return crv;
2045
0
}
2046
2047
/*
2048
 * copy the attributes from one object to another. Don't overwrite existing
2049
 * attributes. NOTE: This is a pretty expensive operation since it
2050
 * grabs the attribute locks for the src object for a *long* time.
2051
 */
2052
CK_RV
2053
sftk_CopyObject(SFTKObject *destObject, SFTKObject *srcObject)
2054
393k
{
2055
393k
    SFTKAttribute *attribute;
2056
393k
    SFTKSessionObject *src_so = sftk_narrowToSessionObject(srcObject);
2057
393k
    SFTKSessionObject *dest_so = sftk_narrowToSessionObject(destObject);
2058
393k
    unsigned int i;
2059
2060
393k
    destObject->validation_value = srcObject->validation_value;
2061
393k
    destObject->source = srcObject->source;
2062
393k
    if (src_so == NULL) {
2063
0
        return sftk_CopyTokenObject(destObject, srcObject);
2064
0
    }
2065
393k
    PORT_Assert(dest_so != NULL);
2066
393k
    if (dest_so == NULL) {
2067
0
        return CKR_ARGUMENTS_BAD;
2068
0
    }
2069
2070
393k
    PR_Lock(src_so->attributeLock);
2071
12.9M
    for (i = 0; i < src_so->hashSize; i++) {
2072
12.5M
        attribute = src_so->head[i];
2073
12.9M
        do {
2074
12.9M
            if (attribute) {
2075
2.33M
                SFTKAttribute *existing;
2076
2.33M
                sftkqueue_find(existing, attribute->handle,
2077
2.33M
                               dest_so->head, dest_so->hashSize);
2078
2.33M
                if (!existing) {
2079
                    /* we need to copy the attribute since each attribute
2080
                     * only has one set of link list pointers */
2081
2.33M
                    SFTKAttribute *newAttribute = sftk_InitAttribute(
2082
2.33M
                        dest_so, dest_so->nextAttr++,
2083
2.33M
                        sftk_attr_expand(&attribute->attrib));
2084
2.33M
                    if (newAttribute == NULL) {
2085
0
                        PR_Unlock(src_so->attributeLock);
2086
0
                        return CKR_HOST_MEMORY;
2087
0
                    }
2088
2.33M
                    sftkqueue_add(newAttribute, newAttribute->handle,
2089
2.33M
                                  dest_so->head, dest_so->hashSize);
2090
2.33M
                }
2091
2.33M
                attribute = attribute->next;
2092
2.33M
            }
2093
12.9M
        } while (attribute != NULL);
2094
12.5M
    }
2095
393k
    PR_Unlock(src_so->attributeLock);
2096
2097
393k
    return CKR_OK;
2098
393k
}
2099
2100
/*
2101
 * ******************** Search Utilities *******************************
2102
 */
2103
2104
/* add an object to a search list */
2105
CK_RV
2106
AddToList(SFTKObjectListElement **list, SFTKObject *object)
2107
0
{
2108
0
    SFTKObjectListElement *newElem =
2109
0
        (SFTKObjectListElement *)PORT_Alloc(sizeof(SFTKObjectListElement));
2110
2111
0
    if (newElem == NULL)
2112
0
        return CKR_HOST_MEMORY;
2113
2114
0
    newElem->next = *list;
2115
0
    newElem->object = object;
2116
0
    sftk_ReferenceObject(object);
2117
2118
0
    *list = newElem;
2119
0
    return CKR_OK;
2120
0
}
2121
2122
/* return true if the object matches the template */
2123
PRBool
2124
sftk_objectMatch(SFTKObject *object, CK_ATTRIBUTE_PTR theTemplate, int count)
2125
376
{
2126
376
    int i;
2127
2128
668
    for (i = 0; i < count; i++) {
2129
668
        SFTKAttribute *attribute = sftk_FindAttribute(object, theTemplate[i].type);
2130
668
        if (attribute == NULL) {
2131
0
            return PR_FALSE;
2132
0
        }
2133
668
        if (attribute->attrib.ulValueLen == theTemplate[i].ulValueLen) {
2134
584
            if (PORT_Memcmp(attribute->attrib.pValue, theTemplate[i].pValue,
2135
584
                            theTemplate[i].ulValueLen) == 0) {
2136
292
                sftk_FreeAttribute(attribute);
2137
292
                continue;
2138
292
            }
2139
584
        }
2140
376
        sftk_FreeAttribute(attribute);
2141
376
        return PR_FALSE;
2142
668
    }
2143
0
    return PR_TRUE;
2144
376
}
2145
2146
/* search through all the objects in the queue and return the template matches
2147
 * in the object list.
2148
 */
2149
CK_RV
2150
sftk_searchObjectList(SFTKSearchResults *search, SFTKObject **head,
2151
                      unsigned int size, PRLock *lock, CK_ATTRIBUTE_PTR theTemplate,
2152
                      int count, PRBool isLoggedIn)
2153
6.11k
{
2154
6.11k
    unsigned int i;
2155
6.11k
    SFTKObject *object;
2156
6.11k
    CK_RV crv = CKR_OK;
2157
2158
6.11k
    PR_Lock(lock);
2159
201k
    for (i = 0; i < size; i++) {
2160
196k
        for (object = head[i]; object != NULL; object = object->next) {
2161
376
            if (sftk_objectMatch(object, theTemplate, count)) {
2162
                /* don't return objects that aren't yet visible */
2163
0
                if ((!isLoggedIn) && sftk_isTrue(object, CKA_PRIVATE))
2164
0
                    continue;
2165
0
                sftk_addHandle(search, object->handle);
2166
0
            }
2167
376
        }
2168
195k
    }
2169
6.11k
    PR_Unlock(lock);
2170
6.11k
    return crv;
2171
6.11k
}
2172
2173
/*
2174
 * free a single list element. Return the Next object in the list.
2175
 */
2176
SFTKObjectListElement *
2177
sftk_FreeObjectListElement(SFTKObjectListElement *objectList)
2178
0
{
2179
0
    SFTKObjectListElement *ol = objectList->next;
2180
2181
0
    sftk_FreeObject(objectList->object);
2182
0
    PORT_Free(objectList);
2183
0
    return ol;
2184
0
}
2185
2186
/* free an entire object list */
2187
void
2188
sftk_FreeObjectList(SFTKObjectListElement *objectList)
2189
0
{
2190
0
    SFTKObjectListElement *ol;
2191
2192
0
    for (ol = objectList; ol != NULL; ol = sftk_FreeObjectListElement(ol)) {
2193
0
    }
2194
0
}
2195
2196
/*
2197
 * free a search structure
2198
 */
2199
void
2200
sftk_FreeSearch(SFTKSearchResults *search)
2201
1.72M
{
2202
1.72M
    if (search->handles) {
2203
1.72M
        PORT_Free(search->handles);
2204
1.72M
    }
2205
1.72M
    PORT_Free(search);
2206
1.72M
}
2207
2208
/*
2209
 * ******************** Session Utilities *******************************
2210
 */
2211
2212
/* update the sessions state based in it's flags and wether or not it's
2213
 * logged in */
2214
void
2215
sftk_update_state(SFTKSlot *slot, SFTKSession *session)
2216
5.61M
{
2217
5.61M
    PR_Lock(slot->slotLock);
2218
5.61M
    if (slot->isLoggedIn) {
2219
2
        if (slot->ssoLoggedIn) {
2220
2
            session->info.state = CKS_RW_SO_FUNCTIONS;
2221
2
        } else if (session->info.flags & CKF_RW_SESSION) {
2222
0
            session->info.state = CKS_RW_USER_FUNCTIONS;
2223
0
        } else {
2224
0
            session->info.state = CKS_RO_USER_FUNCTIONS;
2225
0
        }
2226
5.61M
    } else {
2227
5.61M
        if (session->info.flags & CKF_RW_SESSION) {
2228
894
            session->info.state = CKS_RW_PUBLIC_SESSION;
2229
5.61M
        } else {
2230
5.61M
            session->info.state = CKS_RO_PUBLIC_SESSION;
2231
5.61M
        }
2232
5.61M
    }
2233
5.61M
    PR_Unlock(slot->slotLock);
2234
5.61M
}
2235
2236
/* update the state of all the sessions on a slot */
2237
void
2238
sftk_update_all_states(SFTKSlot *slot)
2239
2
{
2240
2
    unsigned int i;
2241
2
    SFTKSession *session;
2242
2243
66
    for (i = 0; i < slot->sessHashSize; i++) {
2244
64
        PRLock *lock = SFTK_HEAD_BUCKET_LOCK(slot, i);
2245
64
        PR_Lock(lock);
2246
68
        for (session = slot->head[i]; session; session = session->next) {
2247
4
            sftk_update_state(slot, session);
2248
4
        }
2249
64
        PR_Unlock(lock);
2250
64
    }
2251
2
}
2252
2253
/*
2254
 * context are cipher and digest contexts that are associated with a session
2255
 */
2256
void
2257
sftk_FreeContext(SFTKSessionContext *context)
2258
3.02M
{
2259
3.02M
    if (context->cipherInfo) {
2260
3.02M
        (*context->destroy)(context->cipherInfo, PR_TRUE);
2261
3.02M
    }
2262
3.02M
    if (context->hashInfo) {
2263
441k
        (*context->hashdestroy)(context->hashInfo, PR_TRUE);
2264
441k
    }
2265
3.02M
    if (context->key) {
2266
1.48M
        sftk_FreeObject(context->key);
2267
1.48M
        context->key = NULL;
2268
1.48M
    }
2269
3.02M
    if (context->signature) {
2270
21.0k
        SECITEM_FreeItem(context->signature, PR_TRUE);
2271
21.0k
        context->signature = NULL;
2272
21.0k
    }
2273
3.02M
    PORT_Free(context);
2274
3.02M
}
2275
2276
/*
2277
 * Init a new session. NOTE: The session handle is not set, and the
2278
 * session is not added to the slot's session queue.
2279
 */
2280
CK_RV
2281
sftk_InitSession(SFTKSession *session, SFTKSlot *slot, CK_SLOT_ID slotID,
2282
                 CK_NOTIFY notify, CK_VOID_PTR pApplication, CK_FLAGS flags)
2283
2.80M
{
2284
2.80M
    session->next = session->prev = NULL;
2285
2.80M
    session->refCount = 1;
2286
2.80M
    session->enc_context = NULL;
2287
2.80M
    session->hash_context = NULL;
2288
2.80M
    session->search = NULL;
2289
2.80M
    session->objectIDCount = 1;
2290
    /* session->objects[] is protected by slot->objectLock, not by a
2291
     * per-session lock -- see the lock notes on SFTKSlotStr. */
2292
2.80M
    session->objects[0] = NULL;
2293
2294
2.80M
    session->slot = slot;
2295
2.80M
    session->notify = notify;
2296
2.80M
    session->appData = pApplication;
2297
2.80M
    session->info.flags = flags;
2298
2.80M
    session->info.slotID = slotID;
2299
2.80M
    session->info.ulDeviceError = 0;
2300
2.80M
    sftk_update_state(slot, session);
2301
    /* no ops completed yet, so the last one couldn't be a FIPS op */
2302
2.80M
    session->lastOpWasFIPS = PR_FALSE;
2303
2.80M
    return CKR_OK;
2304
2.80M
}
2305
2306
/*
2307
 * Create a new session and init it.
2308
 */
2309
SFTKSession *
2310
sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication,
2311
                CK_FLAGS flags)
2312
2.80M
{
2313
2.80M
    SFTKSession *session;
2314
2.80M
    SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE);
2315
2.80M
    CK_RV crv;
2316
2317
2.80M
    if (slot == NULL)
2318
0
        return NULL;
2319
2320
2.80M
    session = (SFTKSession *)PORT_Alloc(sizeof(SFTKSession));
2321
2.80M
    if (session == NULL)
2322
0
        return NULL;
2323
2324
2.80M
    crv = sftk_InitSession(session, slot, slotID, notify, pApplication, flags);
2325
2.80M
    if (crv != CKR_OK) {
2326
0
        PORT_Free(session);
2327
0
        return NULL;
2328
0
    }
2329
2.80M
    return session;
2330
2.80M
}
2331
2332
/* free all the data associated with a session. */
2333
void
2334
sftk_ClearSession(SFTKSession *session)
2335
2.80M
{
2336
2.80M
    SFTKSlot *slot = sftk_SlotFromSession(session);
2337
2.80M
    SFTKObjectList *op, *next;
2338
2.80M
    SFTKObjectList *toFree = NULL;
2339
2340
    /* Detach every object this session still owns.
2341
     *
2342
     * No one references the session any more, but that does not make it safe
2343
     * to walk this chain unlocked: object handles are slot-global, so a
2344
     * C_DestroyObject on any other session may be removing one of these
2345
     * objects right now. slot->objectLock arbitrates both queues and belongs
2346
     * to the slot, which outlives every session on it.
2347
     */
2348
2.80M
    PR_Lock(slot->objectLock);
2349
2.80M
    for (op = session->objects[0]; op != NULL; op = next) {
2350
0
        next = op->next;
2351
0
        PORT_ReleaseAssert(!next || next->prev == op);
2352
        /* Unlink by hand: we are discarding the whole list, so there is no
2353
         * point patching neighbours. */
2354
0
        op->next = op->prev = NULL;
2355
        /* Everything on this list is still in the slot hash -- a claimant
2356
         * unlinks it from both under this lock -- so the claim normally
2357
         * succeeds. The test guards against a path that ever removes an
2358
         * object from only one queue. */
2359
0
        if (sftk_ClaimObjectRemovalLocked(slot, op->parent)) {
2360
            /* We own the queues' reference, so the object stays alive until
2361
             * we drop it; chain the unlinked element up and free below. */
2362
0
            op->next = toFree;
2363
0
            toFree = op;
2364
0
        }
2365
0
    }
2366
2.80M
    session->objects[0] = NULL;
2367
2.80M
    PR_Unlock(slot->objectLock);
2368
2369
    /* An object that outlives us -- because another thread still holds a
2370
     * reference -- keeps a stale so->session pointing here. That is safe:
2371
     * so->session is only dereferenced under slot->objectLock by a thread
2372
     * that has just won the removal claim, and the claim can no longer
2373
     * succeed for an object we have already pulled out of the slot hash. */
2374
2.80M
    for (op = toFree; op != NULL; op = next) {
2375
0
        next = op->next;
2376
0
        op->next = NULL;
2377
0
        sftk_FreeObject(op->parent); /* drop the queues' reference */
2378
0
    }
2379
2380
2.80M
    if (session->enc_context) {
2381
813k
        sftk_FreeContext(session->enc_context);
2382
813k
        session->enc_context = NULL;
2383
813k
    }
2384
2.80M
    if (session->hash_context) {
2385
800k
        sftk_FreeContext(session->hash_context);
2386
800k
        session->hash_context = NULL;
2387
800k
    }
2388
2.80M
    if (session->search) {
2389
0
        sftk_FreeSearch(session->search);
2390
0
        session->search = NULL;
2391
0
    }
2392
2.80M
}
2393
2394
/* free the data associated with the session, and the session.
2395
 * Caller must have driven refCount to 0; reachable only via sftk_FreeSession. */
2396
static void
2397
sftk_DestroySession(SFTKSession *session)
2398
2.80M
{
2399
2.80M
    PORT_ReleaseAssert(session->refCount == 0);
2400
2.80M
    sftk_ClearSession(session);
2401
2.80M
    PORT_Free(session);
2402
2.80M
}
2403
2404
/*
2405
 * look up a session structure from a session handle
2406
 * generate a reference to it.
2407
 */
2408
SFTKSession *
2409
sftk_SessionFromHandle(CK_SESSION_HANDLE handle)
2410
33.5M
{
2411
33.5M
    SFTKSlot *slot = sftk_SlotFromSessionHandle(handle);
2412
33.5M
    SFTKSession *session;
2413
33.5M
    PRLock *lock;
2414
2415
33.5M
    if (!slot)
2416
0
        return NULL;
2417
33.5M
    lock = SFTK_SESSION_LOCK(slot, handle);
2418
2419
33.5M
    PR_Lock(lock);
2420
33.5M
    sftkqueue_find(session, handle, slot->head, slot->sessHashSize);
2421
33.5M
    if (session)
2422
33.5M
        session->refCount++;
2423
33.5M
    PR_Unlock(lock);
2424
2425
33.5M
    return (session);
2426
33.5M
}
2427
2428
/*
2429
 * release a reference to a session. The slot's session bucket holds the
2430
 * initial reference (created by sftk_InitSession); sftk_SessionFromHandle
2431
 * adds another for the duration of the caller's use. NSC_CloseSession and
2432
 * sftk_CloseAllSessions drop the bucket's reference once the session has
2433
 * been removed from the queue. The thread that drives refCount to 0
2434
 * destroys the session.
2435
 */
2436
void
2437
sftk_FreeSession(SFTKSession *session)
2438
33.5M
{
2439
33.5M
    PRBool destroy = PR_FALSE;
2440
33.5M
    SFTKSlot *slot = sftk_SlotFromSession(session);
2441
33.5M
    PRLock *lock = SFTK_SESSION_LOCK(slot, session->handle);
2442
2443
33.5M
    PR_Lock(lock);
2444
33.5M
    PORT_ReleaseAssert(session->refCount > 0);
2445
33.5M
    if (session->refCount == 1)
2446
2.80M
        destroy = PR_TRUE;
2447
33.5M
    session->refCount--;
2448
33.5M
    PR_Unlock(lock);
2449
2450
33.5M
    if (destroy)
2451
2.80M
        sftk_DestroySession(session);
2452
33.5M
}
2453
2454
void
2455
sftk_addHandle(SFTKSearchResults *search, CK_OBJECT_HANDLE handle)
2456
0
{
2457
0
    if (search->handles == NULL) {
2458
0
        return;
2459
0
    }
2460
0
    if (search->size >= search->array_size) {
2461
0
        search->array_size += NSC_SEARCH_BLOCK_SIZE;
2462
0
        search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles,
2463
0
                                                           sizeof(CK_OBJECT_HANDLE) * search->array_size);
2464
0
        if (search->handles == NULL) {
2465
0
            return;
2466
0
        }
2467
0
    }
2468
0
    search->handles[search->size] = handle;
2469
0
    search->size++;
2470
0
}
2471
2472
static CK_RV
2473
handleToClass(SFTKSlot *slot, CK_OBJECT_HANDLE handle,
2474
              CK_OBJECT_CLASS *objClass)
2475
1.94k
{
2476
1.94k
    SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, handle);
2477
1.94k
    CK_ATTRIBUTE objClassTemplate;
2478
1.94k
    CK_RV crv;
2479
2480
1.94k
    *objClass = CKO_DATA;
2481
1.94k
    objClassTemplate.type = CKA_CLASS;
2482
1.94k
    objClassTemplate.pValue = objClass;
2483
1.94k
    objClassTemplate.ulValueLen = sizeof(*objClass);
2484
1.94k
    crv = sftkdb_GetAttributeValue(dbHandle, handle, &objClassTemplate, 1);
2485
1.94k
    sftk_freeDB(dbHandle);
2486
1.94k
    return crv;
2487
1.94k
}
2488
2489
SFTKObject *
2490
sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, CK_OBJECT_HANDLE handle)
2491
1.94k
{
2492
1.94k
    SFTKObject *object = NULL;
2493
1.94k
    PRBool hasLocks = PR_FALSE;
2494
1.94k
    CK_RV crv;
2495
2496
1.94k
    object = sftk_GetObjectFromList(&hasLocks, PR_FALSE, &tokenObjectList, 0,
2497
1.94k
                                    PR_FALSE);
2498
1.94k
    if (object == NULL) {
2499
0
        return NULL;
2500
0
    }
2501
2502
1.94k
    object->handle = handle;
2503
    /* every object must have a class, if we can't get it, the object
2504
     * doesn't exist */
2505
1.94k
    crv = handleToClass(slot, handle, &object->objclass);
2506
1.94k
    if (crv != CKR_OK) {
2507
0
        goto loser;
2508
0
    }
2509
1.94k
    object->slot = slot;
2510
    /* set up the validation flags */
2511
1.94k
    object->validation_value = 0;
2512
1.94k
    object->validation_attribute.next = NULL;
2513
1.94k
    object->validation_attribute.prev = NULL;
2514
1.94k
    object->validation_attribute.freeAttr = PR_FALSE;
2515
1.94k
    object->validation_attribute.freeData = PR_FALSE;
2516
1.94k
    object->validation_attribute.handle = CKA_OBJECT_VALIDATION_FLAGS;
2517
1.94k
    object->validation_attribute.attrib.type = CKA_OBJECT_VALIDATION_FLAGS;
2518
1.94k
    object->validation_attribute.attrib.pValue = &object->validation_value;
2519
1.94k
    object->validation_attribute.attrib.ulValueLen = sizeof(object->validation_value);
2520
    /* initialize the FIPS flag properly */
2521
1.94k
    sftk_setFIPS(object, sftk_isFIPS(slot->slotID));
2522
1.94k
    object->source = SFTK_SOURCE_DEFAULT;
2523
1.94k
    object->objectInfo = NULL;
2524
1.94k
    object->infoFree = NULL;
2525
1.94k
    if (!hasLocks) {
2526
0
        object->refLock = PR_NewLock();
2527
0
    }
2528
1.94k
    if (object->refLock == NULL) {
2529
0
        goto loser;
2530
0
    }
2531
1.94k
    object->refCount = 1;
2532
1.94k
    object->type = SFTK_TOKEN_OBJECT_TYPE;
2533
2534
1.94k
    return object;
2535
0
loser:
2536
0
    (void)sftk_DestroyObject(object);
2537
0
    return NULL;
2538
1.94k
}
2539
2540
CK_RV
2541
sftk_convertSessionToToken(SFTKObject *obj)
2542
6
{
2543
6
    SECItem *dbKey;
2544
6
    SFTKSessionObject *so = (SFTKSessionObject *)obj;
2545
6
    SFTKTokenObject *to = sftk_narrowToTokenObject(obj);
2546
6
    CK_RV crv;
2547
2548
6
    sftk_DestroySessionObjectData(so);
2549
6
    PR_DestroyLock(so->attributeLock);
2550
2551
6
    sftk_tokenKeyLock(so->obj.slot);
2552
6
    dbKey = sftk_lookupTokenKeyByHandle(so->obj.slot, so->obj.handle);
2553
6
    if (dbKey && SECFailure == SECITEM_CopyItem(NULL, &to->dbKey, dbKey)) {
2554
0
        crv = CKR_HOST_MEMORY;
2555
6
    } else {
2556
6
        crv = CKR_OK;
2557
6
    }
2558
6
    sftk_tokenKeyUnlock(so->obj.slot);
2559
6
    return crv;
2560
6
}
2561
2562
SFTKSessionObject *
2563
sftk_narrowToSessionObject(SFTKObject *obj)
2564
248M
{
2565
248M
    PRBool handleSaysSession = !sftk_isToken(obj->handle);
2566
248M
    PRBool typeSaysSession = obj->type == SFTK_SESSION_OBJECT_TYPE;
2567
248M
    if (handleSaysSession != typeSaysSession) {
2568
0
        PORT_Assert(0);
2569
0
        return NULL;
2570
0
    }
2571
248M
    return handleSaysSession ? (SFTKSessionObject *)obj : NULL;
2572
248M
}
2573
2574
SFTKTokenObject *
2575
sftk_narrowToTokenObject(SFTKObject *obj)
2576
3.09M
{
2577
3.09M
    PRBool handleSaysToken = sftk_isToken(obj->handle);
2578
3.09M
    PRBool typeSaysToken = obj->type == SFTK_TOKEN_OBJECT_TYPE;
2579
3.09M
    if (handleSaysToken != typeSaysToken) {
2580
0
        PORT_Assert(0);
2581
0
        return NULL;
2582
0
    }
2583
3.09M
    return handleSaysToken ? (SFTKTokenObject *)obj : NULL;
2584
3.09M
}
2585
2586
/* Constant time helper functions */
2587
2588
/* sftk_CKRVToMask returns, in constant time, a mask value of
2589
 * all ones if rv == CKR_OK.  Otherwise it returns zero. */
2590
unsigned int
2591
sftk_CKRVToMask(CK_RV rv)
2592
42.5k
{
2593
42.5k
    PR_STATIC_ASSERT(CKR_OK == 0);
2594
42.5k
    return ~PORT_CT_NOT_ZERO(rv);
2595
42.5k
}
2596
2597
/* sftk_CheckCBCPadding checks, in constant time, the padding validity and
2598
 * accordingly sets the pad length. */
2599
CK_RV
2600
sftk_CheckCBCPadding(CK_BYTE_PTR pBuf, unsigned int bufLen,
2601
                     unsigned int blockSize, unsigned int *outPadSize)
2602
10.6k
{
2603
10.6k
    PORT_Assert(outPadSize);
2604
2605
    /* CBC-padded plaintext is always at least one full block */
2606
10.6k
    if (bufLen < blockSize || blockSize == 0) {
2607
0
        *outPadSize = 0;
2608
0
        return CKR_ENCRYPTED_DATA_INVALID;
2609
0
    }
2610
2611
10.6k
    unsigned int padSize = (unsigned int)pBuf[bufLen - 1];
2612
2613
    /* If padSize <= blockSize, set goodPad to all-1s and all-0s otherwise.*/
2614
10.6k
    unsigned int goodPad = PORT_CT_DUPLICATE_MSB_TO_ALL(~(blockSize - padSize));
2615
    /* padSize should not be 0 */
2616
10.6k
    goodPad &= PORT_CT_NOT_ZERO(padSize);
2617
2618
10.6k
    unsigned int i;
2619
181k
    for (i = 0; i < blockSize; i++) {
2620
        /* If i < padSize, set loopMask to all-1s and all-0s otherwise.*/
2621
170k
        unsigned int loopMask = PORT_CT_DUPLICATE_MSB_TO_ALL(~(padSize - 1 - i));
2622
        /* Get the padding value (should be padSize) from buffer */
2623
170k
        unsigned int padVal = pBuf[bufLen - 1 - i];
2624
        /* Update goodPad only if i < padSize */
2625
170k
        goodPad &= PORT_CT_SEL(loopMask, ~(padVal ^ padSize), goodPad);
2626
170k
    }
2627
2628
    /* If any of the final padding bytes had the wrong value, one or more
2629
     * of the lower eight bits of |goodPad| will be cleared. We AND the
2630
     * bottom 8 bits together and duplicate the result to all the bits. */
2631
10.6k
    goodPad &= goodPad >> 4;
2632
10.6k
    goodPad &= goodPad >> 2;
2633
10.6k
    goodPad &= goodPad >> 1;
2634
10.6k
    goodPad <<= sizeof(goodPad) * 8 - 1;
2635
10.6k
    goodPad = PORT_CT_DUPLICATE_MSB_TO_ALL(goodPad);
2636
2637
    /* Set outPadSize to padSize or 0 */
2638
10.6k
    *outPadSize = PORT_CT_SEL(goodPad, padSize, 0);
2639
    /* Return OK if the pad is valid */
2640
10.6k
    return PORT_CT_SEL(goodPad, CKR_OK, CKR_ENCRYPTED_DATA_INVALID);
2641
10.6k
}
2642
2643
void
2644
sftk_EncodeInteger(PRUint64 integer, CK_ULONG num_bits, CK_BBOOL littleEndian,
2645
                   CK_BYTE_PTR output, CK_ULONG_PTR output_len)
2646
0
{
2647
0
    if (output_len) {
2648
0
        *output_len = (num_bits / 8);
2649
0
    }
2650
2651
0
    PR_ASSERT(num_bits > 0 && num_bits <= 64 && (num_bits % 8) == 0);
2652
2653
0
    if (littleEndian == CK_TRUE) {
2654
0
        for (size_t offset = 0; offset < num_bits / 8; offset++) {
2655
0
            output[offset] = (unsigned char)((integer >> (offset * 8)) & 0xFF);
2656
0
        }
2657
0
    } else {
2658
0
        for (size_t offset = 0; offset < num_bits / 8; offset++) {
2659
0
            PRUint64 shift = num_bits - (offset + 1) * 8;
2660
0
            output[offset] = (unsigned char)((integer >> shift) & 0xFF);
2661
0
        }
2662
0
    }
2663
0
}
2664
2665
CK_FLAGS
2666
sftk_AttributeToFlags(CK_ATTRIBUTE_TYPE op)
2667
992k
{
2668
992k
    CK_FLAGS flags = 0;
2669
2670
992k
    switch (op) {
2671
121k
        case CKA_ENCRYPT:
2672
121k
            flags = CKF_ENCRYPT;
2673
121k
            break;
2674
131k
        case CKA_DECRYPT:
2675
131k
            flags = CKF_DECRYPT;
2676
131k
            break;
2677
64.2k
        case CKA_WRAP:
2678
64.2k
            flags = CKF_WRAP;
2679
64.2k
            break;
2680
38.8k
        case CKA_UNWRAP:
2681
38.8k
            flags = CKF_UNWRAP;
2682
38.8k
            break;
2683
0
        case CKA_SIGN:
2684
0
            flags = CKF_SIGN;
2685
0
            break;
2686
0
        case CKA_SIGN_RECOVER:
2687
0
            flags = CKF_SIGN_RECOVER;
2688
0
            break;
2689
0
        case CKA_VERIFY:
2690
0
            flags = CKF_VERIFY;
2691
0
            break;
2692
0
        case CKA_VERIFY_RECOVER:
2693
0
            flags = CKF_VERIFY_RECOVER;
2694
0
            break;
2695
0
        case CKA_DERIVE:
2696
0
            flags = CKF_DERIVE;
2697
0
            break;
2698
        /* fake attribute to select digesting */
2699
0
        case CKA_DIGEST:
2700
0
            flags = CKF_DIGEST;
2701
0
            break;
2702
        /* fake attribute to select key gen */
2703
0
        case CKA_NSS_GENERATE:
2704
0
            flags = CKF_GENERATE;
2705
0
            break;
2706
        /* fake attribute to select key pair gen */
2707
0
        case CKA_NSS_GENERATE_KEY_PAIR:
2708
0
            flags = CKF_GENERATE_KEY_PAIR;
2709
0
            break;
2710
        /* fake attributes to to handle MESSAGE* flags */
2711
265k
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
2712
265k
            flags = CKF_MESSAGE_ENCRYPT;
2713
265k
            break;
2714
370k
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
2715
370k
            flags = CKF_MESSAGE_DECRYPT;
2716
370k
            break;
2717
0
        case CKA_NSS_MESSAGE | CKA_SIGN:
2718
0
            flags = CKF_MESSAGE_SIGN;
2719
0
            break;
2720
0
        case CKA_NSS_MESSAGE | CKA_VERIFY:
2721
0
            flags = CKF_MESSAGE_VERIFY;
2722
0
            break;
2723
0
        default:
2724
0
            break;
2725
992k
    }
2726
992k
    return flags;
2727
992k
}
2728
2729
/*
2730
 * ******************** Hash Utilities **************************
2731
 */
2732
/*
2733
 * Utility function for converting PSS/OAEP parameter types into
2734
 * HASH_HashTypes. Note: Only SHA family functions are defined in RFC 3447.
2735
 */
2736
HASH_HashType
2737
sftk_GetHashTypeFromMechanism(CK_MECHANISM_TYPE mech)
2738
2.24M
{
2739
2.24M
    switch (mech) {
2740
1.01k
        case CKM_SHA_1:
2741
1.99k
        case CKG_MGF1_SHA1:
2742
1.99k
            return HASH_AlgSHA1;
2743
478
        case CKM_SHA224:
2744
528
        case CKG_MGF1_SHA224:
2745
528
            return HASH_AlgSHA224;
2746
1.80M
        case CKM_SHA256:
2747
1.81M
        case CKG_MGF1_SHA256:
2748
1.81M
            return HASH_AlgSHA256;
2749
422k
        case CKM_SHA384:
2750
424k
        case CKG_MGF1_SHA384:
2751
424k
            return HASH_AlgSHA384;
2752
3.05k
        case CKM_SHA512:
2753
5.88k
        case CKG_MGF1_SHA512:
2754
5.88k
            return HASH_AlgSHA512;
2755
40
        default:
2756
40
            return HASH_AlgNULL;
2757
2.24M
    }
2758
2.24M
}
2759
2760
#ifdef NSS_HAS_FIPS_INDICATORS
2761
/**************** FIPS Indicator Utilities *************************/
2762
/* sigh, we probably need a version of this in secutil so that both
2763
 * softoken and NSS can use it */
2764
static SECOidTag
2765
sftk_quickGetECCCurveOid(SFTKObject *source)
2766
{
2767
    SFTKAttribute *attribute = sftk_FindAttribute(source, CKA_EC_PARAMS);
2768
    unsigned char *encoded;
2769
    int len;
2770
    SECItem oid;
2771
    SECOidTag tag;
2772
2773
    if (attribute == NULL) {
2774
        return SEC_OID_UNKNOWN;
2775
    }
2776
    encoded = attribute->attrib.pValue;
2777
    len = attribute->attrib.ulValueLen;
2778
    if ((len < 2) || (encoded[0] != SEC_ASN1_OBJECT_ID) ||
2779
        (len != encoded[1] + 2)) {
2780
        sftk_FreeAttribute(attribute);
2781
        return SEC_OID_UNKNOWN;
2782
    }
2783
    oid.data = encoded + 2;
2784
    oid.len = len - 2;
2785
    tag = SECOID_FindOIDTag(&oid);
2786
    sftk_FreeAttribute(attribute);
2787
    return tag;
2788
}
2789
2790
/* This function currently only returns valid lengths for
2791
 * FIPS approved ECC curves. If we want to make this generic
2792
 * in the future, that Curve determination can be done in
2793
 * the sftk_handleSpecial. Since it's currently only used
2794
 * in FIPS indicators, it's currently only compiled with
2795
 * the FIPS indicator code */
2796
static CK_ULONG
2797
sftk_getKeyLength(SFTKObject *source)
2798
{
2799
    CK_KEY_TYPE keyType = CKK_INVALID_KEY_TYPE;
2800
    CK_ATTRIBUTE_TYPE keyAttribute;
2801
    CK_ULONG keyLength = 0;
2802
    SFTKAttribute *attribute;
2803
    CK_RV crv;
2804
2805
    /* If we don't have a key, then it doesn't have a length.
2806
     * this may be OK (say we are hashing). The mech info will
2807
     * sort this out because algorithms which expect no keys
2808
     * will accept zero length for the keys */
2809
    if (source == NULL) {
2810
        return 0;
2811
    }
2812
2813
    crv = sftk_GetULongAttribute(source, CKA_KEY_TYPE, &keyType);
2814
    if (crv != CKR_OK) {
2815
        /* sometimes we're passed a data object, in that case the
2816
         * key length is CKA_VALUE, which is the default */
2817
        keyType = CKK_INVALID_KEY_TYPE;
2818
    }
2819
    if ((keyType == CKK_EC) || (keyType == CKK_EC_EDWARDS) ||
2820
        (keyType == CKK_EC_MONTGOMERY)) {
2821
        SECOidTag curve = sftk_quickGetECCCurveOid(source);
2822
        switch (curve) {
2823
            case SEC_OID_CURVE25519:
2824
                /* change when we start algorithm testing on curve25519 */
2825
                return 0;
2826
            case SEC_OID_SECG_EC_SECP256R1:
2827
                return 256;
2828
            case SEC_OID_SECG_EC_SECP384R1:
2829
                return 384;
2830
            case SEC_OID_SECG_EC_SECP521R1:
2831
                /* this is a lie, but it makes the table easier. We don't
2832
                 * have to have a double entry for every ECC mechanism */
2833
                return 512;
2834
            default:
2835
                break;
2836
        }
2837
        /* other curves aren't NIST approved, returning 0 will cause these
2838
         * curves to fail FIPS length criteria */
2839
        return 0;
2840
    }
2841
2842
    switch (keyType) {
2843
        case CKK_RSA:
2844
            keyAttribute = CKA_MODULUS;
2845
            break;
2846
        case CKK_DSA:
2847
        case CKK_DH:
2848
            keyAttribute = CKA_PRIME;
2849
            break;
2850
        default:
2851
            keyAttribute = CKA_VALUE;
2852
            break;
2853
    }
2854
    attribute = sftk_FindAttribute(source, keyAttribute);
2855
    if (attribute) {
2856
        keyLength = attribute->attrib.ulValueLen * 8;
2857
        sftk_FreeAttribute(attribute);
2858
    }
2859
    return keyLength;
2860
}
2861
2862
static PRBool
2863
sftk_checkKeyLength(CK_ULONG keyLength, CK_ULONG min,
2864
                    CK_ULONG max, CK_ULONG step)
2865
{
2866
    if (keyLength > max) {
2867
        return PR_FALSE;
2868
    }
2869
    if (keyLength < min) {
2870
        return PR_FALSE;
2871
    }
2872
    if (step == 0) {
2873
        return PR_TRUE;
2874
    }
2875
    if (((keyLength - min) % step) != 0) {
2876
        return PR_FALSE;
2877
    }
2878
    return PR_TRUE;
2879
}
2880
2881
PRBool
2882
sftk_checkFIPSHash(CK_MECHANISM_TYPE hash, PRBool allowSmall, PRBool allowCMAC)
2883
{
2884
    switch (hash) {
2885
        case CKM_AES_CMAC:
2886
            return allowCMAC;
2887
        case CKM_SHA_1:
2888
        case CKM_SHA_1_HMAC:
2889
        case CKM_SHA224:
2890
        case CKM_SHA224_HMAC:
2891
            return allowSmall;
2892
        case CKM_SHA256:
2893
        case CKM_SHA256_HMAC:
2894
        case CKM_SHA384:
2895
        case CKM_SHA384_HMAC:
2896
        case CKM_SHA512:
2897
        case CKM_SHA512_HMAC:
2898
            return PR_TRUE;
2899
    }
2900
    return PR_FALSE;
2901
}
2902
2903
/*
2904
 * handle specialized FIPS semantics that are too complicated to
2905
 * handle with just a table. NOTE: this means any additional semantics
2906
 * would have to be coded here before they can be added to the table */
2907
static PRBool
2908
sftk_handleSpecial(SFTKSlot *slot, CK_MECHANISM *mech,
2909
                   SFTKFIPSAlgorithmList *mechInfo, SFTKObject *source,
2910
                   CK_ULONG keyLength, CK_ULONG targetKeyLength)
2911
{
2912
    PRBool allowSmall = PR_FALSE;
2913
    PRBool allowCMAC = PR_FALSE;
2914
    switch (mechInfo->special) {
2915
        case SFTKFIPSDH: {
2916
            SECItem dhPrime;
2917
            SECItem dhBase;
2918
            SECItem dhGenerator;
2919
            PRBool fipsOk = PR_FALSE;
2920
            const SECItem *dhSubPrime;
2921
            CK_RV crv = sftk_Attribute2SecItem(NULL, &dhPrime,
2922
                                               source, CKA_PRIME);
2923
            if (crv != CKR_OK) {
2924
                return PR_FALSE;
2925
            }
2926
            crv = sftk_Attribute2SecItem(NULL, &dhBase, source, CKA_BASE);
2927
            if (crv != CKR_OK) {
2928
                return PR_FALSE;
2929
            }
2930
            dhSubPrime = sftk_VerifyDH_Prime(&dhPrime, &dhGenerator, PR_TRUE);
2931
            fipsOk = (dhSubPrime) ? PR_TRUE : PR_FALSE;
2932
            if (fipsOk && (SECITEM_CompareItem(&dhBase, &dhGenerator) != 0)) {
2933
                fipsOk = PR_FALSE;
2934
            }
2935
2936
            SECITEM_ZfreeItem(&dhPrime, PR_FALSE);
2937
            SECITEM_ZfreeItem(&dhBase, PR_FALSE);
2938
            return fipsOk;
2939
        }
2940
        case SFTKFIPSNone:
2941
            return PR_FALSE;
2942
        case SFTKFIPSECC:
2943
            /* we've already handled the curve selection in the 'getlength'
2944
             * function */
2945
            return PR_TRUE;
2946
        case SFTKFIPSAEAD: {
2947
            if (mech->ulParameterLen == 0) {
2948
                /* AEAD ciphers are only in FIPS mode if we are using the
2949
                 * MESSAGE interface. This takes an empty parameter
2950
                 * in the init function */
2951
                return PR_TRUE;
2952
            }
2953
            return PR_FALSE;
2954
        }
2955
        case SFTKFIPSRSAPSS: {
2956
            /* PSS salt must not be longer than the  underlying hash.
2957
             * We verify that the underlying hash of the
2958
             * parameters matches Hash of the combined hash mechanisms, so
2959
             * we don't need to look at the specific PSS mechanism */
2960
            CK_RSA_PKCS_PSS_PARAMS *pss = (CK_RSA_PKCS_PSS_PARAMS *)
2961
                                              mech->pParameter;
2962
            const SECHashObject *hashObj = NULL;
2963
            if (mech->ulParameterLen != sizeof(*pss)) {
2964
                return PR_FALSE;
2965
            }
2966
            /* we use the existing hash utilities to find the length of
2967
             * the hash */
2968
            hashObj = HASH_GetRawHashObject(sftk_GetHashTypeFromMechanism(
2969
                pss->hashAlg));
2970
            if (hashObj == NULL) {
2971
                return PR_FALSE;
2972
            }
2973
            /* cap the salt for legacy keys */
2974
            if ((keyLength <= 1024) && (pss->sLen > 63)) {
2975
                return PR_FALSE;
2976
            }
2977
            /* cap the salt based on the hash */
2978
            if (pss->sLen > hashObj->length) {
2979
                return PR_FALSE;
2980
            }
2981
            return PR_TRUE;
2982
        }
2983
        case SFTKFIPSPBKDF2: {
2984
            /* from NIST SP 800-132
2985
             * PBKDF2 must have the following addition restrictions
2986
             * (independent of keysize).
2987
             *    1. iteration count must be at least 1000.
2988
             *    2. salt must be at least 128 bits (16 bytes).
2989
             *    3. password must match the length specified in the SP
2990
             */
2991
            CK_PKCS5_PBKD2_PARAMS2 *pbkdf2 = (CK_PKCS5_PBKD2_PARAMS2 *)
2992
                                                 mech->pParameter;
2993
            if (mech->ulParameterLen != sizeof(*pbkdf2)) {
2994
                return PR_FALSE;
2995
            }
2996
            if (pbkdf2 == NULL) {
2997
                return PR_FALSE;
2998
            }
2999
            if (pbkdf2->iterations < 1000) {
3000
                return PR_FALSE;
3001
            }
3002
            if (pbkdf2->ulSaltSourceDataLen < 16) {
3003
                return PR_FALSE;
3004
            }
3005
            if (pbkdf2->ulPasswordLen < SFTKFIPS_PBKDF2_MIN_PW_LEN) {
3006
                return PR_FALSE;
3007
            }
3008
            return PR_TRUE;
3009
        }
3010
        /* check the hash mechanisms to make sure they themselves are FIPS */
3011
        case SFTKFIPSChkHashSp800:
3012
            allowCMAC = PR_TRUE;
3013
            /* fallthrough... will pick up allowSmall as well */
3014
        case SFTKFIPSChkHash:
3015
            allowSmall = PR_TRUE;
3016
            /* fallthrough */
3017
        case SFTKFIPSChkHashTls:
3018
            if (mech->ulParameterLen < mechInfo->offset + sizeof(CK_ULONG)) {
3019
                return PR_FALSE;
3020
            }
3021
            return sftk_checkFIPSHash(*(CK_MECHANISM_TYPE *)(((char *)mech->pParameter) + mechInfo->offset),
3022
                                      allowSmall, allowCMAC);
3023
        case SFTKFIPSTlsKeyCheck:
3024
            if (mech->mechanism != CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256) {
3025
                /* unless the mechnism has a built-in hash, check the hash */
3026
                if (mech->ulParameterLen < mechInfo->offset + sizeof(CK_ULONG)) {
3027
                    return PR_FALSE;
3028
                }
3029
                if (!sftk_checkFIPSHash(*(CK_MECHANISM_TYPE *)(((char *)mech->pParameter) + mechInfo->offset),
3030
                                        PR_FALSE, PR_FALSE)) {
3031
                    return PR_FALSE;
3032
                }
3033
            }
3034
            return sftk_checkKeyLength(targetKeyLength, 112, 512, 1);
3035
        case SFTKFIPSRSAOAEP: {
3036
            CK_RSA_PKCS_OAEP_PARAMS *rsaoaep = (CK_RSA_PKCS_OAEP_PARAMS *)
3037
                                                   mech->pParameter;
3038
3039
            HASH_HashType hash_msg = sftk_GetHashTypeFromMechanism(rsaoaep->hashAlg);
3040
            HASH_HashType hash_pad = sftk_GetHashTypeFromMechanism(rsaoaep->mgf);
3041
            /* message hash and mask generation function must be the same */
3042
            if (hash_pad != hash_msg)
3043
                return PR_FALSE;
3044
3045
            return sftk_checkFIPSHash(rsaoaep->hashAlg, PR_FALSE, PR_FALSE);
3046
        }
3047
        default:
3048
            break;
3049
    }
3050
    /* if we didn't understand the special processing, mark it non-fips */
3051
    return PR_FALSE;
3052
}
3053
#endif
3054
3055
PRBool
3056
sftk_operationIsFIPS(SFTKSlot *slot, CK_MECHANISM *mech, CK_ATTRIBUTE_TYPE op,
3057
                     SFTKObject *source, CK_ULONG targetKeyLength)
3058
5.48M
{
3059
5.48M
#ifndef NSS_HAS_FIPS_INDICATORS
3060
5.48M
    return PR_FALSE;
3061
#else
3062
    int i;
3063
    CK_FLAGS opFlags;
3064
    CK_ULONG keyLength;
3065
3066
    /* handle all the quick stuff first */
3067
    if (!sftk_isFIPS(slot->slotID)) {
3068
        return PR_FALSE;
3069
    }
3070
    if (source && !sftk_hasFIPS(source)) {
3071
        return PR_FALSE;
3072
    }
3073
    if (mech == NULL) {
3074
        return PR_FALSE;
3075
    }
3076
3077
    /* now get the calculated values */
3078
    opFlags = sftk_AttributeToFlags(op);
3079
    if (opFlags == 0) {
3080
        return PR_FALSE;
3081
    }
3082
    keyLength = sftk_getKeyLength(source);
3083
3084
    /* check against our algorithm array */
3085
    for (i = 0; i < SFTK_NUMBER_FIPS_ALGORITHMS; i++) {
3086
        SFTKFIPSAlgorithmList *mechs = &sftk_fips_mechs[i];
3087
        /* if we match the number of records exactly, then we are an
3088
         * approved algorithm in the approved mode with an approved key */
3089
        if ((mech->mechanism == mechs->type) &&
3090
            (opFlags == (mechs->info.flags & opFlags)) &&
3091
            sftk_checkKeyLength(keyLength, mechs->info.ulMinKeySize,
3092
                                mechs->info.ulMaxKeySize, mechs->step) &&
3093
            ((targetKeyLength == 0) || (mechs->special == SFTKFIPSTlsKeyCheck) || sftk_checkKeyLength(targetKeyLength, mechs->info.ulMinKeySize, mechs->info.ulMaxKeySize, mechs->step)) &&
3094
            ((mechs->special == SFTKFIPSNone) ||
3095
             sftk_handleSpecial(slot, mech, mechs, source, keyLength, targetKeyLength))) {
3096
            return PR_TRUE;
3097
        }
3098
    }
3099
    return PR_FALSE;
3100
#endif
3101
5.48M
}
3102
3103
void
3104
sftk_setFIPS(SFTKObject *obj, PRBool isFIPS)
3105
5.64M
{
3106
5.64M
    if (isFIPS) {
3107
0
        obj->validation_value |= SFTK_VALIDATION_FIPS_FLAG;
3108
5.64M
    } else {
3109
5.64M
        obj->validation_value &= ~SFTK_VALIDATION_FIPS_FLAG;
3110
5.64M
    }
3111
5.64M
}
3112
3113
PRBool
3114
sftk_hasFIPS(SFTKObject *obj)
3115
2.37M
{
3116
2.37M
    return (obj->validation_value & SFTK_VALIDATION_FIPS_FLAG) ? PR_TRUE : PR_FALSE;
3117
2.37M
}
3118
3119
/*
3120
 * create the FIPS Validation objects. If the vendor
3121
 * doesn't supply an NSS_FIPS_MODULE_ID, at compile time,
3122
 * then we assumethis is an unvalidated module.
3123
 */
3124
CK_RV
3125
sftk_CreateValidationObjects(SFTKSlot *slot)
3126
0
{
3127
0
    const char *module_id;
3128
0
    int module_id_len;
3129
0
    CK_RV crv = CKR_OK;
3130
    /* we currently use both vendor specific values and PKCS #11 v3.2
3131
     * values for compatibility for a couple more ESR releases. Then we can
3132
     * drop the vendor specific ones */
3133
0
    CK_OBJECT_CLASS cko_nss_validation = CKO_NSS_VALIDATION;
3134
0
    CK_OBJECT_CLASS cko_validation = CKO_VALIDATION;
3135
0
    CK_NSS_VALIDATION_TYPE ckv_fips = CKV_NSS_FIPS_140;
3136
0
    CK_FLAGS fipsFlag = SFTK_VALIDATION_FIPS_FLAG;
3137
0
    CK_VALIDATION_TYPE swValidationType = CKV_TYPE_SOFTWARE;
3138
0
    CK_VALIDATION_AUTHORITY_TYPE nistValidationAuthority =
3139
0
        CKV_AUTHORITY_TYPE_NIST_CMVP;
3140
0
    CK_UTF8CHAR us[] = { 'U', 'S' };
3141
0
    CK_VERSION fips_version = { 3, 0 }; /* FIPS-140-3 */
3142
0
    CK_ULONG fips_level = 1;            /* or 2 if you validated at level 2 */
3143
3144
0
#ifndef NSS_FIPS_MODULE_ID
3145
0
#define NSS_FIPS_MODULE_ID "Generic NSS " SOFTOKEN_VERSION " Unvalidated"
3146
0
#endif
3147
0
    module_id = NSS_FIPS_MODULE_ID;
3148
0
    module_id_len = sizeof(NSS_FIPS_MODULE_ID) - 1;
3149
0
    SFTKObject *object;
3150
3151
0
    object = sftk_NewObject(slot); /* fill in the handle later */
3152
0
    if (object == NULL) {
3153
0
        return CKR_HOST_MEMORY;
3154
0
    }
3155
0
    sftk_setFIPS(object, PR_FALSE);
3156
3157
0
    crv = sftk_AddAttributeType(object, CKA_CLASS, &cko_nss_validation,
3158
0
                                sizeof(cko_nss_validation));
3159
0
    if (crv != CKR_OK) {
3160
0
        goto loser;
3161
0
    }
3162
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_TYPE,
3163
0
                                &ckv_fips, sizeof(ckv_fips));
3164
0
    if (crv != CKR_OK) {
3165
0
        goto loser;
3166
0
    }
3167
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_VERSION,
3168
0
                                &fips_version, sizeof(fips_version));
3169
0
    if (crv != CKR_OK) {
3170
0
        goto loser;
3171
0
    }
3172
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_LEVEL,
3173
0
                                &fips_level, sizeof(fips_level));
3174
0
    if (crv != CKR_OK) {
3175
0
        goto loser;
3176
0
    }
3177
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_MODULE_ID,
3178
0
                                module_id, module_id_len);
3179
0
    if (crv != CKR_OK) {
3180
0
        goto loser;
3181
0
    }
3182
3183
0
    object->handle = sftk_getNextHandle(slot);
3184
0
    object->slot = slot;
3185
0
    sftk_AddObject(&slot->moduleObjects, object);
3186
0
    sftk_FreeObject(object);
3187
3188
0
    object = sftk_NewObject(slot); /* fill in the handle later */
3189
0
    if (object == NULL) {
3190
0
        return CKR_HOST_MEMORY;
3191
0
    }
3192
0
    sftk_setFIPS(object, PR_FALSE);
3193
0
    crv = sftk_AddAttributeType(object, CKA_CLASS, &cko_validation,
3194
0
                                sizeof(cko_validation));
3195
0
    if (crv != CKR_OK) {
3196
0
        goto loser;
3197
0
    }
3198
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_TYPE,
3199
0
                                &swValidationType, sizeof(swValidationType));
3200
0
    if (crv != CKR_OK) {
3201
0
        goto loser;
3202
0
    }
3203
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_VERSION,
3204
0
                                &fips_version, sizeof(fips_version));
3205
0
    if (crv != CKR_OK) {
3206
0
        goto loser;
3207
0
    }
3208
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_LEVEL,
3209
0
                                &fips_level, sizeof(fips_level));
3210
0
    if (crv != CKR_OK) {
3211
0
        goto loser;
3212
0
    }
3213
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_MODULE_ID,
3214
0
                                module_id, module_id_len);
3215
0
    if (crv != CKR_OK) {
3216
0
        goto loser;
3217
0
    }
3218
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_FLAG,
3219
0
                                &fipsFlag, sizeof(fipsFlag));
3220
0
    if (crv != CKR_OK) {
3221
0
        goto loser;
3222
0
    }
3223
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_AUTHORITY_TYPE,
3224
0
                                &nistValidationAuthority,
3225
0
                                sizeof(nistValidationAuthority));
3226
0
    if (crv != CKR_OK) {
3227
0
        goto loser;
3228
0
    }
3229
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_COUNTRY, us, sizeof(us));
3230
0
    if (crv != CKR_OK) {
3231
0
        goto loser;
3232
0
    }
3233
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_CERTIFICATE_IDENTIFIER,
3234
0
                                NULL, 0);
3235
0
    if (crv != CKR_OK) {
3236
0
        goto loser;
3237
0
    }
3238
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_CERTIFICATE_URI,
3239
0
                                NULL, 0);
3240
0
    if (crv != CKR_OK) {
3241
0
        goto loser;
3242
0
    }
3243
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_PROFILE,
3244
0
                                NULL, 0);
3245
0
    if (crv != CKR_OK) {
3246
0
        goto loser;
3247
0
    }
3248
0
    crv = sftk_AddAttributeType(object, CKA_VALIDATION_VENDOR_URI,
3249
0
                                NULL, 0);
3250
0
    if (crv != CKR_OK) {
3251
0
        goto loser;
3252
0
    }
3253
    /* future, fill in validation certificate information from a supplied
3254
     * pointer to a config file */
3255
0
    object->handle = sftk_getNextHandle(slot);
3256
0
    object->slot = slot;
3257
0
    sftk_AddObject(&slot->moduleObjects, object);
3258
0
loser:
3259
0
    sftk_FreeObject(object);
3260
3261
0
    return crv;
3262
0
}