Coverage Report

Created: 2025-07-11 07:04

/src/nss/lib/softoken/pkcs11u.c
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
/*
5
 * 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
/* this file should be supplied by the vendor and include all the
21
 * algorithms which have Algorithm certs and have been reviewed by
22
 * the lab. A blank file is included for the base so that FIPS mode
23
 * will still be compiled and run, but FIPS indicators will always
24
 * return PR_FALSE
25
 */
26
#include "fips_algorithms.h"
27
#define NSS_HAS_FIPS_INDICATORS 1
28
#endif
29
30
/*
31
 * ******************** Error mapping *******************************
32
 */
33
/*
34
 * map all the SEC_ERROR_xxx error codes that may be returned by freebl
35
 * functions to CKR_xxx.  return CKR_DEVICE_ERROR by default for backward
36
 * compatibility.
37
 */
38
CK_RV
39
sftk_MapCryptError(int error)
40
0
{
41
0
    switch (error) {
42
0
        case SEC_ERROR_INVALID_ARGS:
43
0
        case SEC_ERROR_BAD_DATA: /* MP_RANGE gets mapped to this */
44
0
            return CKR_ARGUMENTS_BAD;
45
0
        case SEC_ERROR_INPUT_LEN:
46
0
            return CKR_DATA_LEN_RANGE;
47
0
        case SEC_ERROR_OUTPUT_LEN:
48
0
            return CKR_BUFFER_TOO_SMALL;
49
0
        case SEC_ERROR_LIBRARY_FAILURE:
50
0
            return CKR_GENERAL_ERROR;
51
0
        case SEC_ERROR_NO_MEMORY:
52
0
            return CKR_HOST_MEMORY;
53
0
        case SEC_ERROR_BAD_SIGNATURE:
54
0
            return CKR_SIGNATURE_INVALID;
55
0
        case SEC_ERROR_INVALID_KEY:
56
0
            return CKR_KEY_SIZE_RANGE;
57
0
        case SEC_ERROR_BAD_KEY:        /* an EC public key that fails validation */
58
0
            return CKR_KEY_SIZE_RANGE; /* the closest error code */
59
0
        case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM:
60
0
            return CKR_TEMPLATE_INCONSISTENT;
61
0
        case SEC_ERROR_UNSUPPORTED_KEYALG:
62
0
            return CKR_MECHANISM_INVALID;
63
0
        case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE:
64
0
            return CKR_DOMAIN_PARAMS_INVALID;
65
        /* key pair generation failed after max number of attempts */
66
0
        case SEC_ERROR_NEED_RANDOM:
67
0
            return CKR_FUNCTION_FAILED;
68
0
    }
69
0
    return CKR_DEVICE_ERROR;
70
0
}
71
72
/*
73
 * functions which adjust the mapping based on different contexts
74
 * (Decrypt or Verify).
75
 */
76
77
/* used by Decrypt and UnwrapKey (indirectly) and Decrypt message */
78
CK_RV
79
sftk_MapDecryptError(int error)
80
0
{
81
0
    switch (error) {
82
        /* usually a padding error, or aead tag mismatch */
83
0
        case SEC_ERROR_BAD_DATA:
84
0
            return CKR_ENCRYPTED_DATA_INVALID;
85
0
        default:
86
0
            return sftk_MapCryptError(error);
87
0
    }
88
0
}
89
90
/*
91
 * return CKR_SIGNATURE_INVALID instead of CKR_DEVICE_ERROR by default for
92
 * backward compatibilty.
93
 */
94
CK_RV
95
sftk_MapVerifyError(int error)
96
0
{
97
0
    CK_RV crv = sftk_MapCryptError(error);
98
0
    if (crv == CKR_DEVICE_ERROR)
99
0
        crv = CKR_SIGNATURE_INVALID;
100
0
    return crv;
101
0
}
102
103
/*
104
 * ******************** Attribute Utilities *******************************
105
 */
106
107
/*
108
 * create a new attribute with type, value, and length. Space is allocated
109
 * to hold value.
110
 */
111
static SFTKAttribute *
112
sftk_NewAttribute(SFTKObject *object,
113
                  CK_ATTRIBUTE_TYPE type, const void *value, CK_ULONG len)
114
0
{
115
0
    SFTKAttribute *attribute;
116
117
0
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
118
0
    int index;
119
120
0
    if (so == NULL) {
121
        /* allocate new attribute in a buffer */
122
0
        PORT_Assert(0);
123
0
        return NULL;
124
0
    }
125
    /*
126
     * We attempt to keep down contention on Malloc and Arena locks by
127
     * limiting the number of these calls on high traversed paths. This
128
     * is done for attributes by 'allocating' them from a pool already
129
     * allocated by the parent object.
130
     */
131
0
    PZ_Lock(so->attributeLock);
132
0
    index = so->nextAttr++;
133
0
    PZ_Unlock(so->attributeLock);
134
0
    PORT_Assert(index < MAX_OBJS_ATTRS);
135
0
    if (index >= MAX_OBJS_ATTRS)
136
0
        return NULL;
137
138
0
    attribute = &so->attrList[index];
139
0
    attribute->attrib.type = type;
140
0
    attribute->freeAttr = PR_FALSE;
141
0
    attribute->freeData = PR_FALSE;
142
0
    if (value) {
143
0
        if (len <= ATTR_SPACE) {
144
0
            attribute->attrib.pValue = attribute->space;
145
0
        } else {
146
0
            attribute->attrib.pValue = PORT_Alloc(len);
147
0
            attribute->freeData = PR_TRUE;
148
0
        }
149
0
        if (attribute->attrib.pValue == NULL) {
150
0
            return NULL;
151
0
        }
152
0
        PORT_Memcpy(attribute->attrib.pValue, value, len);
153
0
        attribute->attrib.ulValueLen = len;
154
0
    } else {
155
0
        attribute->attrib.pValue = NULL;
156
0
        attribute->attrib.ulValueLen = 0;
157
0
    }
158
0
    attribute->attrib.type = type;
159
0
    attribute->handle = type;
160
0
    attribute->next = attribute->prev = NULL;
161
0
    return attribute;
162
0
}
163
164
/*
165
 * Free up all the memory associated with an attribute. Reference count
166
 * must be zero to call this.
167
 */
168
static void
169
sftk_DestroyAttribute(SFTKAttribute *attribute)
170
0
{
171
0
    if (attribute->attrib.pValue) {
172
        /* clear out the data in the attribute value... it may have been
173
         * sensitive data */
174
0
        PORT_Memset(attribute->attrib.pValue, 0, attribute->attrib.ulValueLen);
175
0
        if (attribute->freeData) {
176
0
            PORT_Free(attribute->attrib.pValue);
177
0
            attribute->attrib.pValue = NULL;
178
0
            attribute->freeData = PR_FALSE;
179
0
        }
180
0
    }
181
0
    if (attribute->freeAttr) {
182
0
        PORT_Free(attribute);
183
0
    }
184
0
}
185
186
/*
187
 * release a reference to an attribute structure
188
 */
189
void
190
sftk_FreeAttribute(SFTKAttribute *attribute)
191
0
{
192
0
    if (attribute && attribute->freeAttr) {
193
0
        sftk_DestroyAttribute(attribute);
194
0
        return;
195
0
    }
196
0
}
197
198
static SFTKAttribute *
199
sftk_FindTokenAttribute(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type)
200
0
{
201
0
    SFTKAttribute *myattribute = NULL;
202
0
    SFTKDBHandle *dbHandle = NULL;
203
0
    CK_RV crv = CKR_HOST_MEMORY;
204
205
0
    myattribute = (SFTKAttribute *)PORT_Alloc(sizeof(SFTKAttribute));
206
0
    if (myattribute == NULL) {
207
0
        goto loser;
208
0
    }
209
210
0
    dbHandle = sftk_getDBForTokenObject(object->obj.slot, object->obj.handle);
211
212
0
    myattribute->handle = type;
213
0
    myattribute->attrib.type = type;
214
0
    myattribute->attrib.pValue = myattribute->space;
215
0
    myattribute->attrib.ulValueLen = ATTR_SPACE;
216
0
    myattribute->next = myattribute->prev = NULL;
217
0
    myattribute->freeAttr = PR_TRUE;
218
0
    myattribute->freeData = PR_FALSE;
219
220
0
    crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
221
0
                                   &myattribute->attrib, 1);
222
223
    /* attribute is bigger than our attribute space buffer, malloc it */
224
0
    if (crv == CKR_BUFFER_TOO_SMALL) {
225
0
        myattribute->attrib.pValue = NULL;
226
0
        crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
227
0
                                       &myattribute->attrib, 1);
228
0
        if (crv != CKR_OK) {
229
0
            goto loser;
230
0
        }
231
0
        myattribute->attrib.pValue = PORT_Alloc(myattribute->attrib.ulValueLen);
232
0
        if (myattribute->attrib.pValue == NULL) {
233
0
            crv = CKR_HOST_MEMORY;
234
0
            goto loser;
235
0
        }
236
0
        myattribute->freeData = PR_TRUE;
237
0
        crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle,
238
0
                                       &myattribute->attrib, 1);
239
0
    }
240
0
loser:
241
0
    if (dbHandle) {
242
0
        sftk_freeDB(dbHandle);
243
0
    }
244
0
    if (crv != CKR_OK) {
245
0
        if (myattribute) {
246
0
            myattribute->attrib.ulValueLen = 0;
247
0
            sftk_FreeAttribute(myattribute);
248
0
            myattribute = NULL;
249
0
        }
250
0
    }
251
0
    return myattribute;
252
0
}
253
254
/*
255
 * look up and attribute structure from a type and Object structure.
256
 * The returned attribute is referenced and needs to be freed when
257
 * it is no longer needed.
258
 */
259
SFTKAttribute *
260
sftk_FindAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
261
0
{
262
0
    SFTKAttribute *attribute;
263
0
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
264
265
0
    if (sessObject == NULL) {
266
0
        return sftk_FindTokenAttribute(sftk_narrowToTokenObject(object), type);
267
0
    }
268
269
0
    PZ_Lock(sessObject->attributeLock);
270
0
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
271
0
    PZ_Unlock(sessObject->attributeLock);
272
273
0
    return (attribute);
274
0
}
275
276
/*
277
 * Take a buffer and it's length and return it's true size in bits;
278
 */
279
unsigned int
280
sftk_GetLengthInBits(unsigned char *buf, unsigned int bufLen)
281
0
{
282
0
    unsigned int size = bufLen * 8;
283
0
    unsigned int i;
284
285
    /* Get the real length in bytes */
286
0
    for (i = 0; i < bufLen; i++) {
287
0
        unsigned char c = *buf++;
288
0
        if (c != 0) {
289
0
            unsigned char m;
290
0
            for (m = 0x80; m > 0; m = m >> 1) {
291
0
                if ((c & m) != 0) {
292
0
                    break;
293
0
                }
294
0
                size--;
295
0
            }
296
0
            break;
297
0
        }
298
0
        size -= 8;
299
0
    }
300
0
    return size;
301
0
}
302
303
/*
304
 * Constrain a big num attribute. to size and padding
305
 * minLength means length of the object must be greater than equal to minLength
306
 * maxLength means length of the object must be less than equal to maxLength
307
 * minMultiple means that object length mod minMultiple must equal 0.
308
 * all input sizes are in bits.
309
 * if any constraint is '0' that constraint is not checked.
310
 */
311
CK_RV
312
sftk_ConstrainAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
313
                        int minLength, int maxLength, int minMultiple)
314
0
{
315
0
    SFTKAttribute *attribute;
316
0
    int size;
317
0
    unsigned char *ptr;
318
319
0
    attribute = sftk_FindAttribute(object, type);
320
0
    if (!attribute) {
321
0
        return CKR_TEMPLATE_INCOMPLETE;
322
0
    }
323
0
    ptr = (unsigned char *)attribute->attrib.pValue;
324
0
    if (ptr == NULL) {
325
0
        sftk_FreeAttribute(attribute);
326
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
327
0
    }
328
0
    size = sftk_GetLengthInBits(ptr, attribute->attrib.ulValueLen);
329
0
    sftk_FreeAttribute(attribute);
330
331
0
    if ((minLength != 0) && (size < minLength)) {
332
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
333
0
    }
334
0
    if ((maxLength != 0) && (size > maxLength)) {
335
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
336
0
    }
337
0
    if ((minMultiple != 0) && ((size % minMultiple) != 0)) {
338
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
339
0
    }
340
0
    return CKR_OK;
341
0
}
342
343
PRBool
344
sftk_hasAttributeToken(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type)
345
0
{
346
0
    CK_ATTRIBUTE template;
347
0
    CK_RV crv;
348
0
    SFTKDBHandle *dbHandle;
349
350
0
    dbHandle = sftk_getDBForTokenObject(object->obj.slot, object->obj.handle);
351
0
    template.type = type;
352
0
    template.pValue = NULL;
353
0
    template.ulValueLen = 0;
354
355
0
    crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, &template, 1);
356
0
    sftk_freeDB(dbHandle);
357
358
    /* attribute is bigger than our attribute space buffer, malloc it */
359
0
    return (crv == CKR_OK) ? PR_TRUE : PR_FALSE;
360
0
}
361
362
/*
363
 * return true if object has attribute
364
 */
365
PRBool
366
sftk_hasAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
367
0
{
368
0
    SFTKAttribute *attribute;
369
0
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
370
371
0
    if (sessObject == NULL) {
372
0
        return sftk_hasAttributeToken(sftk_narrowToTokenObject(object), type);
373
0
    }
374
375
0
    PZ_Lock(sessObject->attributeLock);
376
0
    sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize);
377
0
    PZ_Unlock(sessObject->attributeLock);
378
379
0
    return (PRBool)(attribute != NULL);
380
0
}
381
382
/*
383
 * add an attribute to an object
384
 */
385
static void
386
sftk_AddAttribute(SFTKObject *object, SFTKAttribute *attribute)
387
0
{
388
0
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
389
390
0
    if (sessObject == NULL)
391
0
        return;
392
0
    PZ_Lock(sessObject->attributeLock);
393
0
    sftkqueue_add(attribute, attribute->handle,
394
0
                  sessObject->head, sessObject->hashSize);
395
0
    PZ_Unlock(sessObject->attributeLock);
396
0
}
397
398
/*
399
 * copy an unsigned attribute into a SECItem. Secitem is allocated in
400
 * the specified arena.
401
 */
402
CK_RV
403
sftk_Attribute2SSecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object,
404
                        CK_ATTRIBUTE_TYPE type)
405
0
{
406
0
    SFTKAttribute *attribute;
407
408
0
    item->data = NULL;
409
410
0
    attribute = sftk_FindAttribute(object, type);
411
0
    if (attribute == NULL)
412
0
        return CKR_TEMPLATE_INCOMPLETE;
413
414
0
    (void)SECITEM_AllocItem(arena, item, attribute->attrib.ulValueLen);
415
0
    if (item->data == NULL) {
416
0
        sftk_FreeAttribute(attribute);
417
0
        return CKR_HOST_MEMORY;
418
0
    }
419
0
    PORT_Memcpy(item->data, attribute->attrib.pValue, item->len);
420
0
    sftk_FreeAttribute(attribute);
421
0
    return CKR_OK;
422
0
}
423
424
/*
425
 * fetch multiple attributes into  SECItems. Secitem data is allocated in
426
 * the specified arena.
427
 */
428
CK_RV
429
sftk_MultipleAttribute2SecItem(PLArenaPool *arena, SFTKObject *object,
430
                               SFTKItemTemplate *itemTemplate, int itemTemplateCount)
431
0
{
432
433
0
    CK_RV crv = CKR_OK;
434
0
    CK_ATTRIBUTE templateSpace[SFTK_MAX_ITEM_TEMPLATE];
435
0
    CK_ATTRIBUTE *template;
436
0
    SFTKTokenObject *tokObject;
437
0
    SFTKDBHandle *dbHandle = NULL;
438
0
    int i;
439
440
0
    tokObject = sftk_narrowToTokenObject(object);
441
442
    /* session objects, just loop through the list */
443
0
    if (tokObject == NULL) {
444
0
        for (i = 0; i < itemTemplateCount; i++) {
445
0
            crv = sftk_Attribute2SecItem(arena, itemTemplate[i].item, object,
446
0
                                         itemTemplate[i].type);
447
0
            if (crv != CKR_OK) {
448
0
                return crv;
449
0
            }
450
0
        }
451
0
        return CKR_OK;
452
0
    }
453
454
    /* don't do any work if none is required */
455
0
    if (itemTemplateCount == 0) {
456
0
        return CKR_OK;
457
0
    }
458
459
    /* don't allocate the template unless we need it */
460
0
    if (itemTemplateCount > SFTK_MAX_ITEM_TEMPLATE) {
461
0
        template = PORT_NewArray(CK_ATTRIBUTE, itemTemplateCount);
462
0
    } else {
463
0
        template = templateSpace;
464
0
    }
465
466
0
    if (template == NULL) {
467
0
        crv = CKR_HOST_MEMORY;
468
0
        goto loser;
469
0
    }
470
471
0
    dbHandle = sftk_getDBForTokenObject(object->slot, object->handle);
472
0
    if (dbHandle == NULL) {
473
0
        crv = CKR_OBJECT_HANDLE_INVALID;
474
0
        goto loser;
475
0
    }
476
477
    /* set up the PKCS #11 template */
478
0
    for (i = 0; i < itemTemplateCount; i++) {
479
0
        template[i].type = itemTemplate[i].type;
480
0
        template[i].pValue = NULL;
481
0
        template[i].ulValueLen = 0;
482
0
    }
483
484
    /* fetch the attribute lengths */
485
0
    crv = sftkdb_GetAttributeValue(dbHandle, object->handle,
486
0
                                   template, itemTemplateCount);
487
0
    if (crv != CKR_OK) {
488
0
        goto loser;
489
0
    }
490
491
    /* allocate space for the attributes */
492
0
    for (i = 0; i < itemTemplateCount; i++) {
493
0
        template[i].pValue = PORT_ArenaAlloc(arena, template[i].ulValueLen);
494
0
        if (template[i].pValue == NULL) {
495
0
            crv = CKR_HOST_MEMORY;
496
0
            goto loser;
497
0
        }
498
0
    }
499
500
    /* fetch the attributes */
501
0
    crv = sftkdb_GetAttributeValue(dbHandle, object->handle,
502
0
                                   template, itemTemplateCount);
503
0
    if (crv != CKR_OK) {
504
0
        goto loser;
505
0
    }
506
507
    /* Fill in the items */
508
0
    for (i = 0; i < itemTemplateCount; i++) {
509
0
        itemTemplate[i].item->data = template[i].pValue;
510
0
        itemTemplate[i].item->len = template[i].ulValueLen;
511
0
    }
512
513
0
loser:
514
0
    if (template != templateSpace) {
515
0
        PORT_Free(template);
516
0
    }
517
0
    if (dbHandle) {
518
0
        sftk_freeDB(dbHandle);
519
0
    }
520
521
0
    return crv;
522
0
}
523
524
/*
525
 * delete an attribute from an object
526
 */
527
static void
528
sftk_DeleteAttribute(SFTKObject *object, SFTKAttribute *attribute)
529
0
{
530
0
    SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object);
531
532
0
    if (sessObject == NULL) {
533
0
        return;
534
0
    }
535
0
    PZ_Lock(sessObject->attributeLock);
536
0
    if (sftkqueue_is_queued(attribute, attribute->handle,
537
0
                            sessObject->head, sessObject->hashSize)) {
538
0
        sftkqueue_delete(attribute, attribute->handle,
539
0
                         sessObject->head, sessObject->hashSize);
540
0
    }
541
0
    PZ_Unlock(sessObject->attributeLock);
542
0
}
543
544
/*
545
 * this is only valid for CK_BBOOL type attributes. Return the state
546
 * of that attribute.
547
 */
548
PRBool
549
sftk_isTrue(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
550
0
{
551
0
    SFTKAttribute *attribute;
552
0
    PRBool tok = PR_FALSE;
553
554
0
    attribute = sftk_FindAttribute(object, type);
555
0
    if (attribute == NULL) {
556
0
        return PR_FALSE;
557
0
    }
558
0
    tok = (PRBool)(*(CK_BBOOL *)attribute->attrib.pValue);
559
0
    sftk_FreeAttribute(attribute);
560
561
0
    return tok;
562
0
}
563
564
/*
565
 * force an attribute to null.
566
 * this is for sensitive keys which are stored in the database, we don't
567
 * want to keep this info around in memory in the clear.
568
 */
569
void
570
sftk_nullAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
571
0
{
572
0
    SFTKAttribute *attribute;
573
574
0
    attribute = sftk_FindAttribute(object, type);
575
0
    if (attribute == NULL)
576
0
        return;
577
578
0
    if (attribute->attrib.pValue != NULL) {
579
0
        PORT_Memset(attribute->attrib.pValue, 0, attribute->attrib.ulValueLen);
580
0
        if (attribute->freeData) {
581
0
            PORT_Free(attribute->attrib.pValue);
582
0
        }
583
0
        attribute->freeData = PR_FALSE;
584
0
        attribute->attrib.pValue = NULL;
585
0
        attribute->attrib.ulValueLen = 0;
586
0
    }
587
0
    sftk_FreeAttribute(attribute);
588
0
}
589
590
static CK_RV
591
sftk_forceTokenAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
592
                         const void *value, unsigned int len)
593
0
{
594
0
    CK_ATTRIBUTE attribute;
595
0
    SFTKDBHandle *dbHandle = NULL;
596
0
    SFTKTokenObject *to = sftk_narrowToTokenObject(object);
597
0
    CK_RV crv;
598
599
0
    PORT_Assert(to);
600
0
    if (to == NULL) {
601
0
        return CKR_DEVICE_ERROR;
602
0
    }
603
604
0
    dbHandle = sftk_getDBForTokenObject(object->slot, object->handle);
605
606
0
    attribute.type = type;
607
0
    attribute.pValue = (void *)value;
608
0
    attribute.ulValueLen = len;
609
610
0
    crv = sftkdb_SetAttributeValue(dbHandle, object, &attribute, 1);
611
0
    sftk_freeDB(dbHandle);
612
0
    return crv;
613
0
}
614
615
/*
616
 * force an attribute to a specifc value.
617
 */
618
CK_RV
619
sftk_forceAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
620
                    const void *value, unsigned int len)
621
0
{
622
0
    SFTKAttribute *attribute;
623
0
    void *att_val = NULL;
624
0
    PRBool freeData = PR_FALSE;
625
626
0
    PORT_Assert(object);
627
0
    PORT_Assert(object->refCount);
628
0
    PORT_Assert(object->slot);
629
0
    if (!object ||
630
0
        !object->refCount ||
631
0
        !object->slot) {
632
0
        return CKR_DEVICE_ERROR;
633
0
    }
634
0
    if (sftk_isToken(object->handle)) {
635
0
        return sftk_forceTokenAttribute(object, type, value, len);
636
0
    }
637
0
    attribute = sftk_FindAttribute(object, type);
638
0
    if (attribute == NULL)
639
0
        return sftk_AddAttributeType(object, type, value, len);
640
641
0
    if (value) {
642
0
        if (len <= ATTR_SPACE) {
643
0
            att_val = attribute->space;
644
0
        } else {
645
0
            att_val = PORT_Alloc(len);
646
0
            freeData = PR_TRUE;
647
0
        }
648
0
        if (att_val == NULL) {
649
0
            return CKR_HOST_MEMORY;
650
0
        }
651
0
        if (attribute->attrib.pValue == att_val) {
652
0
            PORT_Memset(attribute->attrib.pValue, 0,
653
0
                        attribute->attrib.ulValueLen);
654
0
        }
655
0
        PORT_Memcpy(att_val, value, len);
656
0
    }
657
0
    if (attribute->attrib.pValue != NULL) {
658
0
        if (attribute->attrib.pValue != att_val) {
659
0
            PORT_Memset(attribute->attrib.pValue, 0,
660
0
                        attribute->attrib.ulValueLen);
661
0
        }
662
0
        if (attribute->freeData) {
663
0
            PORT_Free(attribute->attrib.pValue);
664
0
        }
665
0
        attribute->freeData = PR_FALSE;
666
0
        attribute->attrib.pValue = NULL;
667
0
        attribute->attrib.ulValueLen = 0;
668
0
    }
669
0
    if (att_val) {
670
0
        attribute->attrib.pValue = att_val;
671
0
        attribute->attrib.ulValueLen = len;
672
0
        attribute->freeData = freeData;
673
0
    }
674
0
    sftk_FreeAttribute(attribute);
675
0
    return CKR_OK;
676
0
}
677
678
/*
679
 * return a null terminated string from attribute 'type'. This string
680
 * is allocated and needs to be freed with PORT_Free() When complete.
681
 */
682
char *
683
sftk_getString(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
684
0
{
685
0
    SFTKAttribute *attribute;
686
0
    char *label = NULL;
687
688
0
    attribute = sftk_FindAttribute(object, type);
689
0
    if (attribute == NULL)
690
0
        return NULL;
691
692
0
    if (attribute->attrib.pValue != NULL) {
693
0
        label = (char *)PORT_Alloc(attribute->attrib.ulValueLen + 1);
694
0
        if (label == NULL) {
695
0
            sftk_FreeAttribute(attribute);
696
0
            return NULL;
697
0
        }
698
699
0
        PORT_Memcpy(label, attribute->attrib.pValue,
700
0
                    attribute->attrib.ulValueLen);
701
0
        label[attribute->attrib.ulValueLen] = 0;
702
0
    }
703
0
    sftk_FreeAttribute(attribute);
704
0
    return label;
705
0
}
706
707
/*
708
 * decode when a particular attribute may be modified
709
 *  SFTK_NEVER: This attribute must be set at object creation time and
710
 *  can never be modified.
711
 *  SFTK_ONCOPY: This attribute may be modified only when you copy the
712
 *  object.
713
 *  SFTK_SENSITIVE: The CKA_SENSITIVE attribute can only be changed from
714
 *  CK_FALSE to CK_TRUE.
715
 *  SFTK_ALWAYS: This attribute can always be modified.
716
 * Some attributes vary their modification type based on the class of the
717
 *   object.
718
 */
719
SFTKModifyType
720
sftk_modifyType(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass)
721
0
{
722
    /* if we don't know about it, user user defined, always allow modify */
723
0
    SFTKModifyType mtype = SFTK_ALWAYS;
724
725
0
    switch (type) {
726
        /* NEVER */
727
0
        case CKA_CLASS:
728
0
        case CKA_CERTIFICATE_TYPE:
729
0
        case CKA_KEY_TYPE:
730
0
        case CKA_MODULUS:
731
0
        case CKA_MODULUS_BITS:
732
0
        case CKA_PUBLIC_EXPONENT:
733
0
        case CKA_PRIVATE_EXPONENT:
734
0
        case CKA_PRIME:
735
0
        case CKA_BASE:
736
0
        case CKA_PRIME_1:
737
0
        case CKA_PRIME_2:
738
0
        case CKA_EXPONENT_1:
739
0
        case CKA_EXPONENT_2:
740
0
        case CKA_COEFFICIENT:
741
0
        case CKA_VALUE_LEN:
742
0
        case CKA_ALWAYS_SENSITIVE:
743
0
        case CKA_NEVER_EXTRACTABLE:
744
0
        case CKA_NSS_DB:
745
0
            mtype = SFTK_NEVER;
746
0
            break;
747
748
        /* ONCOPY */
749
0
        case CKA_TOKEN:
750
0
        case CKA_PRIVATE:
751
0
        case CKA_MODIFIABLE:
752
0
            mtype = SFTK_ONCOPY;
753
0
            break;
754
755
        /* SENSITIVE */
756
0
        case CKA_SENSITIVE:
757
0
        case CKA_EXTRACTABLE:
758
0
            mtype = SFTK_SENSITIVE;
759
0
            break;
760
761
        /* ALWAYS */
762
0
        case CKA_LABEL:
763
0
        case CKA_APPLICATION:
764
0
        case CKA_ID:
765
0
        case CKA_SERIAL_NUMBER:
766
0
        case CKA_START_DATE:
767
0
        case CKA_END_DATE:
768
0
        case CKA_DERIVE:
769
0
        case CKA_ENCRYPT:
770
0
        case CKA_DECRYPT:
771
0
        case CKA_SIGN:
772
0
        case CKA_VERIFY:
773
0
        case CKA_SIGN_RECOVER:
774
0
        case CKA_VERIFY_RECOVER:
775
0
        case CKA_WRAP:
776
0
        case CKA_UNWRAP:
777
0
            mtype = SFTK_ALWAYS;
778
0
            break;
779
780
        /* DEPENDS ON CLASS */
781
0
        case CKA_VALUE:
782
0
            mtype = (inClass == CKO_DATA) ? SFTK_ALWAYS : SFTK_NEVER;
783
0
            break;
784
785
0
        case CKA_SUBPRIME:
786
            /* allow the CKA_SUBPRIME to be added to dh private keys */
787
0
            mtype = (inClass == CKO_PRIVATE_KEY) ? SFTK_ALWAYS : SFTK_NEVER;
788
0
            break;
789
790
0
        case CKA_SUBJECT:
791
0
            mtype = (inClass == CKO_CERTIFICATE) ? SFTK_NEVER : SFTK_ALWAYS;
792
0
            break;
793
0
        default:
794
0
            break;
795
0
    }
796
0
    return mtype;
797
0
}
798
799
/* decode if a particular attribute is sensitive (cannot be read
800
 * back to the user of if the object is set to SENSITIVE) */
801
PRBool
802
sftk_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass)
803
0
{
804
0
    switch (type) {
805
        /* ALWAYS */
806
0
        case CKA_PRIVATE_EXPONENT:
807
0
        case CKA_PRIME_1:
808
0
        case CKA_PRIME_2:
809
0
        case CKA_EXPONENT_1:
810
0
        case CKA_EXPONENT_2:
811
0
        case CKA_COEFFICIENT:
812
0
            return PR_TRUE;
813
814
        /* DEPENDS ON CLASS */
815
0
        case CKA_VALUE:
816
            /* PRIVATE and SECRET KEYS have SENSITIVE values */
817
0
            return (PRBool)((inClass == CKO_PRIVATE_KEY) || (inClass == CKO_SECRET_KEY));
818
819
0
        default:
820
0
            break;
821
0
    }
822
0
    return PR_FALSE;
823
0
}
824
825
/*
826
 * copy an attribute into a SECItem. Secitem is allocated in the specified
827
 * arena.
828
 */
829
CK_RV
830
sftk_Attribute2SecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object,
831
                       CK_ATTRIBUTE_TYPE type)
832
0
{
833
0
    int len;
834
0
    SFTKAttribute *attribute;
835
836
0
    attribute = sftk_FindAttribute(object, type);
837
0
    if (attribute == NULL)
838
0
        return CKR_TEMPLATE_INCOMPLETE;
839
0
    len = attribute->attrib.ulValueLen;
840
841
0
    if (arena) {
842
0
        item->data = (unsigned char *)PORT_ArenaAlloc(arena, len);
843
0
    } else {
844
0
        item->data = (unsigned char *)PORT_Alloc(len);
845
0
    }
846
0
    if (item->data == NULL) {
847
0
        sftk_FreeAttribute(attribute);
848
0
        return CKR_HOST_MEMORY;
849
0
    }
850
0
    item->len = len;
851
0
    PORT_Memcpy(item->data, attribute->attrib.pValue, len);
852
0
    sftk_FreeAttribute(attribute);
853
0
    return CKR_OK;
854
0
}
855
856
CK_RV
857
sftk_GetULongAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
858
                       CK_ULONG *longData)
859
0
{
860
0
    SFTKAttribute *attribute;
861
862
0
    attribute = sftk_FindAttribute(object, type);
863
0
    if (attribute == NULL)
864
0
        return CKR_TEMPLATE_INCOMPLETE;
865
866
0
    if (attribute->attrib.ulValueLen != sizeof(CK_ULONG)) {
867
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
868
0
    }
869
870
0
    *longData = *(CK_ULONG *)attribute->attrib.pValue;
871
0
    sftk_FreeAttribute(attribute);
872
0
    return CKR_OK;
873
0
}
874
875
void
876
sftk_DeleteAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type)
877
0
{
878
0
    SFTKAttribute *attribute;
879
0
    attribute = sftk_FindAttribute(object, type);
880
0
    if (attribute == NULL)
881
0
        return;
882
0
    sftk_DeleteAttribute(object, attribute);
883
0
    sftk_DestroyAttribute(attribute);
884
0
}
885
886
CK_RV
887
sftk_AddAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
888
                      const void *valPtr, CK_ULONG length)
889
0
{
890
0
    SFTKAttribute *attribute;
891
0
    attribute = sftk_NewAttribute(object, type, valPtr, length);
892
0
    if (attribute == NULL) {
893
0
        return CKR_HOST_MEMORY;
894
0
    }
895
0
    sftk_AddAttribute(object, attribute);
896
0
    return CKR_OK;
897
0
}
898
899
/*
900
 * ******************** Object Utilities *******************************
901
 */
902
903
/* must be called holding sftk_tokenKeyLock(slot) */
904
static SECItem *
905
sftk_lookupTokenKeyByHandle(SFTKSlot *slot, CK_OBJECT_HANDLE handle)
906
0
{
907
0
    return (SECItem *)PL_HashTableLookup(slot->tokObjHashTable, (void *)(uintptr_t)handle);
908
0
}
909
910
/*
911
 * use the refLock. This operations should be very rare, so the added
912
 * contention on the ref lock should be lower than the overhead of adding
913
 * a new lock. We use separate functions for this just in case I'm wrong.
914
 */
915
static void
916
sftk_tokenKeyLock(SFTKSlot *slot)
917
0
{
918
0
    SKIP_AFTER_FORK(PZ_Lock(slot->objectLock));
919
0
}
920
921
static void
922
sftk_tokenKeyUnlock(SFTKSlot *slot)
923
0
{
924
0
    SKIP_AFTER_FORK(PZ_Unlock(slot->objectLock));
925
0
}
926
927
static PRIntn
928
sftk_freeHashItem(PLHashEntry *entry, PRIntn index, void *arg)
929
0
{
930
0
    SECItem *item = (SECItem *)entry->value;
931
932
0
    SECITEM_FreeItem(item, PR_TRUE);
933
0
    return HT_ENUMERATE_NEXT;
934
0
}
935
936
CK_RV
937
SFTK_ClearTokenKeyHashTable(SFTKSlot *slot)
938
0
{
939
0
    sftk_tokenKeyLock(slot);
940
0
    PORT_Assert(!slot->present);
941
0
    PL_HashTableEnumerateEntries(slot->tokObjHashTable, sftk_freeHashItem, NULL);
942
0
    sftk_tokenKeyUnlock(slot);
943
0
    return CKR_OK;
944
0
}
945
946
/* allocation hooks that allow us to recycle old object structures */
947
static SFTKObjectFreeList sessionObjectList = { NULL, NULL, 0 };
948
static SFTKObjectFreeList tokenObjectList = { NULL, NULL, 0 };
949
950
SFTKObject *
951
sftk_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace,
952
                       SFTKObjectFreeList *list, unsigned int hashSize, PRBool isSessionObject)
953
0
{
954
0
    SFTKObject *object;
955
0
    int size = 0;
956
957
0
    if (!optimizeSpace) {
958
0
        PZ_Lock(list->lock);
959
0
        object = list->head;
960
0
        if (object) {
961
0
            list->head = object->next;
962
0
            list->count--;
963
0
        }
964
0
        PZ_Unlock(list->lock);
965
0
        if (object) {
966
            // As a safeguard against misuse of the library, ensure we don't
967
            // hand out live objects that somehow land in the free list.
968
0
            PORT_Assert(object->refCount == 0);
969
0
            if (object->refCount == 0) {
970
0
                object->next = object->prev = NULL;
971
0
                *hasLocks = PR_TRUE;
972
0
                return object;
973
0
            }
974
0
        }
975
0
    }
976
0
    size = isSessionObject ? sizeof(SFTKSessionObject) + hashSize * sizeof(SFTKAttribute *) : sizeof(SFTKTokenObject);
977
978
0
    object = (SFTKObject *)PORT_ZAlloc(size);
979
0
    if (isSessionObject && object) {
980
0
        ((SFTKSessionObject *)object)->hashSize = hashSize;
981
0
    }
982
0
    *hasLocks = PR_FALSE;
983
0
    return object;
984
0
}
985
986
static void
987
sftk_PutObjectToList(SFTKObject *object, SFTKObjectFreeList *list,
988
                     PRBool isSessionObject)
989
0
{
990
991
    /* the code below is equivalent to :
992
     *     optimizeSpace = isSessionObject ? object->optimizeSpace : PR_FALSE;
993
     * just faster.
994
     */
995
0
    PRBool optimizeSpace = isSessionObject &&
996
0
                           ((SFTKSessionObject *)object)->optimizeSpace;
997
0
    if (object->refLock && !optimizeSpace) {
998
0
        PZ_Lock(list->lock);
999
0
        if (list->count < MAX_OBJECT_LIST_SIZE) {
1000
0
            object->next = list->head;
1001
0
            list->head = object;
1002
0
            list->count++;
1003
0
            PZ_Unlock(list->lock);
1004
0
            return;
1005
0
        }
1006
0
        PZ_Unlock(list->lock);
1007
0
    }
1008
0
    if (isSessionObject) {
1009
0
        SFTKSessionObject *so = (SFTKSessionObject *)object;
1010
0
        PZ_DestroyLock(so->attributeLock);
1011
0
        so->attributeLock = NULL;
1012
0
    }
1013
0
    if (object->refLock) {
1014
0
        PZ_DestroyLock(object->refLock);
1015
0
        object->refLock = NULL;
1016
0
    }
1017
0
    PORT_Free(object);
1018
0
}
1019
1020
static SFTKObject *
1021
sftk_freeObjectData(SFTKObject *object)
1022
0
{
1023
0
    SFTKObject *next = object->next;
1024
1025
0
    PORT_Free(object);
1026
0
    return next;
1027
0
}
1028
1029
static void
1030
sftk_InitFreeList(SFTKObjectFreeList *list)
1031
0
{
1032
0
    if (!list->lock) {
1033
0
        list->lock = PZ_NewLock(nssILockObject);
1034
0
    }
1035
0
}
1036
1037
void
1038
sftk_InitFreeLists(void)
1039
0
{
1040
0
    sftk_InitFreeList(&sessionObjectList);
1041
0
    sftk_InitFreeList(&tokenObjectList);
1042
0
}
1043
1044
static void
1045
sftk_CleanupFreeList(SFTKObjectFreeList *list, PRBool isSessionList)
1046
0
{
1047
0
    SFTKObject *object;
1048
1049
0
    if (!list->lock) {
1050
0
        return;
1051
0
    }
1052
0
    SKIP_AFTER_FORK(PZ_Lock(list->lock));
1053
0
    for (object = list->head; object != NULL;
1054
0
         object = sftk_freeObjectData(object)) {
1055
0
        PZ_DestroyLock(object->refLock);
1056
0
        if (isSessionList) {
1057
0
            PZ_DestroyLock(((SFTKSessionObject *)object)->attributeLock);
1058
0
        }
1059
0
    }
1060
0
    list->count = 0;
1061
0
    list->head = NULL;
1062
0
    SKIP_AFTER_FORK(PZ_Unlock(list->lock));
1063
0
    SKIP_AFTER_FORK(PZ_DestroyLock(list->lock));
1064
0
    list->lock = NULL;
1065
0
}
1066
1067
void
1068
sftk_CleanupFreeLists(void)
1069
0
{
1070
0
    sftk_CleanupFreeList(&sessionObjectList, PR_TRUE);
1071
0
    sftk_CleanupFreeList(&tokenObjectList, PR_FALSE);
1072
0
}
1073
1074
/*
1075
 * Create a new object
1076
 */
1077
SFTKObject *
1078
sftk_NewObject(SFTKSlot *slot)
1079
0
{
1080
0
    SFTKObject *object;
1081
0
    SFTKSessionObject *sessObject;
1082
0
    PRBool hasLocks = PR_FALSE;
1083
0
    unsigned int i;
1084
0
    unsigned int hashSize = 0;
1085
1086
0
    hashSize = (slot->optimizeSpace) ? SPACE_ATTRIBUTE_HASH_SIZE : TIME_ATTRIBUTE_HASH_SIZE;
1087
1088
0
    object = sftk_GetObjectFromList(&hasLocks, slot->optimizeSpace,
1089
0
                                    &sessionObjectList, hashSize, PR_TRUE);
1090
0
    if (object == NULL) {
1091
0
        return NULL;
1092
0
    }
1093
0
    sessObject = (SFTKSessionObject *)object;
1094
0
    sessObject->nextAttr = 0;
1095
1096
0
    for (i = 0; i < MAX_OBJS_ATTRS; i++) {
1097
0
        sessObject->attrList[i].attrib.pValue = NULL;
1098
0
        sessObject->attrList[i].freeData = PR_FALSE;
1099
0
    }
1100
0
    sessObject->optimizeSpace = slot->optimizeSpace;
1101
1102
0
    object->handle = 0;
1103
0
    object->next = object->prev = NULL;
1104
0
    object->slot = slot;
1105
0
    object->isFIPS = sftk_isFIPS(slot->slotID);
1106
1107
0
    object->refCount = 1;
1108
0
    sessObject->sessionList.next = NULL;
1109
0
    sessObject->sessionList.prev = NULL;
1110
0
    sessObject->sessionList.parent = object;
1111
0
    sessObject->session = NULL;
1112
0
    sessObject->wasDerived = PR_FALSE;
1113
0
    if (!hasLocks)
1114
0
        object->refLock = PZ_NewLock(nssILockRefLock);
1115
0
    if (object->refLock == NULL) {
1116
0
        PORT_Free(object);
1117
0
        return NULL;
1118
0
    }
1119
0
    if (!hasLocks)
1120
0
        sessObject->attributeLock = PZ_NewLock(nssILockAttribute);
1121
0
    if (sessObject->attributeLock == NULL) {
1122
0
        PZ_DestroyLock(object->refLock);
1123
0
        PORT_Free(object);
1124
0
        return NULL;
1125
0
    }
1126
0
    for (i = 0; i < sessObject->hashSize; i++) {
1127
0
        sessObject->head[i] = NULL;
1128
0
    }
1129
0
    object->objectInfo = NULL;
1130
0
    object->infoFree = NULL;
1131
0
    return object;
1132
0
}
1133
1134
static CK_RV
1135
sftk_DestroySessionObjectData(SFTKSessionObject *so)
1136
0
{
1137
0
    int i;
1138
1139
0
    for (i = 0; i < MAX_OBJS_ATTRS; i++) {
1140
0
        unsigned char *value = so->attrList[i].attrib.pValue;
1141
0
        if (value) {
1142
0
            PORT_Memset(value, 0, so->attrList[i].attrib.ulValueLen);
1143
0
            if (so->attrList[i].freeData) {
1144
0
                PORT_Free(value);
1145
0
            }
1146
0
            so->attrList[i].attrib.pValue = NULL;
1147
0
            so->attrList[i].freeData = PR_FALSE;
1148
0
        }
1149
0
    }
1150
    /*  PZ_DestroyLock(so->attributeLock);*/
1151
0
    return CKR_OK;
1152
0
}
1153
1154
/*
1155
 * free all the data associated with an object. Object reference count must
1156
 * be 'zero'.
1157
 */
1158
static CK_RV
1159
sftk_DestroyObject(SFTKObject *object)
1160
0
{
1161
0
    CK_RV crv = CKR_OK;
1162
0
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1163
0
    SFTKTokenObject *to = sftk_narrowToTokenObject(object);
1164
1165
0
    PORT_Assert(object->refCount == 0);
1166
1167
    /* delete the database value */
1168
0
    if (to) {
1169
0
        if (to->dbKey.data) {
1170
0
            PORT_Free(to->dbKey.data);
1171
0
            to->dbKey.data = NULL;
1172
0
        }
1173
0
    }
1174
0
    if (so) {
1175
0
        sftk_DestroySessionObjectData(so);
1176
0
    }
1177
0
    if (object->objectInfo) {
1178
0
        (*object->infoFree)(object->objectInfo);
1179
0
        object->objectInfo = NULL;
1180
0
        object->infoFree = NULL;
1181
0
    }
1182
0
    if (so) {
1183
0
        sftk_PutObjectToList(object, &sessionObjectList, PR_TRUE);
1184
0
    } else {
1185
0
        sftk_PutObjectToList(object, &tokenObjectList, PR_FALSE);
1186
0
    }
1187
0
    return crv;
1188
0
}
1189
1190
void
1191
sftk_ReferenceObject(SFTKObject *object)
1192
0
{
1193
0
    PZ_Lock(object->refLock);
1194
0
    PORT_Assert(object->refCount > 0);
1195
0
    object->refCount++;
1196
0
    PZ_Unlock(object->refLock);
1197
0
}
1198
1199
static SFTKObject *
1200
sftk_ObjectFromHandleOnSlot(CK_OBJECT_HANDLE handle, SFTKSlot *slot)
1201
0
{
1202
0
    SFTKObject *object;
1203
0
    PRUint32 index = sftk_hash(handle, slot->sessObjHashSize);
1204
1205
0
    if (sftk_isToken(handle)) {
1206
0
        return sftk_NewTokenObject(slot, NULL, handle);
1207
0
    }
1208
1209
0
    PZ_Lock(slot->objectLock);
1210
0
    sftkqueue_find2(object, handle, index, slot->sessObjHashTable);
1211
0
    if (object) {
1212
0
        sftk_ReferenceObject(object);
1213
0
    }
1214
0
    PZ_Unlock(slot->objectLock);
1215
1216
0
    return (object);
1217
0
}
1218
/*
1219
 * look up and object structure from a handle. OBJECT_Handles only make
1220
 * sense in terms of a given session.  make a reference to that object
1221
 * structure returned.
1222
 */
1223
SFTKObject *
1224
sftk_ObjectFromHandle(CK_OBJECT_HANDLE handle, SFTKSession *session)
1225
0
{
1226
0
    SFTKSlot *slot = sftk_SlotFromSession(session);
1227
1228
0
    return sftk_ObjectFromHandleOnSlot(handle, slot);
1229
0
}
1230
1231
/*
1232
 * release a reference to an object handle
1233
 */
1234
SFTKFreeStatus
1235
sftk_FreeObject(SFTKObject *object)
1236
0
{
1237
0
    PRBool destroy = PR_FALSE;
1238
0
    CK_RV crv;
1239
1240
0
    PZ_Lock(object->refLock);
1241
0
    if (object->refCount == 1)
1242
0
        destroy = PR_TRUE;
1243
0
    object->refCount--;
1244
0
    PZ_Unlock(object->refLock);
1245
1246
0
    if (destroy) {
1247
0
        crv = sftk_DestroyObject(object);
1248
0
        if (crv != CKR_OK) {
1249
0
            return SFTK_DestroyFailure;
1250
0
        }
1251
0
        return SFTK_Destroyed;
1252
0
    }
1253
0
    return SFTK_Busy;
1254
0
}
1255
1256
/* find the next available object handle that isn't currently in use */
1257
/* NOTE: This function could loop forever if we've exhausted all
1258
 * 3^31-1 handles. This is highly unlikely (NSS has been running for
1259
 * decades with this code) uless we start increasing the size of the
1260
 * SFTK_TOKEN_MASK (which is just the high bit currently). */
1261
CK_OBJECT_HANDLE
1262
sftk_getNextHandle(SFTKSlot *slot)
1263
0
{
1264
0
    CK_OBJECT_HANDLE handle;
1265
0
    SFTKObject *duplicateObject = NULL;
1266
0
    do {
1267
0
        PRUint32 wrappedAround;
1268
1269
0
        duplicateObject = NULL;
1270
0
        PZ_Lock(slot->objectLock);
1271
0
        wrappedAround = slot->sessionObjectHandleCount & SFTK_TOKEN_MASK;
1272
0
        handle = slot->sessionObjectHandleCount & ~SFTK_TOKEN_MASK;
1273
0
        if (!handle) /* don't allow zero handle */
1274
0
            handle = NSC_MIN_SESSION_OBJECT_HANDLE;
1275
0
        slot->sessionObjectHandleCount = (handle + 1U) | wrappedAround;
1276
        /* Is there already a session object with this handle? */
1277
0
        if (wrappedAround) {
1278
0
            sftkqueue_find(duplicateObject, handle, slot->sessObjHashTable,
1279
0
                           slot->sessObjHashSize);
1280
0
        }
1281
0
        PZ_Unlock(slot->objectLock);
1282
0
    } while (duplicateObject != NULL);
1283
0
    return handle;
1284
0
}
1285
1286
/*
1287
 * add an object to a slot and session queue. These two functions
1288
 * adopt the object.
1289
 */
1290
void
1291
sftk_AddSlotObject(SFTKSlot *slot, SFTKObject *object)
1292
0
{
1293
0
    PRUint32 index = sftk_hash(object->handle, slot->sessObjHashSize);
1294
0
    sftkqueue_init_element(object);
1295
0
    PZ_Lock(slot->objectLock);
1296
0
    sftkqueue_add2(object, object->handle, index, slot->sessObjHashTable);
1297
0
    PZ_Unlock(slot->objectLock);
1298
0
}
1299
1300
void
1301
sftk_AddObject(SFTKSession *session, SFTKObject *object)
1302
0
{
1303
0
    SFTKSlot *slot = sftk_SlotFromSession(session);
1304
0
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1305
1306
0
    if (so) {
1307
0
        PZ_Lock(session->objectLock);
1308
0
        sftkqueue_add(&so->sessionList, 0, session->objects, 0);
1309
0
        so->session = session;
1310
0
        PZ_Unlock(session->objectLock);
1311
0
    }
1312
0
    sftk_AddSlotObject(slot, object);
1313
0
    sftk_ReferenceObject(object);
1314
0
}
1315
1316
/*
1317
 * delete an object from a slot and session queue
1318
 */
1319
CK_RV
1320
sftk_DeleteObject(SFTKSession *session, SFTKObject *object)
1321
0
{
1322
0
    SFTKSlot *slot = sftk_SlotFromSession(session);
1323
0
    SFTKSessionObject *so = sftk_narrowToSessionObject(object);
1324
0
    CK_RV crv = CKR_OK;
1325
0
    PRUint32 index = sftk_hash(object->handle, slot->sessObjHashSize);
1326
1327
    /* Handle Token case */
1328
0
    if (so && so->session) {
1329
0
        session = so->session;
1330
0
        PZ_Lock(session->objectLock);
1331
0
        sftkqueue_delete(&so->sessionList, 0, session->objects, 0);
1332
0
        PZ_Unlock(session->objectLock);
1333
0
        PZ_Lock(slot->objectLock);
1334
0
        sftkqueue_delete2(object, object->handle, index, slot->sessObjHashTable);
1335
0
        PZ_Unlock(slot->objectLock);
1336
0
        sftkqueue_clear_deleted_element(object);
1337
0
        sftk_FreeObject(object); /* free the reference owned by the queue */
1338
0
    } else {
1339
0
        SFTKDBHandle *handle = sftk_getDBForTokenObject(slot, object->handle);
1340
0
#ifdef DEBUG
1341
0
        SFTKTokenObject *to = sftk_narrowToTokenObject(object);
1342
0
        PORT_Assert(to);
1343
0
#endif
1344
0
        crv = sftkdb_DestroyObject(handle, object->handle, object->objclass);
1345
0
        sftk_freeDB(handle);
1346
0
    }
1347
0
    return crv;
1348
0
}
1349
1350
/*
1351
 * Token objects don't explicitly store their attributes, so we need to know
1352
 * what attributes make up a particular token object before we can copy it.
1353
 * below are the tables by object type.
1354
 */
1355
static const CK_ATTRIBUTE_TYPE commonAttrs[] = {
1356
    CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_MODIFIABLE
1357
};
1358
static const CK_ULONG commonAttrsCount =
1359
    sizeof(commonAttrs) / sizeof(commonAttrs[0]);
1360
1361
static const CK_ATTRIBUTE_TYPE commonKeyAttrs[] = {
1362
    CKA_ID, CKA_START_DATE, CKA_END_DATE, CKA_DERIVE, CKA_LOCAL, CKA_KEY_TYPE
1363
};
1364
static const CK_ULONG commonKeyAttrsCount =
1365
    sizeof(commonKeyAttrs) / sizeof(commonKeyAttrs[0]);
1366
1367
static const CK_ATTRIBUTE_TYPE secretKeyAttrs[] = {
1368
    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN,
1369
    CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_VALUE
1370
};
1371
static const CK_ULONG secretKeyAttrsCount =
1372
    sizeof(secretKeyAttrs) / sizeof(secretKeyAttrs[0]);
1373
1374
static const CK_ATTRIBUTE_TYPE commonPubKeyAttrs[] = {
1375
    CKA_ENCRYPT, CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_WRAP, CKA_SUBJECT
1376
};
1377
static const CK_ULONG commonPubKeyAttrsCount =
1378
    sizeof(commonPubKeyAttrs) / sizeof(commonPubKeyAttrs[0]);
1379
1380
static const CK_ATTRIBUTE_TYPE rsaPubKeyAttrs[] = {
1381
    CKA_MODULUS, CKA_PUBLIC_EXPONENT
1382
};
1383
static const CK_ULONG rsaPubKeyAttrsCount =
1384
    sizeof(rsaPubKeyAttrs) / sizeof(rsaPubKeyAttrs[0]);
1385
1386
static const CK_ATTRIBUTE_TYPE dsaPubKeyAttrs[] = {
1387
    CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE
1388
};
1389
static const CK_ULONG dsaPubKeyAttrsCount =
1390
    sizeof(dsaPubKeyAttrs) / sizeof(dsaPubKeyAttrs[0]);
1391
1392
static const CK_ATTRIBUTE_TYPE dhPubKeyAttrs[] = {
1393
    CKA_PRIME, CKA_BASE, CKA_VALUE
1394
};
1395
static const CK_ULONG dhPubKeyAttrsCount =
1396
    sizeof(dhPubKeyAttrs) / sizeof(dhPubKeyAttrs[0]);
1397
static const CK_ATTRIBUTE_TYPE ecPubKeyAttrs[] = {
1398
    CKA_EC_PARAMS, CKA_EC_POINT
1399
};
1400
static const CK_ULONG ecPubKeyAttrsCount =
1401
    sizeof(ecPubKeyAttrs) / sizeof(ecPubKeyAttrs[0]);
1402
1403
static const CK_ATTRIBUTE_TYPE commonPrivKeyAttrs[] = {
1404
    CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER, CKA_UNWRAP, CKA_SUBJECT,
1405
    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_NSS_DB, CKA_PUBLIC_KEY_INFO
1406
};
1407
static const CK_ULONG commonPrivKeyAttrsCount =
1408
    sizeof(commonPrivKeyAttrs) / sizeof(commonPrivKeyAttrs[0]);
1409
1410
static const CK_ATTRIBUTE_TYPE rsaPrivKeyAttrs[] = {
1411
    CKA_MODULUS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
1412
    CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT
1413
};
1414
static const CK_ULONG rsaPrivKeyAttrsCount =
1415
    sizeof(rsaPrivKeyAttrs) / sizeof(rsaPrivKeyAttrs[0]);
1416
1417
static const CK_ATTRIBUTE_TYPE dsaPrivKeyAttrs[] = {
1418
    CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE
1419
};
1420
static const CK_ULONG dsaPrivKeyAttrsCount =
1421
    sizeof(dsaPrivKeyAttrs) / sizeof(dsaPrivKeyAttrs[0]);
1422
1423
static const CK_ATTRIBUTE_TYPE dhPrivKeyAttrs[] = {
1424
    CKA_PRIME, CKA_BASE, CKA_VALUE
1425
};
1426
static const CK_ULONG dhPrivKeyAttrsCount =
1427
    sizeof(dhPrivKeyAttrs) / sizeof(dhPrivKeyAttrs[0]);
1428
static const CK_ATTRIBUTE_TYPE ecPrivKeyAttrs[] = {
1429
    CKA_EC_PARAMS, CKA_VALUE
1430
};
1431
static const CK_ULONG ecPrivKeyAttrsCount =
1432
    sizeof(ecPrivKeyAttrs) / sizeof(ecPrivKeyAttrs[0]);
1433
1434
static const CK_ATTRIBUTE_TYPE certAttrs[] = {
1435
    CKA_CERTIFICATE_TYPE, CKA_VALUE, CKA_SUBJECT, CKA_ISSUER, CKA_SERIAL_NUMBER
1436
};
1437
static const CK_ULONG certAttrsCount =
1438
    sizeof(certAttrs) / sizeof(certAttrs[0]);
1439
1440
static const CK_ATTRIBUTE_TYPE nssTrustAttrs[] = {
1441
    CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_NSS_CERT_SHA1_HASH,
1442
    CKA_NSS_CERT_MD5_HASH, CKA_NSS_TRUST_SERVER_AUTH, CKA_NSS_TRUST_CLIENT_AUTH,
1443
    CKA_NSS_TRUST_EMAIL_PROTECTION, CKA_NSS_TRUST_CODE_SIGNING,
1444
    CKA_NSS_TRUST_STEP_UP_APPROVED
1445
};
1446
static const CK_ULONG nssTrustAttrsCount =
1447
    sizeof(nssTrustAttrs) / sizeof(nssTrustAttrs[0]);
1448
1449
static const CK_ATTRIBUTE_TYPE trustAttrs[] = {
1450
    CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_HASH_OF_CERTIFICATE,
1451
    CKA_NAME_HASH_ALGORITHM, CKA_PKCS_TRUST_SERVER_AUTH,
1452
    CKA_PKCS_TRUST_CLIENT_AUTH, CKA_PKCS_TRUST_EMAIL_PROTECTION,
1453
    CKA_PKCS_TRUST_CODE_SIGNING
1454
};
1455
static const CK_ULONG trustAttrsCount =
1456
    sizeof(trustAttrs) / sizeof(trustAttrs[0]);
1457
1458
static const CK_ATTRIBUTE_TYPE smimeAttrs[] = {
1459
    CKA_SUBJECT, CKA_NSS_EMAIL, CKA_NSS_SMIME_TIMESTAMP, CKA_VALUE
1460
};
1461
static const CK_ULONG smimeAttrsCount =
1462
    sizeof(smimeAttrs) / sizeof(smimeAttrs[0]);
1463
1464
static const CK_ATTRIBUTE_TYPE crlAttrs[] = {
1465
    CKA_SUBJECT, CKA_VALUE, CKA_NSS_URL, CKA_NSS_KRL
1466
};
1467
static const CK_ULONG crlAttrsCount =
1468
    sizeof(crlAttrs) / sizeof(crlAttrs[0]);
1469
1470
/* copy an object based on it's table */
1471
CK_RV
1472
stfk_CopyTokenAttributes(SFTKObject *destObject, SFTKTokenObject *src_to,
1473
                         const CK_ATTRIBUTE_TYPE *attrArray, CK_ULONG attrCount)
1474
0
{
1475
0
    SFTKAttribute *attribute;
1476
0
    SFTKAttribute *newAttribute;
1477
0
    CK_RV crv = CKR_OK;
1478
0
    unsigned int i;
1479
1480
0
    for (i = 0; i < attrCount; i++) {
1481
0
        if (!sftk_hasAttribute(destObject, attrArray[i])) {
1482
0
            attribute = sftk_FindAttribute(&src_to->obj, attrArray[i]);
1483
0
            if (!attribute) {
1484
0
                continue; /* return CKR_ATTRIBUTE_VALUE_INVALID; */
1485
0
            }
1486
            /* we need to copy the attribute since each attribute
1487
             * only has one set of link list pointers */
1488
0
            newAttribute = sftk_NewAttribute(destObject,
1489
0
                                             sftk_attr_expand(&attribute->attrib));
1490
0
            sftk_FreeAttribute(attribute); /* free the old attribute */
1491
0
            if (!newAttribute) {
1492
0
                return CKR_HOST_MEMORY;
1493
0
            }
1494
0
            sftk_AddAttribute(destObject, newAttribute);
1495
0
        }
1496
0
    }
1497
0
    return crv;
1498
0
}
1499
1500
CK_RV
1501
stfk_CopyTokenPrivateKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1502
0
{
1503
0
    CK_RV crv;
1504
0
    CK_KEY_TYPE key_type;
1505
0
    SFTKAttribute *attribute;
1506
1507
    /* copy the common attributes for all keys first */
1508
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1509
0
                                   commonKeyAttrsCount);
1510
0
    if (crv != CKR_OK) {
1511
0
        goto fail;
1512
0
    }
1513
    /* copy the common attributes for all private keys next */
1514
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonPrivKeyAttrs,
1515
0
                                   commonPrivKeyAttrsCount);
1516
0
    if (crv != CKR_OK) {
1517
0
        goto fail;
1518
0
    }
1519
0
    attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE);
1520
0
    PORT_Assert(attribute); /* if it wasn't here, ww should have failed
1521
                             * copying the common attributes */
1522
0
    if (!attribute) {
1523
        /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but
1524
         * the fact is, the only reason we couldn't get the attribute would
1525
         * be a memory error or database error (an error in the 'device').
1526
         * if we have a database error code, we could return it here */
1527
0
        crv = CKR_DEVICE_ERROR;
1528
0
        goto fail;
1529
0
    }
1530
0
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1531
0
    sftk_FreeAttribute(attribute);
1532
1533
    /* finally copy the attributes for various private key types */
1534
0
    switch (key_type) {
1535
0
        case CKK_RSA:
1536
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPrivKeyAttrs,
1537
0
                                           rsaPrivKeyAttrsCount);
1538
0
            break;
1539
0
        case CKK_DSA:
1540
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPrivKeyAttrs,
1541
0
                                           dsaPrivKeyAttrsCount);
1542
0
            break;
1543
0
        case CKK_DH:
1544
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dhPrivKeyAttrs,
1545
0
                                           dhPrivKeyAttrsCount);
1546
0
            break;
1547
0
        case CKK_EC:
1548
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, ecPrivKeyAttrs,
1549
0
                                           ecPrivKeyAttrsCount);
1550
0
            break;
1551
0
        default:
1552
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
1553
                                     * of token keys into our database. */
1554
0
    }
1555
0
fail:
1556
0
    return crv;
1557
0
}
1558
1559
CK_RV
1560
stfk_CopyTokenPublicKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1561
0
{
1562
0
    CK_RV crv;
1563
0
    CK_KEY_TYPE key_type;
1564
0
    SFTKAttribute *attribute;
1565
1566
    /* copy the common attributes for all keys first */
1567
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1568
0
                                   commonKeyAttrsCount);
1569
0
    if (crv != CKR_OK) {
1570
0
        goto fail;
1571
0
    }
1572
1573
    /* copy the common attributes for all public keys next */
1574
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonPubKeyAttrs,
1575
0
                                   commonPubKeyAttrsCount);
1576
0
    if (crv != CKR_OK) {
1577
0
        goto fail;
1578
0
    }
1579
0
    attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE);
1580
0
    PORT_Assert(attribute); /* if it wasn't here, ww should have failed
1581
                             * copying the common attributes */
1582
0
    if (!attribute) {
1583
        /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but
1584
         * the fact is, the only reason we couldn't get the attribute would
1585
         * be a memory error or database error (an error in the 'device').
1586
         * if we have a database error code, we could return it here */
1587
0
        crv = CKR_DEVICE_ERROR;
1588
0
        goto fail;
1589
0
    }
1590
0
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1591
0
    sftk_FreeAttribute(attribute);
1592
1593
    /* finally copy the attributes for various public key types */
1594
0
    switch (key_type) {
1595
0
        case CKK_RSA:
1596
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPubKeyAttrs,
1597
0
                                           rsaPubKeyAttrsCount);
1598
0
            break;
1599
0
        case CKK_DSA:
1600
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPubKeyAttrs,
1601
0
                                           dsaPubKeyAttrsCount);
1602
0
            break;
1603
0
        case CKK_DH:
1604
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, dhPubKeyAttrs,
1605
0
                                           dhPubKeyAttrsCount);
1606
0
            break;
1607
0
        case CKK_EC:
1608
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, ecPubKeyAttrs,
1609
0
                                           ecPubKeyAttrsCount);
1610
0
            break;
1611
0
        default:
1612
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
1613
                                     * of token keys into our database. */
1614
0
    }
1615
0
fail:
1616
0
    return crv;
1617
0
}
1618
CK_RV
1619
stfk_CopyTokenSecretKey(SFTKObject *destObject, SFTKTokenObject *src_to)
1620
0
{
1621
0
    CK_RV crv;
1622
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs,
1623
0
                                   commonKeyAttrsCount);
1624
0
    if (crv != CKR_OK) {
1625
0
        goto fail;
1626
0
    }
1627
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, secretKeyAttrs,
1628
0
                                   secretKeyAttrsCount);
1629
0
fail:
1630
0
    return crv;
1631
0
}
1632
1633
/*
1634
 * Copy a token object. We need to explicitly copy the relevant
1635
 * attributes since token objects don't store those attributes in
1636
 * the token itself.
1637
 */
1638
CK_RV
1639
sftk_CopyTokenObject(SFTKObject *destObject, SFTKObject *srcObject)
1640
0
{
1641
0
    SFTKTokenObject *src_to = sftk_narrowToTokenObject(srcObject);
1642
0
    CK_RV crv;
1643
1644
0
    PORT_Assert(src_to);
1645
0
    if (src_to == NULL) {
1646
0
        return CKR_DEVICE_ERROR; /* internal state inconsistant */
1647
0
    }
1648
1649
0
    crv = stfk_CopyTokenAttributes(destObject, src_to, commonAttrs,
1650
0
                                   commonAttrsCount);
1651
0
    if (crv != CKR_OK) {
1652
0
        goto fail;
1653
0
    }
1654
0
    switch (src_to->obj.objclass) {
1655
0
        case CKO_CERTIFICATE:
1656
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, certAttrs,
1657
0
                                           certAttrsCount);
1658
0
            break;
1659
0
        case CKO_NSS_TRUST:
1660
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, nssTrustAttrs,
1661
0
                                           nssTrustAttrsCount);
1662
0
            break;
1663
0
        case CKO_TRUST:
1664
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, trustAttrs,
1665
0
                                           trustAttrsCount);
1666
0
            break;
1667
0
        case CKO_NSS_SMIME:
1668
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, smimeAttrs,
1669
0
                                           smimeAttrsCount);
1670
0
            break;
1671
0
        case CKO_NSS_CRL:
1672
0
            crv = stfk_CopyTokenAttributes(destObject, src_to, crlAttrs,
1673
0
                                           crlAttrsCount);
1674
0
            break;
1675
0
        case CKO_PRIVATE_KEY:
1676
0
            crv = stfk_CopyTokenPrivateKey(destObject, src_to);
1677
0
            break;
1678
0
        case CKO_PUBLIC_KEY:
1679
0
            crv = stfk_CopyTokenPublicKey(destObject, src_to);
1680
0
            break;
1681
0
        case CKO_SECRET_KEY:
1682
0
            crv = stfk_CopyTokenSecretKey(destObject, src_to);
1683
0
            break;
1684
0
        default:
1685
0
            crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
1686
                                     * of token keys into our database. */
1687
0
    }
1688
0
fail:
1689
0
    return crv;
1690
0
}
1691
1692
/*
1693
 * copy the attributes from one object to another. Don't overwrite existing
1694
 * attributes. NOTE: This is a pretty expensive operation since it
1695
 * grabs the attribute locks for the src object for a *long* time.
1696
 */
1697
CK_RV
1698
sftk_CopyObject(SFTKObject *destObject, SFTKObject *srcObject)
1699
0
{
1700
0
    SFTKAttribute *attribute;
1701
0
    SFTKSessionObject *src_so = sftk_narrowToSessionObject(srcObject);
1702
0
    unsigned int i;
1703
1704
0
    destObject->isFIPS = srcObject->isFIPS;
1705
0
    if (src_so == NULL) {
1706
0
        return sftk_CopyTokenObject(destObject, srcObject);
1707
0
    }
1708
1709
0
    PZ_Lock(src_so->attributeLock);
1710
0
    for (i = 0; i < src_so->hashSize; i++) {
1711
0
        attribute = src_so->head[i];
1712
0
        do {
1713
0
            if (attribute) {
1714
0
                if (!sftk_hasAttribute(destObject, attribute->handle)) {
1715
                    /* we need to copy the attribute since each attribute
1716
                     * only has one set of link list pointers */
1717
0
                    SFTKAttribute *newAttribute = sftk_NewAttribute(
1718
0
                        destObject, sftk_attr_expand(&attribute->attrib));
1719
0
                    if (newAttribute == NULL) {
1720
0
                        PZ_Unlock(src_so->attributeLock);
1721
0
                        return CKR_HOST_MEMORY;
1722
0
                    }
1723
0
                    sftk_AddAttribute(destObject, newAttribute);
1724
0
                }
1725
0
                attribute = attribute->next;
1726
0
            }
1727
0
        } while (attribute != NULL);
1728
0
    }
1729
0
    PZ_Unlock(src_so->attributeLock);
1730
1731
0
    return CKR_OK;
1732
0
}
1733
1734
/*
1735
 * ******************** Search Utilities *******************************
1736
 */
1737
1738
/* add an object to a search list */
1739
CK_RV
1740
AddToList(SFTKObjectListElement **list, SFTKObject *object)
1741
0
{
1742
0
    SFTKObjectListElement *newElem =
1743
0
        (SFTKObjectListElement *)PORT_Alloc(sizeof(SFTKObjectListElement));
1744
1745
0
    if (newElem == NULL)
1746
0
        return CKR_HOST_MEMORY;
1747
1748
0
    newElem->next = *list;
1749
0
    newElem->object = object;
1750
0
    sftk_ReferenceObject(object);
1751
1752
0
    *list = newElem;
1753
0
    return CKR_OK;
1754
0
}
1755
1756
/* return true if the object matches the template */
1757
PRBool
1758
sftk_objectMatch(SFTKObject *object, CK_ATTRIBUTE_PTR theTemplate, int count)
1759
0
{
1760
0
    int i;
1761
1762
0
    for (i = 0; i < count; i++) {
1763
0
        SFTKAttribute *attribute = sftk_FindAttribute(object, theTemplate[i].type);
1764
0
        if (attribute == NULL) {
1765
0
            return PR_FALSE;
1766
0
        }
1767
0
        if (attribute->attrib.ulValueLen == theTemplate[i].ulValueLen) {
1768
0
            if (PORT_Memcmp(attribute->attrib.pValue, theTemplate[i].pValue,
1769
0
                            theTemplate[i].ulValueLen) == 0) {
1770
0
                sftk_FreeAttribute(attribute);
1771
0
                continue;
1772
0
            }
1773
0
        }
1774
0
        sftk_FreeAttribute(attribute);
1775
0
        return PR_FALSE;
1776
0
    }
1777
0
    return PR_TRUE;
1778
0
}
1779
1780
/* search through all the objects in the queue and return the template matches
1781
 * in the object list.
1782
 */
1783
CK_RV
1784
sftk_searchObjectList(SFTKSearchResults *search, SFTKObject **head,
1785
                      unsigned int size, PZLock *lock, CK_ATTRIBUTE_PTR theTemplate,
1786
                      int count, PRBool isLoggedIn)
1787
0
{
1788
0
    unsigned int i;
1789
0
    SFTKObject *object;
1790
0
    CK_RV crv = CKR_OK;
1791
1792
0
    PZ_Lock(lock);
1793
0
    for (i = 0; i < size; i++) {
1794
0
        for (object = head[i]; object != NULL; object = object->next) {
1795
0
            if (sftk_objectMatch(object, theTemplate, count)) {
1796
                /* don't return objects that aren't yet visible */
1797
0
                if ((!isLoggedIn) && sftk_isTrue(object, CKA_PRIVATE))
1798
0
                    continue;
1799
0
                sftk_addHandle(search, object->handle);
1800
0
            }
1801
0
        }
1802
0
    }
1803
0
    PZ_Unlock(lock);
1804
0
    return crv;
1805
0
}
1806
1807
/*
1808
 * free a single list element. Return the Next object in the list.
1809
 */
1810
SFTKObjectListElement *
1811
sftk_FreeObjectListElement(SFTKObjectListElement *objectList)
1812
0
{
1813
0
    SFTKObjectListElement *ol = objectList->next;
1814
1815
0
    sftk_FreeObject(objectList->object);
1816
0
    PORT_Free(objectList);
1817
0
    return ol;
1818
0
}
1819
1820
/* free an entire object list */
1821
void
1822
sftk_FreeObjectList(SFTKObjectListElement *objectList)
1823
0
{
1824
0
    SFTKObjectListElement *ol;
1825
1826
0
    for (ol = objectList; ol != NULL; ol = sftk_FreeObjectListElement(ol)) {
1827
0
    }
1828
0
}
1829
1830
/*
1831
 * free a search structure
1832
 */
1833
void
1834
sftk_FreeSearch(SFTKSearchResults *search)
1835
0
{
1836
0
    if (search->handles) {
1837
0
        PORT_Free(search->handles);
1838
0
    }
1839
0
    PORT_Free(search);
1840
0
}
1841
1842
/*
1843
 * ******************** Session Utilities *******************************
1844
 */
1845
1846
/* update the sessions state based in it's flags and wether or not it's
1847
 * logged in */
1848
void
1849
sftk_update_state(SFTKSlot *slot, SFTKSession *session)
1850
0
{
1851
0
    if (slot->isLoggedIn) {
1852
0
        if (slot->ssoLoggedIn) {
1853
0
            session->info.state = CKS_RW_SO_FUNCTIONS;
1854
0
        } else if (session->info.flags & CKF_RW_SESSION) {
1855
0
            session->info.state = CKS_RW_USER_FUNCTIONS;
1856
0
        } else {
1857
0
            session->info.state = CKS_RO_USER_FUNCTIONS;
1858
0
        }
1859
0
    } else {
1860
0
        if (session->info.flags & CKF_RW_SESSION) {
1861
0
            session->info.state = CKS_RW_PUBLIC_SESSION;
1862
0
        } else {
1863
0
            session->info.state = CKS_RO_PUBLIC_SESSION;
1864
0
        }
1865
0
    }
1866
0
}
1867
1868
/* update the state of all the sessions on a slot */
1869
void
1870
sftk_update_all_states(SFTKSlot *slot)
1871
0
{
1872
0
    unsigned int i;
1873
0
    SFTKSession *session;
1874
1875
0
    for (i = 0; i < slot->sessHashSize; i++) {
1876
0
        PZLock *lock = SFTK_SESSION_LOCK(slot, i);
1877
0
        PZ_Lock(lock);
1878
0
        for (session = slot->head[i]; session; session = session->next) {
1879
0
            sftk_update_state(slot, session);
1880
0
        }
1881
0
        PZ_Unlock(lock);
1882
0
    }
1883
0
}
1884
1885
/*
1886
 * context are cipher and digest contexts that are associated with a session
1887
 */
1888
void
1889
sftk_FreeContext(SFTKSessionContext *context)
1890
0
{
1891
0
    if (context->cipherInfo) {
1892
0
        (*context->destroy)(context->cipherInfo, PR_TRUE);
1893
0
    }
1894
0
    if (context->hashInfo) {
1895
0
        (*context->hashdestroy)(context->hashInfo, PR_TRUE);
1896
0
    }
1897
0
    if (context->key) {
1898
0
        sftk_FreeObject(context->key);
1899
0
        context->key = NULL;
1900
0
    }
1901
0
    PORT_Free(context);
1902
0
}
1903
1904
/*
1905
 * Init a new session. NOTE: The session handle is not set, and the
1906
 * session is not added to the slot's session queue.
1907
 */
1908
CK_RV
1909
sftk_InitSession(SFTKSession *session, SFTKSlot *slot, CK_SLOT_ID slotID,
1910
                 CK_NOTIFY notify, CK_VOID_PTR pApplication, CK_FLAGS flags)
1911
0
{
1912
0
    session->next = session->prev = NULL;
1913
0
    session->enc_context = NULL;
1914
0
    session->hash_context = NULL;
1915
0
    session->sign_context = NULL;
1916
0
    session->search = NULL;
1917
0
    session->objectIDCount = 1;
1918
0
    session->objectLock = PZ_NewLock(nssILockObject);
1919
0
    if (session->objectLock == NULL) {
1920
0
        return CKR_HOST_MEMORY;
1921
0
    }
1922
0
    session->objects[0] = NULL;
1923
1924
0
    session->slot = slot;
1925
0
    session->notify = notify;
1926
0
    session->appData = pApplication;
1927
0
    session->info.flags = flags;
1928
0
    session->info.slotID = slotID;
1929
0
    session->info.ulDeviceError = 0;
1930
0
    sftk_update_state(slot, session);
1931
    /* no ops completed yet, so the last one couldn't be a FIPS op */
1932
0
    session->lastOpWasFIPS = PR_FALSE;
1933
0
    return CKR_OK;
1934
0
}
1935
1936
/*
1937
 * Create a new session and init it.
1938
 */
1939
SFTKSession *
1940
sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication,
1941
                CK_FLAGS flags)
1942
0
{
1943
0
    SFTKSession *session;
1944
0
    SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE);
1945
0
    CK_RV crv;
1946
1947
0
    if (slot == NULL)
1948
0
        return NULL;
1949
1950
0
    session = (SFTKSession *)PORT_Alloc(sizeof(SFTKSession));
1951
0
    if (session == NULL)
1952
0
        return NULL;
1953
1954
0
    crv = sftk_InitSession(session, slot, slotID, notify, pApplication, flags);
1955
0
    if (crv != CKR_OK) {
1956
0
        PORT_Free(session);
1957
0
        return NULL;
1958
0
    }
1959
0
    return session;
1960
0
}
1961
1962
/* free all the data associated with a session. */
1963
void
1964
sftk_ClearSession(SFTKSession *session)
1965
0
{
1966
0
    SFTKObjectList *op, *next;
1967
1968
    /* clean out the attributes */
1969
    /* since no one is referencing us, it's safe to walk the chain
1970
     * without a lock */
1971
0
    for (op = session->objects[0]; op != NULL; op = next) {
1972
0
        next = op->next;
1973
        /* paranoia */
1974
0
        op->next = op->prev = NULL;
1975
0
        sftk_DeleteObject(session, op->parent);
1976
0
    }
1977
0
    PZ_DestroyLock(session->objectLock);
1978
0
    if (session->enc_context) {
1979
0
        sftk_FreeContext(session->enc_context);
1980
0
    }
1981
0
    if (session->hash_context) {
1982
0
        sftk_FreeContext(session->hash_context);
1983
0
    }
1984
0
    if (session->sign_context) {
1985
0
        sftk_FreeContext(session->sign_context);
1986
0
    }
1987
0
    if (session->search) {
1988
0
        sftk_FreeSearch(session->search);
1989
0
    }
1990
0
}
1991
1992
/* free the data associated with the session, and the session */
1993
void
1994
sftk_DestroySession(SFTKSession *session)
1995
0
{
1996
0
    sftk_ClearSession(session);
1997
0
    PORT_Free(session);
1998
0
}
1999
2000
/*
2001
 * look up a session structure from a session handle
2002
 * generate a reference to it.
2003
 */
2004
SFTKSession *
2005
sftk_SessionFromHandle(CK_SESSION_HANDLE handle)
2006
0
{
2007
0
    SFTKSlot *slot = sftk_SlotFromSessionHandle(handle);
2008
0
    SFTKSession *session;
2009
0
    PZLock *lock;
2010
2011
0
    if (!slot)
2012
0
        return NULL;
2013
0
    lock = SFTK_SESSION_LOCK(slot, handle);
2014
2015
0
    PZ_Lock(lock);
2016
0
    sftkqueue_find(session, handle, slot->head, slot->sessHashSize);
2017
0
    PZ_Unlock(lock);
2018
2019
0
    return (session);
2020
0
}
2021
2022
/*
2023
 * release a reference to a session handle. This method of using SFTKSessions
2024
 * is deprecated, but the pattern should be retained until a future effort
2025
 * to refactor all SFTKSession users at once is completed.
2026
 */
2027
void
2028
sftk_FreeSession(SFTKSession *session)
2029
0
{
2030
0
    return;
2031
0
}
2032
2033
void
2034
sftk_addHandle(SFTKSearchResults *search, CK_OBJECT_HANDLE handle)
2035
0
{
2036
0
    if (search->handles == NULL) {
2037
0
        return;
2038
0
    }
2039
0
    if (search->size >= search->array_size) {
2040
0
        search->array_size += NSC_SEARCH_BLOCK_SIZE;
2041
0
        search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles,
2042
0
                                                           sizeof(CK_OBJECT_HANDLE) * search->array_size);
2043
0
        if (search->handles == NULL) {
2044
0
            return;
2045
0
        }
2046
0
    }
2047
0
    search->handles[search->size] = handle;
2048
0
    search->size++;
2049
0
}
2050
2051
static CK_RV
2052
handleToClass(SFTKSlot *slot, CK_OBJECT_HANDLE handle,
2053
              CK_OBJECT_CLASS *objClass)
2054
0
{
2055
0
    SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, handle);
2056
0
    CK_ATTRIBUTE objClassTemplate;
2057
0
    CK_RV crv;
2058
2059
0
    *objClass = CKO_DATA;
2060
0
    objClassTemplate.type = CKA_CLASS;
2061
0
    objClassTemplate.pValue = objClass;
2062
0
    objClassTemplate.ulValueLen = sizeof(*objClass);
2063
0
    crv = sftkdb_GetAttributeValue(dbHandle, handle, &objClassTemplate, 1);
2064
0
    sftk_freeDB(dbHandle);
2065
0
    return crv;
2066
0
}
2067
2068
SFTKObject *
2069
sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, CK_OBJECT_HANDLE handle)
2070
0
{
2071
0
    SFTKObject *object = NULL;
2072
0
    PRBool hasLocks = PR_FALSE;
2073
0
    CK_RV crv;
2074
2075
0
    object = sftk_GetObjectFromList(&hasLocks, PR_FALSE, &tokenObjectList, 0,
2076
0
                                    PR_FALSE);
2077
0
    if (object == NULL) {
2078
0
        return NULL;
2079
0
    }
2080
2081
0
    object->handle = handle;
2082
    /* every object must have a class, if we can't get it, the object
2083
     * doesn't exist */
2084
0
    crv = handleToClass(slot, handle, &object->objclass);
2085
0
    if (crv != CKR_OK) {
2086
0
        goto loser;
2087
0
    }
2088
0
    object->slot = slot;
2089
0
    object->isFIPS = sftk_isFIPS(slot->slotID);
2090
0
    object->objectInfo = NULL;
2091
0
    object->infoFree = NULL;
2092
0
    if (!hasLocks) {
2093
0
        object->refLock = PZ_NewLock(nssILockRefLock);
2094
0
    }
2095
0
    if (object->refLock == NULL) {
2096
0
        goto loser;
2097
0
    }
2098
0
    object->refCount = 1;
2099
2100
0
    return object;
2101
0
loser:
2102
0
    (void)sftk_DestroyObject(object);
2103
0
    return NULL;
2104
0
}
2105
2106
SFTKTokenObject *
2107
sftk_convertSessionToToken(SFTKObject *obj)
2108
0
{
2109
0
    SECItem *key;
2110
0
    SFTKSessionObject *so = (SFTKSessionObject *)obj;
2111
0
    SFTKTokenObject *to = sftk_narrowToTokenObject(obj);
2112
0
    SECStatus rv;
2113
2114
0
    sftk_DestroySessionObjectData(so);
2115
0
    PZ_DestroyLock(so->attributeLock);
2116
0
    if (to == NULL) {
2117
0
        return NULL;
2118
0
    }
2119
0
    sftk_tokenKeyLock(so->obj.slot);
2120
0
    key = sftk_lookupTokenKeyByHandle(so->obj.slot, so->obj.handle);
2121
0
    if (key == NULL) {
2122
0
        sftk_tokenKeyUnlock(so->obj.slot);
2123
0
        return NULL;
2124
0
    }
2125
0
    rv = SECITEM_CopyItem(NULL, &to->dbKey, key);
2126
0
    sftk_tokenKeyUnlock(so->obj.slot);
2127
0
    if (rv == SECFailure) {
2128
0
        return NULL;
2129
0
    }
2130
2131
0
    return to;
2132
0
}
2133
2134
SFTKSessionObject *
2135
sftk_narrowToSessionObject(SFTKObject *obj)
2136
0
{
2137
0
    return !sftk_isToken(obj->handle) ? (SFTKSessionObject *)obj : NULL;
2138
0
}
2139
2140
SFTKTokenObject *
2141
sftk_narrowToTokenObject(SFTKObject *obj)
2142
0
{
2143
0
    return sftk_isToken(obj->handle) ? (SFTKTokenObject *)obj : NULL;
2144
0
}
2145
2146
/* Constant time helper functions */
2147
2148
/* sftk_CKRVToMask returns, in constant time, a mask value of
2149
 * all ones if rv == CKR_OK.  Otherwise it returns zero. */
2150
unsigned int
2151
sftk_CKRVToMask(CK_RV rv)
2152
0
{
2153
0
    PR_STATIC_ASSERT(CKR_OK == 0);
2154
0
    return ~PORT_CT_NOT_ZERO(rv);
2155
0
}
2156
2157
/* sftk_CheckCBCPadding checks, in constant time, the padding validity and
2158
 * accordingly sets the pad length. */
2159
CK_RV
2160
sftk_CheckCBCPadding(CK_BYTE_PTR pBuf, unsigned int bufLen,
2161
                     unsigned int blockSize, unsigned int *outPadSize)
2162
0
{
2163
0
    PORT_Assert(outPadSize);
2164
2165
0
    unsigned int padSize = (unsigned int)pBuf[bufLen - 1];
2166
2167
    /* If padSize <= blockSize, set goodPad to all-1s and all-0s otherwise.*/
2168
0
    unsigned int goodPad = PORT_CT_DUPLICATE_MSB_TO_ALL(~(blockSize - padSize));
2169
    /* padSize should not be 0 */
2170
0
    goodPad &= PORT_CT_NOT_ZERO(padSize);
2171
2172
0
    unsigned int i;
2173
0
    for (i = 0; i < blockSize; i++) {
2174
        /* If i < padSize, set loopMask to all-1s and all-0s otherwise.*/
2175
0
        unsigned int loopMask = PORT_CT_DUPLICATE_MSB_TO_ALL(~(padSize - 1 - i));
2176
        /* Get the padding value (should be padSize) from buffer */
2177
0
        unsigned int padVal = pBuf[bufLen - 1 - i];
2178
        /* Update goodPad only if i < padSize */
2179
0
        goodPad &= PORT_CT_SEL(loopMask, ~(padVal ^ padSize), goodPad);
2180
0
    }
2181
2182
    /* If any of the final padding bytes had the wrong value, one or more
2183
     * of the lower eight bits of |goodPad| will be cleared. We AND the
2184
     * bottom 8 bits together and duplicate the result to all the bits. */
2185
0
    goodPad &= goodPad >> 4;
2186
0
    goodPad &= goodPad >> 2;
2187
0
    goodPad &= goodPad >> 1;
2188
0
    goodPad <<= sizeof(goodPad) * 8 - 1;
2189
0
    goodPad = PORT_CT_DUPLICATE_MSB_TO_ALL(goodPad);
2190
2191
    /* Set outPadSize to padSize or 0 */
2192
0
    *outPadSize = PORT_CT_SEL(goodPad, padSize, 0);
2193
    /* Return OK if the pad is valid */
2194
0
    return PORT_CT_SEL(goodPad, CKR_OK, CKR_ENCRYPTED_DATA_INVALID);
2195
0
}
2196
2197
void
2198
sftk_EncodeInteger(PRUint64 integer, CK_ULONG num_bits, CK_BBOOL littleEndian,
2199
                   CK_BYTE_PTR output, CK_ULONG_PTR output_len)
2200
0
{
2201
0
    if (output_len) {
2202
0
        *output_len = (num_bits / 8);
2203
0
    }
2204
2205
0
    PR_ASSERT(num_bits > 0 && num_bits <= 64 && (num_bits % 8) == 0);
2206
2207
0
    if (littleEndian == CK_TRUE) {
2208
0
        for (size_t offset = 0; offset < num_bits / 8; offset++) {
2209
0
            output[offset] = (unsigned char)((integer >> (offset * 8)) & 0xFF);
2210
0
        }
2211
0
    } else {
2212
0
        for (size_t offset = 0; offset < num_bits / 8; offset++) {
2213
0
            PRUint64 shift = num_bits - (offset + 1) * 8;
2214
0
            output[offset] = (unsigned char)((integer >> shift) & 0xFF);
2215
0
        }
2216
0
    }
2217
0
}
2218
2219
CK_FLAGS
2220
sftk_AttributeToFlags(CK_ATTRIBUTE_TYPE op)
2221
0
{
2222
0
    CK_FLAGS flags = 0;
2223
2224
0
    switch (op) {
2225
0
        case CKA_ENCRYPT:
2226
0
            flags = CKF_ENCRYPT;
2227
0
            break;
2228
0
        case CKA_DECRYPT:
2229
0
            flags = CKF_DECRYPT;
2230
0
            break;
2231
0
        case CKA_WRAP:
2232
0
            flags = CKF_WRAP;
2233
0
            break;
2234
0
        case CKA_UNWRAP:
2235
0
            flags = CKF_UNWRAP;
2236
0
            break;
2237
0
        case CKA_SIGN:
2238
0
            flags = CKF_SIGN;
2239
0
            break;
2240
0
        case CKA_SIGN_RECOVER:
2241
0
            flags = CKF_SIGN_RECOVER;
2242
0
            break;
2243
0
        case CKA_VERIFY:
2244
0
            flags = CKF_VERIFY;
2245
0
            break;
2246
0
        case CKA_VERIFY_RECOVER:
2247
0
            flags = CKF_VERIFY_RECOVER;
2248
0
            break;
2249
0
        case CKA_DERIVE:
2250
0
            flags = CKF_DERIVE;
2251
0
            break;
2252
        /* fake attribute to select digesting */
2253
0
        case CKA_DIGEST:
2254
0
            flags = CKF_DIGEST;
2255
0
            break;
2256
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
2257
0
            flags = CKF_MESSAGE_ENCRYPT;
2258
0
            break;
2259
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
2260
0
            flags = CKF_MESSAGE_DECRYPT;
2261
0
            break;
2262
0
        case CKA_NSS_MESSAGE | CKA_SIGN:
2263
0
            flags = CKF_MESSAGE_SIGN;
2264
0
            break;
2265
0
        case CKA_NSS_MESSAGE | CKA_VERIFY:
2266
0
            flags = CKF_MESSAGE_VERIFY;
2267
0
            break;
2268
0
        default:
2269
0
            break;
2270
0
    }
2271
0
    return flags;
2272
0
}
2273
2274
/*
2275
 * ******************** Hash Utilities **************************
2276
 */
2277
/*
2278
 * Utility function for converting PSS/OAEP parameter types into
2279
 * HASH_HashTypes. Note: Only SHA family functions are defined in RFC 3447.
2280
 */
2281
HASH_HashType
2282
sftk_GetHashTypeFromMechanism(CK_MECHANISM_TYPE mech)
2283
0
{
2284
0
    switch (mech) {
2285
0
        case CKM_SHA_1:
2286
0
        case CKG_MGF1_SHA1:
2287
0
            return HASH_AlgSHA1;
2288
0
        case CKM_SHA224:
2289
0
        case CKG_MGF1_SHA224:
2290
0
            return HASH_AlgSHA224;
2291
0
        case CKM_SHA256:
2292
0
        case CKG_MGF1_SHA256:
2293
0
            return HASH_AlgSHA256;
2294
0
        case CKM_SHA384:
2295
0
        case CKG_MGF1_SHA384:
2296
0
            return HASH_AlgSHA384;
2297
0
        case CKM_SHA512:
2298
0
        case CKG_MGF1_SHA512:
2299
0
            return HASH_AlgSHA512;
2300
0
        default:
2301
0
            return HASH_AlgNULL;
2302
0
    }
2303
0
}
2304
2305
#ifdef NSS_HAS_FIPS_INDICATORS
2306
/**************** FIPS Indicator Utilities *************************/
2307
/* sigh, we probably need a version of this in secutil so that both
2308
 * softoken and NSS can use it */
2309
static SECOidTag
2310
sftk_quickGetECCCurveOid(SFTKObject *source)
2311
{
2312
    SFTKAttribute *attribute = sftk_FindAttribute(source, CKA_EC_PARAMS);
2313
    unsigned char *encoded;
2314
    int len;
2315
    SECItem oid;
2316
    SECOidTag tag;
2317
2318
    if (attribute == NULL) {
2319
        return SEC_OID_UNKNOWN;
2320
    }
2321
    encoded = attribute->attrib.pValue;
2322
    len = attribute->attrib.ulValueLen;
2323
    if ((len < 2) || (encoded[0] != SEC_ASN1_OBJECT_ID) ||
2324
        (len != encoded[1] + 2)) {
2325
        sftk_FreeAttribute(attribute);
2326
        return SEC_OID_UNKNOWN;
2327
    }
2328
    oid.data = encoded + 2;
2329
    oid.len = len - 2;
2330
    tag = SECOID_FindOIDTag(&oid);
2331
    sftk_FreeAttribute(attribute);
2332
    return tag;
2333
}
2334
2335
/* This function currently only returns valid lengths for
2336
 * FIPS approved ECC curves. If we want to make this generic
2337
 * in the future, that Curve determination can be done in
2338
 * the sftk_handleSpecial. Since it's currently only used
2339
 * in FIPS indicators, it's currently only compiled with
2340
 * the FIPS indicator code */
2341
static int
2342
sftk_getKeyLength(SFTKObject *source)
2343
{
2344
    CK_KEY_TYPE keyType = CK_INVALID_HANDLE;
2345
    CK_ATTRIBUTE_TYPE keyAttribute;
2346
    CK_ULONG keyLength = 0;
2347
    SFTKAttribute *attribute;
2348
    CK_RV crv;
2349
2350
    /* If we don't have a key, then it doesn't have a length.
2351
     * this may be OK (say we are hashing). The mech info will
2352
     * sort this out because algorithms which expect no keys
2353
     * will accept zero length for the keys */
2354
    if (source == NULL) {
2355
        return 0;
2356
    }
2357
2358
    crv = sftk_GetULongAttribute(source, CKA_KEY_TYPE, &keyType);
2359
    if (crv != CKR_OK) {
2360
        /* sometimes we're passed a data object, in that case the
2361
         * key length is CKA_VALUE, which is the default */
2362
        keyType = CKK_INVALID_KEY_TYPE;
2363
    }
2364
    if (keyType == CKK_EC) {
2365
        SECOidTag curve = sftk_quickGetECCCurveOid(source);
2366
        switch (curve) {
2367
            case SEC_OID_CURVE25519:
2368
                /* change when we start algorithm testing on curve25519 */
2369
                return 0;
2370
            case SEC_OID_SECG_EC_SECP256R1:
2371
                return 256;
2372
            case SEC_OID_SECG_EC_SECP384R1:
2373
                return 384;
2374
            case SEC_OID_SECG_EC_SECP521R1:
2375
                /* this is a lie, but it makes the table easier. We don't
2376
                 * have to have a double entry for every ECC mechanism */
2377
                return 512;
2378
            default:
2379
                break;
2380
        }
2381
        /* other curves aren't NIST approved, returning 0 will cause these
2382
         * curves to fail FIPS length criteria */
2383
        return 0;
2384
    }
2385
2386
    switch (keyType) {
2387
        case CKK_RSA:
2388
            keyAttribute = CKA_MODULUS;
2389
            break;
2390
        case CKK_DSA:
2391
        case CKK_DH:
2392
            keyAttribute = CKA_PRIME;
2393
            break;
2394
        default:
2395
            keyAttribute = CKA_VALUE;
2396
            break;
2397
    }
2398
    attribute = sftk_FindAttribute(source, keyAttribute);
2399
    if (attribute) {
2400
        keyLength = attribute->attrib.ulValueLen * 8;
2401
        sftk_FreeAttribute(attribute);
2402
    }
2403
    return keyLength;
2404
}
2405
2406
/*
2407
 * handle specialized FIPS semantics that are too complicated to
2408
 * handle with just a table. NOTE: this means any additional semantics
2409
 * would have to be coded here before they can be added to the table */
2410
static PRBool
2411
sftk_handleSpecial(SFTKSlot *slot, CK_MECHANISM *mech,
2412
                   SFTKFIPSAlgorithmList *mechInfo, SFTKObject *source)
2413
{
2414
    switch (mechInfo->special) {
2415
        case SFTKFIPSDH: {
2416
            SECItem dhPrime;
2417
            SECItem dhBase;
2418
            SECItem dhGenerator;
2419
            PRBool fipsOk = PR_FALSE;
2420
            const SECItem *dhSubPrime;
2421
            CK_RV crv = sftk_Attribute2SecItem(NULL, &dhPrime,
2422
                                               source, CKA_PRIME);
2423
            if (crv != CKR_OK) {
2424
                return PR_FALSE;
2425
            }
2426
            crv = sftk_Attribute2SecItem(NULL, &dhBase, source, CKA_BASE);
2427
            if (crv != CKR_OK) {
2428
                return PR_FALSE;
2429
            }
2430
            dhSubPrime = sftk_VerifyDH_Prime(&dhPrime, &dhGenerator, PR_TRUE);
2431
            fipsOk = (dhSubPrime) ? PR_TRUE : PR_FALSE;
2432
            if (fipsOk && (SECITEM_CompareItem(&dhBase, &dhGenerator) != 0)) {
2433
                fipsOk = PR_FALSE;
2434
            }
2435
2436
            SECITEM_ZfreeItem(&dhPrime, PR_FALSE);
2437
            SECITEM_ZfreeItem(&dhBase, PR_FALSE);
2438
            return fipsOk;
2439
        }
2440
        case SFTKFIPSNone:
2441
            return PR_FALSE;
2442
        case SFTKFIPSECC:
2443
            /* we've already handled the curve selection in the 'getlength'
2444
             * function */
2445
            return PR_TRUE;
2446
        case SFTKFIPSAEAD: {
2447
            if (mech->ulParameterLen == 0) {
2448
                /* AEAD ciphers are only in FIPS mode if we are using the
2449
                 * MESSAGE interface. This takes an empty parameter
2450
                 * in the init function */
2451
                return PR_TRUE;
2452
            }
2453
            return PR_FALSE;
2454
        }
2455
        case SFTKFIPSRSAPSS: {
2456
            /* PSS salt must not be longer than the  underlying hash.
2457
             * We verify that the underlying hash of the
2458
             * parameters matches Hash of the combined hash mechanisms, so
2459
             * we don't need to look at the specific PSS mechanism */
2460
            CK_RSA_PKCS_PSS_PARAMS *pss = (CK_RSA_PKCS_PSS_PARAMS *)
2461
                                              mech->pParameter;
2462
            const SECHashObject *hashObj = NULL;
2463
            if (mech->ulParameterLen != sizeof(*pss)) {
2464
                return PR_FALSE;
2465
            }
2466
            /* we use the existing hash utilities to find the length of
2467
             * the hash */
2468
            hashObj = HASH_GetRawHashObject(sftk_GetHashTypeFromMechanism(
2469
                pss->hashAlg));
2470
            if (hashObj == NULL) {
2471
                return PR_FALSE;
2472
            }
2473
            if (pss->sLen > hashObj->length) {
2474
                return PR_FALSE;
2475
            }
2476
            return PR_TRUE;
2477
        }
2478
        default:
2479
            break;
2480
    }
2481
    /* if we didn't understand the special processing, mark it non-fips */
2482
    return PR_FALSE;
2483
}
2484
#endif
2485
2486
PRBool
2487
sftk_operationIsFIPS(SFTKSlot *slot, CK_MECHANISM *mech, CK_ATTRIBUTE_TYPE op,
2488
                     SFTKObject *source)
2489
0
{
2490
0
#ifndef NSS_HAS_FIPS_INDICATORS
2491
0
    return PR_FALSE;
2492
#else
2493
    int i;
2494
    CK_FLAGS opFlags;
2495
    CK_ULONG keyLength;
2496
2497
    /* handle all the quick stuff first */
2498
    if (!sftk_isFIPS(slot->slotID)) {
2499
        return PR_FALSE;
2500
    }
2501
    if (source && !source->isFIPS) {
2502
        return PR_FALSE;
2503
    }
2504
    if (mech == NULL) {
2505
        return PR_FALSE;
2506
    }
2507
2508
    /* now get the calculated values */
2509
    opFlags = sftk_AttributeToFlags(op);
2510
    if (opFlags == 0) {
2511
        return PR_FALSE;
2512
    }
2513
    keyLength = sftk_getKeyLength(source);
2514
2515
    /* check against our algorithm array */
2516
    for (i = 0; i < SFTK_NUMBER_FIPS_ALGORITHMS; i++) {
2517
        SFTKFIPSAlgorithmList *mechs = &sftk_fips_mechs[i];
2518
        /* if we match the number of records exactly, then we are an
2519
         * approved algorithm in the approved mode with an approved key */
2520
        if (((mech->mechanism == mechs->type) &&
2521
             (opFlags == (mechs->info.flags & opFlags)) &&
2522
             (keyLength <= mechs->info.ulMaxKeySize) &&
2523
             (keyLength >= mechs->info.ulMinKeySize) &&
2524
             ((keyLength - mechs->info.ulMinKeySize) % mechs->step) == 0) &&
2525
            ((mechs->special == SFTKFIPSNone) ||
2526
             sftk_handleSpecial(slot, mech, mechs, source))) {
2527
            return PR_TRUE;
2528
        }
2529
    }
2530
    return PR_FALSE;
2531
#endif
2532
0
}
2533
2534
/*
2535
 * create the FIPS Validation objects. If the vendor
2536
 * doesn't supply an NSS_FIPS_MODULE_ID, at compile time,
2537
 * then we assumethis is an unvalidated module.
2538
 */
2539
CK_RV
2540
sftk_CreateValidationObjects(SFTKSlot *slot)
2541
0
{
2542
0
    const char *module_id;
2543
0
    int module_id_len;
2544
0
    CK_RV crv = CKR_OK;
2545
    /* we currently use vendor specific values until the validation
2546
     * objects are approved for PKCS #11 v3.2. */
2547
0
    CK_OBJECT_CLASS cko_validation = CKO_NSS_VALIDATION;
2548
0
    CK_NSS_VALIDATION_TYPE ckv_fips = CKV_NSS_FIPS_140;
2549
0
    CK_VERSION fips_version = { 3, 0 }; /* FIPS-140-3 */
2550
0
    CK_ULONG fips_level = 1;            /* or 2 if you validated at level 2 */
2551
2552
0
#ifndef NSS_FIPS_MODULE_ID
2553
0
#define NSS_FIPS_MODULE_ID "Generic NSS " SOFTOKEN_VERSION " Unvalidated"
2554
0
#endif
2555
0
    module_id = NSS_FIPS_MODULE_ID;
2556
0
    module_id_len = sizeof(NSS_FIPS_MODULE_ID) - 1;
2557
0
    SFTKObject *object;
2558
2559
0
    object = sftk_NewObject(slot); /* fill in the handle later */
2560
0
    if (object == NULL) {
2561
0
        return CKR_HOST_MEMORY;
2562
0
    }
2563
0
    object->isFIPS = PR_FALSE;
2564
2565
0
    crv = sftk_AddAttributeType(object, CKA_CLASS,
2566
0
                                &cko_validation, sizeof(cko_validation));
2567
0
    if (crv != CKR_OK) {
2568
0
        goto loser;
2569
0
    }
2570
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_TYPE,
2571
0
                                &ckv_fips, sizeof(ckv_fips));
2572
0
    if (crv != CKR_OK) {
2573
0
        goto loser;
2574
0
    }
2575
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_VERSION,
2576
0
                                &fips_version, sizeof(fips_version));
2577
0
    if (crv != CKR_OK) {
2578
0
        goto loser;
2579
0
    }
2580
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_LEVEL,
2581
0
                                &fips_level, sizeof(fips_level));
2582
0
    if (crv != CKR_OK) {
2583
0
        goto loser;
2584
0
    }
2585
0
    crv = sftk_AddAttributeType(object, CKA_NSS_VALIDATION_MODULE_ID,
2586
0
                                module_id, module_id_len);
2587
0
    if (crv != CKR_OK) {
2588
0
        goto loser;
2589
0
    }
2590
2591
    /* future, fill in validation certificate information from a supplied
2592
     * pointer to a config file */
2593
0
    object->handle = sftk_getNextHandle(slot);
2594
0
    object->slot = slot;
2595
0
    sftk_AddObject(&slot->moduleObjects, object);
2596
0
loser:
2597
0
    sftk_FreeObject(object);
2598
0
    return crv;
2599
0
}