Coverage Report

Created: 2025-08-18 06:34

/src/nss/lib/pk11wrap/pk11cxt.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
 * This file PK11Contexts which are  used in multipart hashing,
6
 * encryption/decryption, and signing/verication operations.
7
 */
8
9
#include "seccomon.h"
10
#include "secmod.h"
11
#include "nssilock.h"
12
#include "secmodi.h"
13
#include "secmodti.h"
14
#include "pkcs11.h"
15
#include "pk11func.h"
16
#include "secitem.h"
17
#include "secoid.h"
18
#include "sechash.h"
19
#include "secerr.h"
20
#include "blapit.h"
21
#include "secport.h"
22
23
static const SECItem pk11_null_params = { 0 };
24
25
/**********************************************************************
26
 *
27
 *                   Now Deal with Crypto Contexts
28
 *
29
 **********************************************************************/
30
31
/*
32
 * the monitors...
33
 */
34
void
35
PK11_EnterContextMonitor(PK11Context *cx)
36
0
{
37
    /* if we own the session and our slot is ThreadSafe, only monitor
38
     * the Context */
39
0
    if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
40
        /* Should this use monitors instead? */
41
0
        PZ_Lock(cx->sessionLock);
42
0
    } else {
43
0
        PK11_EnterSlotMonitor(cx->slot);
44
0
    }
45
0
}
46
47
void
48
PK11_ExitContextMonitor(PK11Context *cx)
49
0
{
50
    /* if we own the session and our slot is ThreadSafe, only monitor
51
     * the Context */
52
0
    if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
53
        /* Should this use monitors instead? */
54
0
        PZ_Unlock(cx->sessionLock);
55
0
    } else {
56
0
        PK11_ExitSlotMonitor(cx->slot);
57
0
    }
58
0
}
59
60
/*
61
 * Free up a Cipher Context
62
 */
63
void
64
PK11_DestroyContext(PK11Context *context, PRBool freeit)
65
0
{
66
0
    pk11_CloseSession(context->slot, context->session, context->ownSession);
67
    /* initialize the critical fields of the context */
68
0
    if (context->savedData != NULL)
69
0
        PORT_Free(context->savedData);
70
0
    if (context->key)
71
0
        PK11_FreeSymKey(context->key);
72
0
    if (context->param && context->param != &pk11_null_params)
73
0
        SECITEM_FreeItem(context->param, PR_TRUE);
74
0
    if (context->sessionLock)
75
0
        PZ_DestroyLock(context->sessionLock);
76
0
    PK11_FreeSlot(context->slot);
77
0
    if (freeit)
78
0
        PORT_Free(context);
79
0
}
80
81
/*
82
 * save the current context. Allocate Space if necessary.
83
 */
84
static unsigned char *
85
pk11_saveContextHelper(PK11Context *context, unsigned char *buffer,
86
                       unsigned long *savedLength)
87
0
{
88
0
    CK_RV crv;
89
90
    /* If buffer is NULL, this will get the length */
91
0
    crv = PK11_GETTAB(context->slot)->C_GetOperationState(context->session, (CK_BYTE_PTR)buffer, savedLength);
92
0
    if (!buffer || (crv == CKR_BUFFER_TOO_SMALL)) {
93
        /* the given buffer wasn't big enough (or was NULL), but we
94
         * have the length, so try again with a new buffer and the
95
         * correct length
96
         */
97
0
        unsigned long bufLen = *savedLength;
98
0
        buffer = PORT_Alloc(bufLen);
99
0
        if (buffer == NULL) {
100
0
            return (unsigned char *)NULL;
101
0
        }
102
0
        crv = PK11_GETTAB(context->slot)->C_GetOperationState(context->session, (CK_BYTE_PTR)buffer, savedLength);
103
0
        if (crv != CKR_OK) {
104
0
            PORT_ZFree(buffer, bufLen);
105
0
        }
106
0
    }
107
0
    if (crv != CKR_OK) {
108
0
        PORT_SetError(PK11_MapError(crv));
109
0
        return (unsigned char *)NULL;
110
0
    }
111
0
    return buffer;
112
0
}
113
114
void *
115
pk11_saveContext(PK11Context *context, void *space, unsigned long *savedLength)
116
0
{
117
0
    return pk11_saveContextHelper(context,
118
0
                                  (unsigned char *)space, savedLength);
119
0
}
120
121
/*
122
 * restore the current context
123
 */
124
SECStatus
125
pk11_restoreContext(PK11Context *context, void *space, unsigned long savedLength)
126
0
{
127
0
    CK_RV crv;
128
0
    CK_OBJECT_HANDLE objectID = context->objectID;
129
130
0
    PORT_Assert(space != NULL);
131
0
    if (space == NULL) {
132
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
133
0
        return SECFailure;
134
0
    }
135
0
    crv = PK11_GETTAB(context->slot)->C_SetOperationState(context->session, (CK_BYTE_PTR)space, savedLength, objectID, 0);
136
0
    if (crv != CKR_OK) {
137
0
        PORT_SetError(PK11_MapError(crv));
138
0
        return SECFailure;
139
0
    }
140
0
    return SECSuccess;
141
0
}
142
143
SECStatus pk11_Finalize(PK11Context *context);
144
145
/*
146
 *  Initialize a Message function. Particular function is passed in as a
147
 *  function pointer. Since all C_Message*Init funcitons have the same
148
 *  prototype, we just pick one of the the prototypes to declare our init
149
 *  function.
150
 */
151
static CK_RV
152
pk11_contextInitMessage(PK11Context *context, CK_MECHANISM_PTR mech,
153
                        CK_C_MessageEncryptInit initFunc,
154
                        CK_FLAGS flags, CK_RV scrv)
155
0
{
156
0
    PK11SlotInfo *slot = context->slot;
157
0
    CK_RV crv = CKR_OK;
158
159
0
    context->ivCounter = 0;
160
0
    context->ivMaxCount = 0;
161
0
    context->ivFixedBits = 0;
162
0
    context->ivLen = 0;
163
0
    context->ivGen = CKG_NO_GENERATE;
164
0
    context->simulate_mechanism = (mech)->mechanism;
165
0
    context->simulate_message = PR_FALSE;
166
    /* check that we can do the Message interface. We need to check
167
     * for either 1) are we using a PKCS #11 v3 interface and 2) is the
168
     * Message flag set on the mechanism. If either is false we simulate
169
     * the message interface for the Encrypt and Decrypt cases using the
170
     * PKCS #11 V2 interface.
171
     * Sign and verify do not have V2 interfaces, so we go ahead and fail
172
     * if those cases */
173
0
    if ((PK11_CheckPKCS11Version(slot, 3, 0, PR_TRUE) >= 0) &&
174
0
        PK11_DoesMechanismFlag(slot, (mech)->mechanism, flags)) {
175
0
        PK11_EnterContextMonitor(context);
176
0
        crv = (*initFunc)((context)->session, (mech), (context)->objectID);
177
0
        PK11_ExitContextMonitor(context);
178
0
        if ((crv == CKR_FUNCTION_NOT_SUPPORTED) ||
179
0
            (crv == CKR_MECHANISM_INVALID)) {
180
            /* we have a 3.0 interface, and the flag was set (or ignored)
181
             * but the implementation was not there, use the V2 interface */
182
0
            crv = (scrv);
183
0
            context->simulate_message = PR_TRUE;
184
0
        }
185
0
    } else {
186
0
        crv = (scrv);
187
0
        context->simulate_message = PR_TRUE;
188
0
    }
189
0
    return crv;
190
0
}
191
192
/*
193
 * Context initialization. Used by all flavors of CreateContext
194
 */
195
static SECStatus
196
pk11_context_init(PK11Context *context, CK_MECHANISM *mech_info)
197
0
{
198
0
    CK_RV crv;
199
0
    SECStatus rv = SECSuccess;
200
201
0
    context->simulate_message = PR_FALSE;
202
0
    switch (context->operation) {
203
0
        case CKA_ENCRYPT:
204
0
            PK11_EnterContextMonitor(context);
205
0
            crv = PK11_GETTAB(context->slot)->C_EncryptInit(context->session, mech_info, context->objectID);
206
0
            PK11_ExitContextMonitor(context);
207
0
            break;
208
0
        case CKA_DECRYPT:
209
0
            PK11_EnterContextMonitor(context);
210
0
            if (context->fortezzaHack) {
211
0
                CK_ULONG count = 0;
212
                /* generate the IV for fortezza */
213
0
                crv = PK11_GETTAB(context->slot)->C_EncryptInit(context->session, mech_info, context->objectID);
214
0
                if (crv != CKR_OK) {
215
0
                    PK11_ExitContextMonitor(context);
216
0
                    break;
217
0
                }
218
0
                PK11_GETTAB(context->slot)
219
0
                    ->C_EncryptFinal(context->session,
220
0
                                     NULL, &count);
221
0
            }
222
0
            crv = PK11_GETTAB(context->slot)->C_DecryptInit(context->session, mech_info, context->objectID);
223
0
            PK11_ExitContextMonitor(context);
224
0
            break;
225
0
        case CKA_SIGN:
226
0
            PK11_EnterContextMonitor(context);
227
0
            crv = PK11_GETTAB(context->slot)->C_SignInit(context->session, mech_info, context->objectID);
228
0
            PK11_ExitContextMonitor(context);
229
0
            break;
230
0
        case CKA_VERIFY:
231
            /* NOTE: we previously has this set to C_SignInit for Macing.
232
             * It turns out now one could possibly use it that way, though,
233
             * because PK11_HashOp() always called C_VerifyUpdate on CKA_VERIFY,
234
             * which would have failed. So everyone just calls us with CKA_SIGN
235
             * when Macing even when they are verifying, no need to 'do it
236
             * for them'. It needs to be VerifyInit now so that we can do
237
             * PKCS #11 hash/Verify combo operations. */
238
0
            PK11_EnterContextMonitor(context);
239
0
            crv = PK11_GETTAB(context->slot)->C_VerifyInit(context->session, mech_info, context->objectID);
240
0
            PK11_ExitContextMonitor(context);
241
0
            break;
242
0
        case CKA_DIGEST:
243
0
            PK11_EnterContextMonitor(context);
244
0
            crv = PK11_GETTAB(context->slot)->C_DigestInit(context->session, mech_info);
245
0
            PK11_ExitContextMonitor(context);
246
0
            break;
247
248
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
249
0
            crv = pk11_contextInitMessage(context, mech_info,
250
0
                                          PK11_GETTAB(context->slot)->C_MessageEncryptInit,
251
0
                                          CKF_MESSAGE_ENCRYPT, CKR_OK);
252
0
            break;
253
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
254
0
            crv = pk11_contextInitMessage(context, mech_info,
255
0
                                          PK11_GETTAB(context->slot)->C_MessageDecryptInit,
256
0
                                          CKF_MESSAGE_DECRYPT, CKR_OK);
257
0
            break;
258
0
        case CKA_NSS_MESSAGE | CKA_SIGN:
259
0
            crv = pk11_contextInitMessage(context, mech_info,
260
0
                                          PK11_GETTAB(context->slot)->C_MessageSignInit,
261
0
                                          CKF_MESSAGE_SIGN, CKR_FUNCTION_NOT_SUPPORTED);
262
0
            break;
263
0
        case CKA_NSS_MESSAGE | CKA_VERIFY:
264
0
            crv = pk11_contextInitMessage(context, mech_info,
265
0
                                          PK11_GETTAB(context->slot)->C_MessageVerifyInit,
266
0
                                          CKF_MESSAGE_VERIFY, CKR_FUNCTION_NOT_SUPPORTED);
267
0
            break;
268
0
        default:
269
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
270
0
            break;
271
0
    }
272
273
0
    if (crv != CKR_OK) {
274
0
        PORT_SetError(PK11_MapError(crv));
275
0
        return SECFailure;
276
0
    }
277
278
    /* handle the case where the token is using the old NSS mechanism */
279
0
    if (context->simulate_message &&
280
0
        !PK11_DoesMechanism(context->slot, context->simulate_mechanism)) {
281
0
        if ((context->simulate_mechanism == CKM_CHACHA20_POLY1305) &&
282
0
            PK11_DoesMechanism(context->slot, CKM_NSS_CHACHA20_POLY1305)) {
283
0
            context->simulate_mechanism = CKM_NSS_CHACHA20_POLY1305;
284
0
        } else {
285
0
            PORT_SetError(PK11_MapError(CKR_MECHANISM_INVALID));
286
0
            return SECFailure;
287
0
        }
288
0
    }
289
290
    /*
291
     * handle session starvation case.. use our last session to multiplex
292
     */
293
0
    if (!context->ownSession) {
294
0
        PK11_EnterContextMonitor(context);
295
0
        context->savedData = pk11_saveContext(context, context->savedData,
296
0
                                              &context->savedLength);
297
0
        if (context->savedData == NULL)
298
0
            rv = SECFailure;
299
        /* clear out out session for others to use */
300
0
        pk11_Finalize(context);
301
0
        PK11_ExitContextMonitor(context);
302
0
    }
303
0
    return rv;
304
0
}
305
306
/*
307
 * Testing interfaces, not for general use. This function forces
308
 * an AEAD context into simulation mode even though the target token
309
 * can already do PKCS #11 v3.0 Message (i.e. softoken).
310
 */
311
SECStatus
312
_PK11_ContextSetAEADSimulation(PK11Context *context)
313
0
{
314
0
    CK_RV crv;
315
    /* only message encrypt and message decrypt contexts can be simulated */
316
0
    if ((context->operation != (CKA_NSS_MESSAGE | CKA_ENCRYPT)) &&
317
0
        (context->operation != (CKA_NSS_MESSAGE | CKA_DECRYPT))) {
318
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
319
0
        return SECFailure;
320
0
    }
321
    /* if we are already simulating, return */
322
0
    if (context->simulate_message) {
323
0
        return SECSuccess;
324
0
    }
325
    /* we need to shutdown the existing AEAD operation */
326
0
    switch (context->operation) {
327
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
328
0
            crv = PK11_GETTAB(context->slot)->C_MessageEncryptFinal(context->session);
329
0
            break;
330
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
331
0
            crv = PK11_GETTAB(context->slot)->C_MessageDecryptFinal(context->session);
332
0
            break;
333
0
        default:
334
0
            PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
335
0
            return SECFailure;
336
0
    }
337
0
    if (crv != CKR_OK) {
338
0
        PORT_SetError(PK11_MapError(crv));
339
0
        return SECFailure;
340
0
    }
341
0
    context->simulate_message = PR_TRUE;
342
0
    return SECSuccess;
343
0
}
344
345
PRBool
346
_PK11_ContextGetAEADSimulation(PK11Context *context)
347
0
{
348
0
    return context->simulate_message;
349
0
}
350
351
/*
352
 * Common Helper Function do come up with a new context.
353
 */
354
static PK11Context *
355
pk11_CreateNewContextInSlot(CK_MECHANISM_TYPE type,
356
                            PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation,
357
                            PK11SymKey *symKey, CK_OBJECT_HANDLE objectID,
358
                            const SECItem *param, void *pwArg)
359
0
{
360
0
    CK_MECHANISM mech_info;
361
0
    PK11Context *context;
362
0
    SECStatus rv;
363
364
0
    PORT_Assert(slot != NULL);
365
0
    if (!slot || ((objectID == CK_INVALID_HANDLE) && ((operation != CKA_DIGEST) ||
366
0
                                                      (type == CKM_SKIPJACK_CBC64)))) {
367
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
368
0
        return NULL;
369
0
    }
370
0
    context = (PK11Context *)PORT_Alloc(sizeof(PK11Context));
371
0
    if (context == NULL) {
372
0
        return NULL;
373
0
    }
374
375
    /* now deal with the fortezza hack... the fortezza hack is an attempt
376
     * to get around the issue of the card not allowing you to do a FORTEZZA
377
     * LoadIV/Encrypt, which was added because such a combination could be
378
     * use to circumvent the key escrow system. Unfortunately SSL needs to
379
     * do this kind of operation, so in SSL we do a loadIV (to verify it),
380
     * Then GenerateIV, and through away the first 8 bytes on either side
381
     * of the connection.*/
382
0
    context->fortezzaHack = PR_FALSE;
383
0
    if (type == CKM_SKIPJACK_CBC64) {
384
0
        if (symKey && (symKey->origin == PK11_OriginFortezzaHack)) {
385
0
            context->fortezzaHack = PR_TRUE;
386
0
        }
387
0
    }
388
389
    /* initialize the critical fields of the context */
390
0
    context->operation = operation;
391
    /* If we were given a symKey, keep our own reference to it so
392
     * that the key doesn't disappear in the middle of the operation
393
     * if the caller frees it. Public and Private keys are not reference
394
     * counted, so the caller just has to keep his copies around until
395
     * the operation completes */
396
0
    context->key = symKey ? PK11_ReferenceSymKey(symKey) : NULL;
397
0
    context->objectID = objectID;
398
0
    context->slot = PK11_ReferenceSlot(slot);
399
0
    context->session = pk11_GetNewSession(slot, &context->ownSession);
400
0
    context->pwArg = pwArg;
401
    /* get our session */
402
0
    context->savedData = NULL;
403
404
    /* save the parameters so that some digesting stuff can do multiple
405
     * begins on a single context */
406
0
    context->type = type;
407
0
    if (param) {
408
0
        if (param->len > 0) {
409
0
            context->param = SECITEM_DupItem(param);
410
0
        } else {
411
0
            context->param = (SECItem *)&pk11_null_params;
412
0
        }
413
0
    } else {
414
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
415
0
        context->param = NULL;
416
0
    }
417
0
    context->init = PR_FALSE;
418
0
    context->sessionLock = PZ_NewLock(nssILockPK11cxt);
419
0
    if ((context->param == NULL) || (context->sessionLock == NULL)) {
420
0
        PK11_DestroyContext(context, PR_TRUE);
421
0
        return NULL;
422
0
    }
423
424
0
    mech_info.mechanism = type;
425
0
    mech_info.pParameter = param->data;
426
0
    mech_info.ulParameterLen = param->len;
427
0
    rv = pk11_context_init(context, &mech_info);
428
429
0
    if (rv != SECSuccess) {
430
0
        PK11_DestroyContext(context, PR_TRUE);
431
0
        return NULL;
432
0
    }
433
0
    context->init = PR_TRUE;
434
0
    return context;
435
0
}
436
437
/*
438
 * put together the various PK11_Create_Context calls used by different
439
 * parts of libsec.
440
 */
441
PK11Context *
442
__PK11_CreateContextByRawKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
443
                             PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
444
                             SECItem *param, void *wincx)
445
0
{
446
0
    PK11SymKey *symKey = NULL;
447
0
    PK11Context *context = NULL;
448
449
    /* first get a slot */
450
0
    if (slot == NULL) {
451
0
        slot = PK11_GetBestSlot(type, wincx);
452
0
        if (slot == NULL) {
453
0
            PORT_SetError(SEC_ERROR_NO_MODULE);
454
0
            goto loser;
455
0
        }
456
0
    } else {
457
0
        PK11_ReferenceSlot(slot);
458
0
    }
459
460
    /* now import the key */
461
0
    symKey = PK11_ImportSymKey(slot, type, origin, operation, key, wincx);
462
0
    if (symKey == NULL)
463
0
        goto loser;
464
465
0
    context = PK11_CreateContextBySymKey(type, operation, symKey, param);
466
467
0
loser:
468
0
    if (symKey) {
469
0
        PK11_FreeSymKey(symKey);
470
0
    }
471
0
    if (slot) {
472
0
        PK11_FreeSlot(slot);
473
0
    }
474
475
0
    return context;
476
0
}
477
478
PK11Context *
479
PK11_CreateContextByRawKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
480
                           PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
481
                           SECItem *param, void *wincx)
482
0
{
483
0
    return __PK11_CreateContextByRawKey(slot, type, origin, operation,
484
0
                                        key, param, wincx);
485
0
}
486
487
/*
488
 * Create a context from a key. We really should make sure we aren't using
489
 * the same key in multiple sessions!
490
 */
491
PK11Context *
492
PK11_CreateContextBySymKey(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE operation,
493
                           PK11SymKey *symKey, const SECItem *param)
494
0
{
495
0
    PK11SymKey *newKey;
496
0
    PK11Context *context;
497
498
    /* if this slot doesn't support the mechanism, go to a slot that does */
499
0
    newKey = pk11_ForceSlot(symKey, type, operation);
500
0
    if (newKey == NULL) {
501
0
        PK11_ReferenceSymKey(symKey);
502
0
    } else {
503
0
        symKey = newKey;
504
0
    }
505
506
    /* Context keeps its reference to the symKey, so it's safe to
507
     * free our reference we we are through, even though we may have
508
     * created the key using pk11_ForceSlot. */
509
0
    context = pk11_CreateNewContextInSlot(type, symKey->slot, operation, symKey,
510
0
                                          symKey->objectID, param, symKey->cx);
511
0
    PK11_FreeSymKey(symKey);
512
0
    return context;
513
0
}
514
515
/* To support multipart public key operations (like hash/verify operations),
516
 * we need to create contexts with public keys. */
517
PK11Context *
518
PK11_CreateContextByPubKey(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE operation,
519
                           SECKEYPublicKey *pubKey, const SECItem *param,
520
                           void *pwArg)
521
0
{
522
0
    PK11SlotInfo *slot = pubKey->pkcs11Slot;
523
0
    SECItem nullparam = { 0, 0, 0 };
524
525
    /* if this slot doesn't support the mechanism, go to a slot that does */
526
    /* public keys have all their data in the public key data structure,
527
     * so there's no need to export the old key, just  import this one. The
528
     * import manages consistancy of the public key data structure */
529
0
    if (slot == NULL || !PK11_DoesMechanism(slot, type)) {
530
0
        CK_OBJECT_HANDLE objectID;
531
0
        slot = PK11_GetBestSlot(type, NULL);
532
0
        if (slot == NULL) {
533
0
            return NULL;
534
0
        }
535
0
        objectID = PK11_ImportPublicKey(slot, pubKey, PR_FALSE);
536
0
        PK11_FreeSlot(slot);
537
0
        if (objectID == CK_INVALID_HANDLE) {
538
0
            return NULL;
539
0
        }
540
0
    }
541
542
    /* unlike symkeys, we accept a NULL parameter. map a null parameter
543
     * to the empty parameter. This matches the semantics of
544
     * PK11_VerifyWithMechanism */
545
0
    return pk11_CreateNewContextInSlot(type, pubKey->pkcs11Slot, operation,
546
0
                                       NULL, pubKey->pkcs11ID,
547
0
                                       param ? param : &nullparam, pwArg);
548
0
}
549
550
/* To support multipart private key operations (like hash/sign operations),
551
 * we need to create contexts with private keys. */
552
PK11Context *
553
PK11_CreateContextByPrivKey(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE operation,
554
                            SECKEYPrivateKey *privKey, const SECItem *param)
555
0
{
556
0
    SECItem nullparam = { 0, 0, 0 };
557
    /* Private keys are generally not movable. If the token the
558
     * private key lives on can't do the operation, generally we are
559
     * stuck anyway. So no need to try to manipulate the key into
560
     * another token */
561
562
    /* if this slot doesn't support the mechanism, go to a slot that does */
563
    /* unlike symkeys, we accept a NULL parameter. map a null parameter
564
     * to the empty parameter. This matches the semantics of
565
     * PK11_SignWithMechanism */
566
0
    return pk11_CreateNewContextInSlot(type, privKey->pkcs11Slot, operation,
567
0
                                       NULL, privKey->pkcs11ID,
568
0
                                       param ? param : &nullparam,
569
0
                                       privKey->wincx);
570
0
}
571
572
/*
573
 * Digest contexts don't need keys, but the do need to find a slot.
574
 * Macing should use PK11_CreateContextBySymKey.
575
 */
576
PK11Context *
577
PK11_CreateDigestContext(SECOidTag hashAlg)
578
0
{
579
    /* digesting has to work without authentication to the slot */
580
0
    CK_MECHANISM_TYPE type;
581
0
    PK11SlotInfo *slot;
582
0
    PK11Context *context;
583
0
    SECItem param;
584
585
0
    type = PK11_AlgtagToMechanism(hashAlg);
586
0
    slot = PK11_GetBestSlot(type, NULL);
587
0
    if (slot == NULL) {
588
0
        PORT_SetError(SEC_ERROR_NO_MODULE);
589
0
        return NULL;
590
0
    }
591
592
    /* maybe should really be PK11_GenerateNewParam?? */
593
0
    param.data = NULL;
594
0
    param.len = 0;
595
0
    param.type = 0;
596
597
0
    context = pk11_CreateNewContextInSlot(type, slot, CKA_DIGEST, NULL,
598
0
                                          CK_INVALID_HANDLE, &param, NULL);
599
0
    PK11_FreeSlot(slot);
600
0
    return context;
601
0
}
602
603
/*
604
 * create a new context which is the clone of the state of old context.
605
 */
606
PK11Context *
607
PK11_CloneContext(PK11Context *old)
608
0
{
609
0
    PK11Context *newcx;
610
0
    PRBool needFree = PR_FALSE;
611
0
    SECStatus rv = SECSuccess;
612
0
    void *data;
613
0
    unsigned long len;
614
615
0
    newcx = pk11_CreateNewContextInSlot(old->type, old->slot, old->operation,
616
0
                                        old->key, old->objectID, old->param,
617
0
                                        old->pwArg);
618
0
    if (newcx == NULL)
619
0
        return NULL;
620
621
    /* now clone the save state. First we need to find the save state
622
     * of the old session. If the old context owns it's session,
623
     * the state needs to be saved, otherwise the state is in saveData. */
624
0
    if (old->ownSession) {
625
0
        PK11_EnterContextMonitor(old);
626
0
        data = pk11_saveContext(old, NULL, &len);
627
0
        PK11_ExitContextMonitor(old);
628
0
        needFree = PR_TRUE;
629
0
    } else {
630
0
        data = old->savedData;
631
0
        len = old->savedLength;
632
0
    }
633
634
0
    if (data == NULL) {
635
0
        PK11_DestroyContext(newcx, PR_TRUE);
636
0
        return NULL;
637
0
    }
638
639
    /* now copy that state into our new context. Again we have different
640
     * work if the new context owns it's own session. If it does, we
641
     * restore the state gathered above. If it doesn't, we copy the
642
     * saveData pointer... */
643
0
    if (newcx->ownSession) {
644
0
        PK11_EnterContextMonitor(newcx);
645
0
        rv = pk11_restoreContext(newcx, data, len);
646
0
        PK11_ExitContextMonitor(newcx);
647
0
    } else {
648
0
        PORT_Assert(newcx->savedData != NULL);
649
0
        if ((newcx->savedData == NULL) || (newcx->savedLength < len)) {
650
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
651
0
            rv = SECFailure;
652
0
        } else {
653
0
            PORT_Memcpy(newcx->savedData, data, len);
654
0
            newcx->savedLength = len;
655
0
        }
656
0
    }
657
658
0
    if (needFree)
659
0
        PORT_Free(data);
660
661
0
    if (rv != SECSuccess) {
662
0
        PK11_DestroyContext(newcx, PR_TRUE);
663
0
        return NULL;
664
0
    }
665
0
    return newcx;
666
0
}
667
668
/*
669
 * save the current context state into a variable. Required to make FORTEZZA
670
 * work.
671
 */
672
SECStatus
673
PK11_SaveContext(PK11Context *cx, unsigned char *save, int *len, int saveLength)
674
0
{
675
0
    unsigned char *data = NULL;
676
0
    CK_ULONG length = saveLength;
677
678
0
    if (cx->ownSession) {
679
0
        PK11_EnterContextMonitor(cx);
680
0
        data = pk11_saveContextHelper(cx, save, &length);
681
0
        PK11_ExitContextMonitor(cx);
682
0
        if (data)
683
0
            *len = length;
684
0
    } else if ((unsigned)saveLength >= cx->savedLength) {
685
0
        data = (unsigned char *)cx->savedData;
686
0
        if (cx->savedData) {
687
0
            PORT_Memcpy(save, cx->savedData, cx->savedLength);
688
0
        }
689
0
        *len = cx->savedLength;
690
0
    }
691
0
    if (data != NULL) {
692
0
        if (cx->ownSession) {
693
0
            PORT_ZFree(data, length);
694
0
        }
695
0
        return SECSuccess;
696
0
    } else {
697
0
        return SECFailure;
698
0
    }
699
0
}
700
701
/* same as above, but may allocate the return buffer. */
702
unsigned char *
703
PK11_SaveContextAlloc(PK11Context *cx,
704
                      unsigned char *preAllocBuf, unsigned int pabLen,
705
                      unsigned int *stateLen)
706
0
{
707
0
    unsigned char *stateBuf = NULL;
708
0
    unsigned long length = (unsigned long)pabLen;
709
710
0
    if (cx->ownSession) {
711
0
        PK11_EnterContextMonitor(cx);
712
0
        stateBuf = pk11_saveContextHelper(cx, preAllocBuf, &length);
713
0
        PK11_ExitContextMonitor(cx);
714
0
        *stateLen = (stateBuf != NULL) ? length : 0;
715
0
    } else {
716
0
        if (pabLen < cx->savedLength) {
717
0
            stateBuf = (unsigned char *)PORT_Alloc(cx->savedLength);
718
0
            if (!stateBuf) {
719
0
                return (unsigned char *)NULL;
720
0
            }
721
0
        } else {
722
0
            stateBuf = preAllocBuf;
723
0
        }
724
0
        if (cx->savedData) {
725
0
            PORT_Memcpy(stateBuf, cx->savedData, cx->savedLength);
726
0
        }
727
0
        *stateLen = cx->savedLength;
728
0
    }
729
0
    return stateBuf;
730
0
}
731
732
/*
733
 * restore the context state into a new running context. Also required for
734
 * FORTEZZA .
735
 */
736
SECStatus
737
PK11_RestoreContext(PK11Context *cx, unsigned char *save, int len)
738
0
{
739
0
    SECStatus rv = SECSuccess;
740
0
    if (cx->ownSession) {
741
0
        PK11_EnterContextMonitor(cx);
742
0
        pk11_Finalize(cx);
743
0
        rv = pk11_restoreContext(cx, save, len);
744
0
        PK11_ExitContextMonitor(cx);
745
0
    } else {
746
0
        PORT_Assert(cx->savedData != NULL);
747
0
        if ((cx->savedData == NULL) || (cx->savedLength < (unsigned)len)) {
748
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
749
0
            rv = SECFailure;
750
0
        } else {
751
0
            PORT_Memcpy(cx->savedData, save, len);
752
0
            cx->savedLength = len;
753
0
        }
754
0
    }
755
0
    return rv;
756
0
}
757
758
/*
759
 * This is  to get FIPS compliance until we can convert
760
 * libjar to use PK11_ hashing functions. It returns PR_FALSE
761
 * if we can't get a PK11 Context.
762
 */
763
PRBool
764
PK11_HashOK(SECOidTag algID)
765
0
{
766
0
    PK11Context *cx;
767
768
0
    cx = PK11_CreateDigestContext(algID);
769
0
    if (cx == NULL)
770
0
        return PR_FALSE;
771
0
    PK11_DestroyContext(cx, PR_TRUE);
772
0
    return PR_TRUE;
773
0
}
774
775
/*
776
 * start a new digesting or Mac'ing operation on this context
777
 */
778
SECStatus
779
PK11_DigestBegin(PK11Context *cx)
780
0
{
781
0
    CK_MECHANISM mech_info;
782
0
    SECStatus rv;
783
784
0
    if (cx->init == PR_TRUE) {
785
0
        return SECSuccess;
786
0
    }
787
788
    /*
789
     * make sure the old context is clear first
790
     */
791
0
    PK11_EnterContextMonitor(cx);
792
0
    pk11_Finalize(cx);
793
0
    PK11_ExitContextMonitor(cx);
794
795
0
    mech_info.mechanism = cx->type;
796
0
    mech_info.pParameter = cx->param->data;
797
0
    mech_info.ulParameterLen = cx->param->len;
798
0
    rv = pk11_context_init(cx, &mech_info);
799
800
0
    if (rv != SECSuccess) {
801
0
        return SECFailure;
802
0
    }
803
0
    cx->init = PR_TRUE;
804
0
    return SECSuccess;
805
0
}
806
807
SECStatus
808
PK11_HashBuf(SECOidTag hashAlg, unsigned char *out, const unsigned char *in,
809
             PRInt32 len)
810
0
{
811
0
    PK11Context *context;
812
0
    unsigned int max_length;
813
0
    unsigned int out_length;
814
0
    SECStatus rv;
815
816
    /* len will be passed to PK11_DigestOp as unsigned. */
817
0
    if (len < 0) {
818
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
819
0
        return SECFailure;
820
0
    }
821
822
0
    context = PK11_CreateDigestContext(hashAlg);
823
0
    if (context == NULL)
824
0
        return SECFailure;
825
826
0
    rv = PK11_DigestBegin(context);
827
0
    if (rv != SECSuccess) {
828
0
        PK11_DestroyContext(context, PR_TRUE);
829
0
        return rv;
830
0
    }
831
832
0
    rv = PK11_DigestOp(context, in, len);
833
0
    if (rv != SECSuccess) {
834
0
        PK11_DestroyContext(context, PR_TRUE);
835
0
        return rv;
836
0
    }
837
838
    /* XXX This really should have been an argument to this function! */
839
0
    max_length = HASH_ResultLenByOidTag(hashAlg);
840
0
    PORT_Assert(max_length);
841
0
    if (!max_length)
842
0
        max_length = HASH_LENGTH_MAX;
843
844
0
    rv = PK11_DigestFinal(context, out, &out_length, max_length);
845
0
    PK11_DestroyContext(context, PR_TRUE);
846
0
    return rv;
847
0
}
848
849
/*
850
 * execute a bulk encryption operation
851
 */
852
SECStatus
853
PK11_CipherOp(PK11Context *context, unsigned char *out, int *outlen,
854
              int maxout, const unsigned char *in, int inlen)
855
0
{
856
0
    CK_RV crv = CKR_OK;
857
0
    CK_ULONG length = maxout;
858
0
    CK_ULONG offset = 0;
859
0
    SECStatus rv = SECSuccess;
860
0
    unsigned char *saveOut = out;
861
0
    unsigned char *allocOut = NULL;
862
863
    /* if we ran out of session, we need to restore our previously stored
864
     * state.
865
     */
866
0
    PK11_EnterContextMonitor(context);
867
0
    if (!context->ownSession) {
868
0
        rv = pk11_restoreContext(context, context->savedData,
869
0
                                 context->savedLength);
870
0
        if (rv != SECSuccess) {
871
0
            PK11_ExitContextMonitor(context);
872
0
            return rv;
873
0
        }
874
0
    }
875
876
    /*
877
     * The fortezza hack is to send 8 extra bytes on the first encrypted and
878
     * lose them on the first decrypt.
879
     */
880
0
    if (context->fortezzaHack) {
881
0
        unsigned char random[8];
882
0
        if (context->operation == CKA_ENCRYPT) {
883
0
            PK11_ExitContextMonitor(context);
884
0
            rv = PK11_GenerateRandom(random, sizeof(random));
885
0
            PK11_EnterContextMonitor(context);
886
887
            /* since we are offseting the output, we can't encrypt back into
888
             * the same buffer... allocate a temporary buffer just for this
889
             * call. */
890
0
            allocOut = out = (unsigned char *)PORT_Alloc(maxout);
891
0
            if (out == NULL) {
892
0
                PK11_ExitContextMonitor(context);
893
0
                return SECFailure;
894
0
            }
895
0
            crv = PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session, random, sizeof(random), out, &length);
896
897
0
            out += length;
898
0
            maxout -= length;
899
0
            offset = length;
900
0
        } else if (context->operation == CKA_DECRYPT) {
901
0
            length = sizeof(random);
902
0
            crv = PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session, (CK_BYTE_PTR)in, sizeof(random), random, &length);
903
0
            inlen -= length;
904
0
            in += length;
905
0
            context->fortezzaHack = PR_FALSE;
906
0
        }
907
0
    }
908
909
0
    switch (context->operation) {
910
0
        case CKA_ENCRYPT:
911
0
            length = maxout;
912
0
            crv = PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session, (CK_BYTE_PTR)in, inlen, out, &length);
913
0
            length += offset;
914
0
            break;
915
0
        case CKA_DECRYPT:
916
0
            length = maxout;
917
0
            crv = PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session, (CK_BYTE_PTR)in, inlen, out, &length);
918
0
            break;
919
0
        default:
920
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
921
0
            break;
922
0
    }
923
924
0
    if (crv != CKR_OK) {
925
0
        PORT_SetError(PK11_MapError(crv));
926
0
        *outlen = 0;
927
0
        rv = SECFailure;
928
0
    } else {
929
0
        *outlen = length;
930
0
    }
931
932
0
    if (context->fortezzaHack) {
933
0
        if (context->operation == CKA_ENCRYPT) {
934
0
            PORT_Assert(allocOut);
935
0
            PORT_Memcpy(saveOut, allocOut, length);
936
0
            PORT_Free(allocOut);
937
0
        }
938
0
        context->fortezzaHack = PR_FALSE;
939
0
    }
940
941
    /*
942
     * handle session starvation case.. use our last session to multiplex
943
     */
944
0
    if (!context->ownSession) {
945
0
        context->savedData = pk11_saveContext(context, context->savedData,
946
0
                                              &context->savedLength);
947
0
        if (context->savedData == NULL)
948
0
            rv = SECFailure;
949
950
        /* clear out out session for others to use */
951
0
        pk11_Finalize(context);
952
0
    }
953
0
    PK11_ExitContextMonitor(context);
954
0
    return rv;
955
0
}
956
957
/*
958
 * Simulate the IV generation that normally would happen in the token.
959
 *
960
 * This is a modifed copy of what is in freebl/gcm.c. We can't use the
961
 * version in freebl because of layering, since freebl is inside the token
962
 * boundary. These issues are traditionally handled by moving them to util,
963
 * but we also have two different Random functions we have two switch between.
964
 * Since this is primarily here for tokens that don't support the PKCS #11
965
 * Message Interface, it's OK if they diverge a bit. Slight semantic
966
 * differences from the freebl/gcm.c version shouldn't be much more than the
967
 * sematic differences between freebl and other tokens which do implement the
968
 * Message Interface. */
969
static SECStatus
970
pk11_GenerateIV(PK11Context *context, CK_GENERATOR_FUNCTION ivgen,
971
                int fixedBits, unsigned char *iv, int ivLen)
972
0
{
973
0
    unsigned int i;
974
0
    unsigned int flexBits;
975
0
    unsigned int ivOffset;
976
0
    unsigned int ivNewCount;
977
0
    unsigned char ivMask;
978
0
    unsigned char ivSave;
979
0
    SECStatus rv;
980
981
0
    if (context->ivCounter != 0) {
982
        /* If we've already generated a message, make sure all subsequent
983
         * messages are using the same generator */
984
0
        if ((context->ivGen != ivgen) ||
985
0
            (context->ivFixedBits != fixedBits) ||
986
0
            (context->ivLen != ivLen)) {
987
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
988
0
            return SECFailure;
989
0
        }
990
0
    } else {
991
        /* remember these values */
992
0
        context->ivGen = ivgen;
993
0
        context->ivFixedBits = fixedBits;
994
0
        context->ivLen = ivLen;
995
        /* now calculate how may bits of IV we have to supply */
996
0
        flexBits = ivLen * PR_BITS_PER_BYTE;
997
        /* first make sure we aren't going to overflow */
998
0
        if (flexBits < fixedBits) {
999
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
1000
0
            return SECFailure;
1001
0
        }
1002
0
        flexBits -= fixedBits;
1003
        /* if we are generating a random number reduce the acceptable bits to
1004
         * avoid birthday attacks */
1005
0
        if (ivgen == CKG_GENERATE_RANDOM) {
1006
0
            if (flexBits <= GCMIV_RANDOM_BIRTHDAY_BITS) {
1007
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1008
0
                return SECFailure;
1009
0
            }
1010
            /* see freebl/blapit.h for how GCMIV_RANDOM_BIRTHDAY_BITS is
1011
             * calculated. */
1012
0
            flexBits -= GCMIV_RANDOM_BIRTHDAY_BITS;
1013
0
            flexBits = flexBits >> 1;
1014
0
        }
1015
0
        if (flexBits == 0) {
1016
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
1017
0
            return SECFailure;
1018
0
        }
1019
        /* Turn those bits into the number of IV's we can safely return */
1020
0
        if (flexBits >= sizeof(context->ivMaxCount) * PR_BITS_PER_BYTE) {
1021
0
            context->ivMaxCount = PR_UINT64(0xffffffffffffffff);
1022
0
        } else {
1023
0
            context->ivMaxCount = (PR_UINT64(1) << flexBits);
1024
0
        }
1025
0
    }
1026
1027
    /* no generate, accept the IV from the source */
1028
0
    if (ivgen == CKG_NO_GENERATE) {
1029
0
        context->ivCounter = 1;
1030
0
        return SECSuccess;
1031
0
    }
1032
1033
    /* make sure we haven't exceeded the number of IVs we can return
1034
     * for this key, generator, and IV size */
1035
0
    if (context->ivCounter >= context->ivMaxCount) {
1036
        /* use a unique error from just bad user input */
1037
0
        PORT_SetError(SEC_ERROR_EXTRA_INPUT);
1038
0
        return SECFailure;
1039
0
    }
1040
1041
    /* build to mask to handle the first byte of the IV */
1042
0
    ivOffset = fixedBits / PR_BITS_PER_BYTE;
1043
0
    ivMask = 0xff >> ((PR_BITS_PER_BYTE - (fixedBits & 7)) & 7);
1044
0
    ivNewCount = ivLen - ivOffset;
1045
1046
    /* finally generate the IV */
1047
0
    switch (ivgen) {
1048
0
        case CKG_GENERATE: /* default to counter */
1049
0
        case CKG_GENERATE_COUNTER:
1050
0
            iv[ivOffset] = (iv[ivOffset] & ~ivMask) |
1051
0
                           (PORT_GET_BYTE_BE(context->ivCounter, 0, ivNewCount) & ivMask);
1052
0
            for (i = 1; i < ivNewCount; i++) {
1053
0
                iv[ivOffset + i] =
1054
0
                    PORT_GET_BYTE_BE(context->ivCounter, i, ivNewCount);
1055
0
            }
1056
0
            break;
1057
0
        case CKG_GENERATE_COUNTER_XOR:
1058
0
            iv[ivOffset] ^=
1059
0
                (PORT_GET_BYTE_BE(context->ivCounter, 0, ivNewCount) & ivMask);
1060
0
            for (i = 1; i < ivNewCount; i++) {
1061
0
                iv[ivOffset + i] ^=
1062
0
                    PORT_GET_BYTE_BE(context->ivCounter, i, ivNewCount);
1063
0
            }
1064
0
            break;
1065
0
        case CKG_GENERATE_RANDOM:
1066
0
            ivSave = iv[ivOffset] & ~ivMask;
1067
0
            rv = PK11_GenerateRandom(iv + ivOffset, ivNewCount);
1068
0
            iv[ivOffset] = ivSave | (iv[ivOffset] & ivMask);
1069
0
            if (rv != SECSuccess) {
1070
0
                return rv;
1071
0
            }
1072
0
            break;
1073
0
    }
1074
0
    context->ivCounter++;
1075
0
    return SECSuccess;
1076
0
}
1077
1078
/*
1079
 * PKCS #11 v2.40 did not have a message interface. If our module can't
1080
 * do the message interface use the old method of doing AEAD */
1081
static SECStatus
1082
pk11_AEADSimulateOp(PK11Context *context, void *params, int paramslen,
1083
                    const unsigned char *aad, int aadlen,
1084
                    unsigned char *out, int *outlen,
1085
                    int maxout, const unsigned char *in, int inlen)
1086
0
{
1087
0
    unsigned int length = maxout;
1088
0
    SECStatus rv = SECSuccess;
1089
0
    unsigned char *saveOut = out;
1090
0
    unsigned char *allocOut = NULL;
1091
1092
    /*
1093
     * first we need to convert the single shot (v2.40) parameters into
1094
     * the message version of the parameters. This usually involves
1095
     * copying the Nonce or IV, setting the AAD from our parameter list
1096
     * and handling the tag differences */
1097
0
    CK_GCM_PARAMS_V3 gcm;
1098
0
    CK_GCM_MESSAGE_PARAMS *gcm_message;
1099
0
    CK_CCM_PARAMS ccm;
1100
0
    CK_CCM_MESSAGE_PARAMS *ccm_message;
1101
0
    CK_SALSA20_CHACHA20_POLY1305_PARAMS chacha_poly;
1102
0
    CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS *chacha_poly_message;
1103
0
    CK_NSS_AEAD_PARAMS nss_chacha_poly;
1104
0
    CK_MECHANISM_TYPE mechanism = context->simulate_mechanism;
1105
0
    SECItem sim_params = { 0, NULL, 0 };
1106
0
    unsigned char *tag = NULL;
1107
0
    unsigned int taglen;
1108
0
    PRBool encrypt;
1109
1110
0
    *outlen = 0;
1111
    /* figure out if we are encrypting or decrypting, as tags are
1112
     * handled differently in both */
1113
0
    switch (context->operation) {
1114
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
1115
0
            encrypt = PR_TRUE;
1116
0
            break;
1117
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
1118
0
            encrypt = PR_FALSE;
1119
0
            break;
1120
0
        default:
1121
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
1122
0
            return SECFailure;
1123
0
    }
1124
1125
0
    switch (mechanism) {
1126
0
        case CKM_CHACHA20_POLY1305:
1127
0
        case CKM_SALSA20_POLY1305:
1128
0
            if (paramslen != sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS)) {
1129
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1130
0
                return SECFailure;
1131
0
            }
1132
0
            chacha_poly_message =
1133
0
                (CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS *)params;
1134
0
            chacha_poly.pNonce = chacha_poly_message->pNonce;
1135
0
            chacha_poly.ulNonceLen = chacha_poly_message->ulNonceLen;
1136
0
            chacha_poly.pAAD = (CK_BYTE_PTR)aad;
1137
0
            chacha_poly.ulAADLen = aadlen;
1138
0
            tag = chacha_poly_message->pTag;
1139
0
            taglen = 16;
1140
0
            sim_params.data = (unsigned char *)&chacha_poly;
1141
0
            sim_params.len = sizeof(chacha_poly);
1142
            /* SALSA20_POLY1305 and CHACHA20_POLY1305 do not generate the iv
1143
             * internally, don't simulate it either */
1144
0
            break;
1145
0
        case CKM_NSS_CHACHA20_POLY1305:
1146
0
            if (paramslen != sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS)) {
1147
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1148
0
                return SECFailure;
1149
0
            }
1150
0
            chacha_poly_message =
1151
0
                (CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS *)params;
1152
0
            tag = chacha_poly_message->pTag;
1153
0
            taglen = 16;
1154
0
            nss_chacha_poly.pNonce = chacha_poly_message->pNonce;
1155
0
            nss_chacha_poly.ulNonceLen = chacha_poly_message->ulNonceLen;
1156
0
            nss_chacha_poly.pAAD = (CK_BYTE_PTR)aad;
1157
0
            nss_chacha_poly.ulAADLen = aadlen;
1158
0
            nss_chacha_poly.ulTagLen = taglen;
1159
0
            sim_params.data = (unsigned char *)&nss_chacha_poly;
1160
0
            sim_params.len = sizeof(nss_chacha_poly);
1161
            /* CKM_NSS_CHACHA20_POLY1305 does not generate the iv
1162
             * internally, don't simulate it either */
1163
0
            break;
1164
0
        case CKM_AES_CCM:
1165
0
            if (paramslen != sizeof(CK_CCM_MESSAGE_PARAMS)) {
1166
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1167
0
                return SECFailure;
1168
0
            }
1169
0
            ccm_message = (CK_CCM_MESSAGE_PARAMS *)params;
1170
0
            ccm.ulDataLen = ccm_message->ulDataLen;
1171
0
            ccm.pNonce = ccm_message->pNonce;
1172
0
            ccm.ulNonceLen = ccm_message->ulNonceLen;
1173
0
            ccm.pAAD = (CK_BYTE_PTR)aad;
1174
0
            ccm.ulAADLen = aadlen;
1175
0
            ccm.ulMACLen = ccm_message->ulMACLen;
1176
0
            tag = ccm_message->pMAC;
1177
0
            taglen = ccm_message->ulMACLen;
1178
0
            sim_params.data = (unsigned char *)&ccm;
1179
0
            sim_params.len = sizeof(ccm);
1180
0
            if (encrypt) {
1181
                /* simulate generating the IV */
1182
0
                rv = pk11_GenerateIV(context, ccm_message->nonceGenerator,
1183
0
                                     ccm_message->ulNonceFixedBits,
1184
0
                                     ccm_message->pNonce,
1185
0
                                     ccm_message->ulNonceLen);
1186
0
                if (rv != SECSuccess) {
1187
0
                    return rv;
1188
0
                }
1189
0
            }
1190
0
            break;
1191
0
        case CKM_AES_GCM:
1192
0
            if (paramslen != sizeof(CK_GCM_MESSAGE_PARAMS)) {
1193
0
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
1194
0
                return SECFailure;
1195
0
            }
1196
0
            gcm_message = (CK_GCM_MESSAGE_PARAMS *)params;
1197
0
            gcm.pIv = gcm_message->pIv;
1198
0
            gcm.ulIvLen = gcm_message->ulIvLen;
1199
0
            gcm.ulIvBits = gcm.ulIvLen * PR_BITS_PER_BYTE;
1200
0
            gcm.pAAD = (CK_BYTE_PTR)aad;
1201
0
            gcm.ulAADLen = aadlen;
1202
0
            gcm.ulTagBits = gcm_message->ulTagBits;
1203
0
            tag = gcm_message->pTag;
1204
0
            taglen = (gcm_message->ulTagBits + (PR_BITS_PER_BYTE - 1)) / PR_BITS_PER_BYTE;
1205
0
            sim_params.data = (unsigned char *)&gcm;
1206
0
            sim_params.len = sizeof(gcm);
1207
0
            if (encrypt) {
1208
                /* simulate generating the IV */
1209
0
                rv = pk11_GenerateIV(context, gcm_message->ivGenerator,
1210
0
                                     gcm_message->ulIvFixedBits,
1211
0
                                     gcm_message->pIv, gcm_message->ulIvLen);
1212
0
                if (rv != SECSuccess) {
1213
0
                    return rv;
1214
0
                }
1215
0
            }
1216
0
            break;
1217
0
        default:
1218
0
            PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1219
0
            return SECFailure;
1220
0
    }
1221
    /* now handle the tag. The message interface separates the tag from
1222
     * the data, while the single shot gets and puts the tag at the end of
1223
     * the encrypted data. */
1224
0
    if (!encrypt) {
1225
        /* In the decrypt case, if the tag is already at the end of the
1226
         * input buffer we are golden, otherwise we'll need a new input
1227
         * buffer and copy the tag at the end of it */
1228
0
        if (tag != in + inlen) {
1229
0
            allocOut = PORT_Alloc(inlen + taglen);
1230
0
            if (allocOut == NULL) {
1231
0
                return SECFailure;
1232
0
            }
1233
0
            PORT_Memcpy(allocOut, in, inlen);
1234
0
            PORT_Memcpy(allocOut + inlen, tag, taglen);
1235
0
            in = allocOut;
1236
0
        }
1237
0
        inlen = inlen + taglen;
1238
0
    } else {
1239
        /* if we end up allocating, we don't want to overrun this buffer,
1240
         * so we fail early here */
1241
0
        if (maxout < inlen) {
1242
0
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
1243
0
            return SECFailure;
1244
0
        }
1245
        /* in the encrypt case, we are fine if maxout is big enough to hold
1246
         * the tag. We'll copy the tag after the operation */
1247
0
        if (maxout < inlen + taglen) {
1248
0
            allocOut = PORT_Alloc(inlen + taglen);
1249
0
            if (allocOut == NULL) {
1250
0
                return SECFailure;
1251
0
            }
1252
0
            out = allocOut;
1253
0
            length = maxout = inlen + taglen;
1254
0
        }
1255
0
    }
1256
    /* now do the operation */
1257
0
    if (encrypt) {
1258
0
        rv = PK11_Encrypt(context->key, mechanism, &sim_params, out, &length,
1259
0
                          maxout, in, inlen);
1260
0
    } else {
1261
0
        rv = PK11_Decrypt(context->key, mechanism, &sim_params, out, &length,
1262
0
                          maxout, in, inlen);
1263
0
    }
1264
0
    if (rv != SECSuccess) {
1265
        /* If the mechanism was CKM_AES_GCM, the module may have been
1266
         * following the same error as old versions of NSS. Retry with
1267
         * the CK_NSS_GCM_PARAMS */
1268
0
        if ((mechanism == CKM_AES_GCM) &&
1269
0
            (PORT_GetError() == SEC_ERROR_BAD_DATA)) {
1270
0
            CK_NSS_GCM_PARAMS gcm_nss;
1271
0
            gcm_message = (CK_GCM_MESSAGE_PARAMS *)params;
1272
0
            gcm_nss.pIv = gcm_message->pIv;
1273
0
            gcm_nss.ulIvLen = gcm_message->ulIvLen;
1274
0
            gcm_nss.pAAD = (CK_BYTE_PTR)aad;
1275
0
            gcm_nss.ulAADLen = aadlen;
1276
0
            gcm_nss.ulTagBits = gcm_message->ulTagBits;
1277
0
            sim_params.data = (unsigned char *)&gcm_nss;
1278
0
            sim_params.len = sizeof(gcm_nss);
1279
0
            if (encrypt) {
1280
0
                rv = PK11_Encrypt(context->key, mechanism, &sim_params, out,
1281
0
                                  &length, maxout, in, inlen);
1282
0
            } else {
1283
0
                rv = PK11_Decrypt(context->key, mechanism, &sim_params, out,
1284
0
                                  &length, maxout, in, inlen);
1285
0
            }
1286
0
            if (rv != SECSuccess) {
1287
0
                goto fail;
1288
0
            }
1289
0
        } else {
1290
0
            goto fail;
1291
0
        }
1292
0
    }
1293
1294
    /* on encrypt, separate the output buffer from the tag */
1295
0
    if (encrypt) {
1296
0
        if ((length < taglen) || (length > inlen + taglen)) {
1297
            /* PKCS #11 module should not return a length smaller than
1298
             * taglen, or bigger than inlen+taglen */
1299
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1300
0
            rv = SECFailure;
1301
0
            goto fail;
1302
0
        }
1303
0
        length = length - taglen;
1304
0
        if (allocOut) {
1305
            /*
1306
             * If we used a temporary buffer, copy it out to the original
1307
             * buffer.
1308
             */
1309
0
            PORT_Memcpy(saveOut, allocOut, length);
1310
0
        }
1311
        /* if the tag isn't in the right place, copy it out */
1312
0
        if (tag != out + length) {
1313
0
            PORT_Memcpy(tag, out + length, taglen);
1314
0
        }
1315
0
    }
1316
0
    *outlen = length;
1317
0
    rv = SECSuccess;
1318
0
fail:
1319
0
    if (allocOut) {
1320
0
        PORT_Free(allocOut);
1321
0
    }
1322
0
    return rv;
1323
0
}
1324
1325
/*
1326
 * Do an AEAD operation. This function optionally returns
1327
 * and IV on Encrypt for all mechanism. NSS knows which mechanisms
1328
 * generate IV's in the token and which don't. This allows the
1329
 * applications to make a single call without special handling for
1330
 * each AEAD mechanism (the special handling is all contained here.
1331
 */
1332
SECStatus
1333
PK11_AEADOp(PK11Context *context, CK_GENERATOR_FUNCTION ivgen,
1334
            int fixedbits, unsigned char *iv, int ivlen,
1335
            const unsigned char *aad, int aadlen,
1336
            unsigned char *out, int *outlen,
1337
            int maxout, unsigned char *tag, int taglen,
1338
            const unsigned char *in, int inlen)
1339
0
{
1340
0
    CK_GCM_MESSAGE_PARAMS gcm_message;
1341
0
    CK_CCM_MESSAGE_PARAMS ccm_message;
1342
0
    CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS chacha_poly_message;
1343
0
    void *params;
1344
0
    int paramslen;
1345
0
    SECStatus rv;
1346
1347
0
    switch (context->simulate_mechanism) {
1348
0
        case CKM_CHACHA20_POLY1305:
1349
0
        case CKM_SALSA20_POLY1305:
1350
0
        case CKM_NSS_CHACHA20_POLY1305:
1351
0
            chacha_poly_message.pNonce = iv;
1352
0
            chacha_poly_message.ulNonceLen = ivlen;
1353
0
            chacha_poly_message.pTag = tag;
1354
0
            params = &chacha_poly_message;
1355
0
            paramslen = sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS);
1356
            /* SALSA20_POLY1305 and CHACHA20_POLY1305 do not generate the iv
1357
             * internally, Do it here. */
1358
0
            if (context->operation == (CKA_NSS_MESSAGE | CKA_ENCRYPT)) {
1359
                /* simulate generating the IV */
1360
0
                rv = pk11_GenerateIV(context, ivgen, fixedbits, iv, ivlen);
1361
0
                if (rv != SECSuccess) {
1362
0
                    return rv;
1363
0
                }
1364
0
            }
1365
0
            break;
1366
0
        case CKM_AES_GCM:
1367
0
            gcm_message.pIv = iv;
1368
0
            gcm_message.ulIvLen = ivlen;
1369
0
            gcm_message.ivGenerator = ivgen;
1370
0
            gcm_message.ulIvFixedBits = fixedbits;
1371
0
            gcm_message.pTag = tag;
1372
0
            gcm_message.ulTagBits = taglen * 8;
1373
0
            params = &gcm_message;
1374
0
            paramslen = sizeof(CK_GCM_MESSAGE_PARAMS);
1375
            /* GCM generates IV internally */
1376
0
            break;
1377
0
        case CKM_AES_CCM:
1378
0
            ccm_message.ulDataLen = inlen;
1379
0
            ccm_message.pNonce = iv;
1380
0
            ccm_message.ulNonceLen = ivlen;
1381
0
            ccm_message.nonceGenerator = ivgen;
1382
0
            ccm_message.ulNonceFixedBits = fixedbits;
1383
0
            ccm_message.pMAC = tag;
1384
0
            ccm_message.ulMACLen = taglen;
1385
0
            params = &ccm_message;
1386
0
            paramslen = sizeof(CK_GCM_MESSAGE_PARAMS);
1387
            /* CCM generates IV internally */
1388
0
            break;
1389
1390
0
        default:
1391
0
            PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1392
0
            return SECFailure;
1393
0
    }
1394
0
    return PK11_AEADRawOp(context, params, paramslen, aad, aadlen, out, outlen,
1395
0
                          maxout, in, inlen);
1396
0
}
1397
1398
/* Do and AED operation. The application builds the params on it's own
1399
 * and passes them in. This allows applications direct access to the params
1400
 * so they can use mechanisms not yet understood by, NSS, or get semantics
1401
 * not suppied by PK11_AEAD. */
1402
SECStatus
1403
PK11_AEADRawOp(PK11Context *context, void *params, int paramslen,
1404
               const unsigned char *aad, int aadlen,
1405
               unsigned char *out, int *outlen,
1406
               int maxout, const unsigned char *in, int inlen)
1407
0
{
1408
0
    CK_RV crv = CKR_OK;
1409
0
    CK_ULONG length = maxout;
1410
0
    SECStatus rv = SECSuccess;
1411
1412
0
    PORT_Assert(outlen != NULL);
1413
0
    *outlen = 0;
1414
0
    if (((context->operation) & CKA_NSS_MESSAGE_MASK) != CKA_NSS_MESSAGE) {
1415
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1416
0
        return SECFailure;
1417
0
    }
1418
1419
    /*
1420
     * The PKCS 11 module does not support the message interface, fall
1421
     * back to using single shot operation */
1422
0
    if (context->simulate_message) {
1423
0
        return pk11_AEADSimulateOp(context, params, paramslen, aad, aadlen,
1424
0
                                   out, outlen, maxout, in, inlen);
1425
0
    }
1426
1427
    /* if we ran out of session, we need to restore our previously stored
1428
     * state.
1429
     */
1430
0
    PK11_EnterContextMonitor(context);
1431
0
    if (!context->ownSession) {
1432
0
        rv = pk11_restoreContext(context, context->savedData,
1433
0
                                 context->savedLength);
1434
0
        if (rv != SECSuccess) {
1435
0
            PK11_ExitContextMonitor(context);
1436
0
            return rv;
1437
0
        }
1438
0
    }
1439
1440
0
    switch (context->operation) {
1441
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
1442
0
            length = maxout;
1443
0
            crv = PK11_GETTAB(context->slot)->C_EncryptMessage(context->session, params, paramslen, (CK_BYTE_PTR)aad, aadlen, (CK_BYTE_PTR)in, inlen, out, &length);
1444
0
            break;
1445
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
1446
0
            length = maxout;
1447
0
            crv = PK11_GETTAB(context->slot)->C_DecryptMessage(context->session, params, paramslen, (CK_BYTE_PTR)aad, aadlen, (CK_BYTE_PTR)in, inlen, out, &length);
1448
0
            break;
1449
0
        case CKA_NSS_MESSAGE | CKA_SIGN:
1450
0
            length = maxout;
1451
0
            crv = PK11_GETTAB(context->slot)->C_SignMessage(context->session, params, paramslen, (CK_BYTE_PTR)in, inlen, out, &length);
1452
0
            break;
1453
0
        case CKA_NSS_MESSAGE | CKA_VERIFY:
1454
0
            length = maxout; /* sig length */
1455
0
            crv = PK11_GETTAB(context->slot)->C_VerifyMessage(context->session, params, paramslen, (CK_BYTE_PTR)in, inlen, out /* sig */, length);
1456
0
            break;
1457
0
        default:
1458
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
1459
0
            break;
1460
0
    }
1461
1462
0
    if (crv != CKR_OK) {
1463
0
        PORT_SetError(PK11_MapError(crv));
1464
0
        rv = SECFailure;
1465
0
    } else {
1466
0
        *outlen = length;
1467
0
    }
1468
1469
    /*
1470
     * handle session starvation case.. use our last session to multiplex
1471
     */
1472
0
    if (!context->ownSession) {
1473
0
        context->savedData = pk11_saveContext(context, context->savedData,
1474
0
                                              &context->savedLength);
1475
0
        if (context->savedData == NULL)
1476
0
            rv = SECFailure;
1477
1478
        /* clear out out session for others to use */
1479
0
        pk11_Finalize(context);
1480
0
    }
1481
0
    PK11_ExitContextMonitor(context);
1482
0
    return rv;
1483
0
}
1484
1485
/*
1486
 * execute a digest/signature operation
1487
 */
1488
SECStatus
1489
PK11_DigestOp(PK11Context *context, const unsigned char *in, unsigned inLen)
1490
0
{
1491
0
    CK_RV crv = CKR_OK;
1492
0
    SECStatus rv = SECSuccess;
1493
1494
0
    if (inLen == 0) {
1495
0
        return SECSuccess;
1496
0
    }
1497
0
    if (!in) {
1498
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1499
0
        return SECFailure;
1500
0
    }
1501
1502
    /* if we ran out of session, we need to restore our previously stored
1503
     * state.
1504
     */
1505
0
    context->init = PR_FALSE;
1506
0
    PK11_EnterContextMonitor(context);
1507
0
    if (!context->ownSession) {
1508
0
        rv = pk11_restoreContext(context, context->savedData,
1509
0
                                 context->savedLength);
1510
0
        if (rv != SECSuccess) {
1511
0
            PK11_ExitContextMonitor(context);
1512
0
            return rv;
1513
0
        }
1514
0
    }
1515
1516
0
    switch (context->operation) {
1517
        /* also for MAC'ing */
1518
0
        case CKA_SIGN:
1519
0
            crv = PK11_GETTAB(context->slot)->C_SignUpdate(context->session, (unsigned char *)in, inLen);
1520
0
            break;
1521
0
        case CKA_VERIFY:
1522
0
            crv = PK11_GETTAB(context->slot)->C_VerifyUpdate(context->session, (unsigned char *)in, inLen);
1523
0
            break;
1524
0
        case CKA_DIGEST:
1525
0
            crv = PK11_GETTAB(context->slot)->C_DigestUpdate(context->session, (unsigned char *)in, inLen);
1526
0
            break;
1527
0
        default:
1528
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
1529
0
            break;
1530
0
    }
1531
1532
0
    if (crv != CKR_OK) {
1533
0
        PORT_SetError(PK11_MapError(crv));
1534
0
        rv = SECFailure;
1535
0
    }
1536
1537
    /*
1538
     * handle session starvation case.. use our last session to multiplex
1539
     */
1540
0
    if (!context->ownSession) {
1541
0
        context->savedData = pk11_saveContext(context, context->savedData,
1542
0
                                              &context->savedLength);
1543
0
        if (context->savedData == NULL)
1544
0
            rv = SECFailure;
1545
1546
        /* clear out out session for others to use */
1547
0
        pk11_Finalize(context);
1548
0
    }
1549
0
    PK11_ExitContextMonitor(context);
1550
0
    return rv;
1551
0
}
1552
1553
/*
1554
 * Digest a key if possible./
1555
 */
1556
SECStatus
1557
PK11_DigestKey(PK11Context *context, PK11SymKey *key)
1558
0
{
1559
0
    CK_RV crv = CKR_OK;
1560
0
    SECStatus rv = SECSuccess;
1561
0
    PK11SymKey *newKey = NULL;
1562
1563
0
    if (!context || !key) {
1564
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1565
0
        return SECFailure;
1566
0
    }
1567
1568
    /* if we ran out of session, we need to restore our previously stored
1569
     * state.
1570
     */
1571
0
    if (context->slot != key->slot) {
1572
0
        newKey = pk11_CopyToSlot(context->slot, CKM_SSL3_SHA1_MAC, CKA_SIGN, key);
1573
0
    } else {
1574
0
        newKey = PK11_ReferenceSymKey(key);
1575
0
    }
1576
1577
0
    context->init = PR_FALSE;
1578
0
    PK11_EnterContextMonitor(context);
1579
0
    if (!context->ownSession) {
1580
0
        rv = pk11_restoreContext(context, context->savedData,
1581
0
                                 context->savedLength);
1582
0
        if (rv != SECSuccess) {
1583
0
            PK11_ExitContextMonitor(context);
1584
0
            PK11_FreeSymKey(newKey);
1585
0
            return rv;
1586
0
        }
1587
0
    }
1588
1589
0
    if (newKey == NULL) {
1590
0
        crv = CKR_KEY_TYPE_INCONSISTENT;
1591
0
        if (key->data.data) {
1592
0
            crv = PK11_GETTAB(context->slot)->C_DigestUpdate(context->session, key->data.data, key->data.len);
1593
0
        }
1594
0
    } else {
1595
0
        crv = PK11_GETTAB(context->slot)->C_DigestKey(context->session, newKey->objectID);
1596
0
    }
1597
1598
0
    if (crv != CKR_OK) {
1599
0
        PORT_SetError(PK11_MapError(crv));
1600
0
        rv = SECFailure;
1601
0
    }
1602
1603
    /*
1604
     * handle session starvation case.. use our last session to multiplex
1605
     */
1606
0
    if (!context->ownSession) {
1607
0
        context->savedData = pk11_saveContext(context, context->savedData,
1608
0
                                              &context->savedLength);
1609
0
        if (context->savedData == NULL)
1610
0
            rv = SECFailure;
1611
1612
        /* clear out out session for others to use */
1613
0
        pk11_Finalize(context);
1614
0
    }
1615
0
    PK11_ExitContextMonitor(context);
1616
0
    if (newKey)
1617
0
        PK11_FreeSymKey(newKey);
1618
0
    return rv;
1619
0
}
1620
1621
/*
1622
 * externally callable version of the lowercase pk11_finalize().
1623
 */
1624
SECStatus
1625
PK11_Finalize(PK11Context *context)
1626
0
{
1627
0
    SECStatus rv;
1628
1629
0
    PK11_EnterContextMonitor(context);
1630
0
    rv = pk11_Finalize(context);
1631
0
    PK11_ExitContextMonitor(context);
1632
0
    return rv;
1633
0
}
1634
1635
/*
1636
 * clean up a cipher operation, so the session can be used by
1637
 * someone new.
1638
 */
1639
SECStatus
1640
pk11_Finalize(PK11Context *context)
1641
0
{
1642
0
    CK_ULONG count = 0;
1643
0
    CK_RV crv;
1644
0
    unsigned char stackBuf[256];
1645
0
    unsigned char *buffer = NULL;
1646
1647
0
    if (!context->ownSession) {
1648
0
        return SECSuccess;
1649
0
    }
1650
1651
0
finalize:
1652
0
    switch (context->operation) {
1653
0
        case CKA_ENCRYPT:
1654
0
            crv = PK11_GETTAB(context->slot)->C_EncryptFinal(context->session, buffer, &count);
1655
0
            break;
1656
0
        case CKA_DECRYPT:
1657
0
            crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session, buffer, &count);
1658
0
            break;
1659
0
        case CKA_SIGN:
1660
0
            crv = PK11_GETTAB(context->slot)->C_SignFinal(context->session, buffer, &count);
1661
0
            break;
1662
0
        case CKA_VERIFY:
1663
0
            crv = PK11_GETTAB(context->slot)->C_VerifyFinal(context->session, buffer, count);
1664
0
            break;
1665
0
        case CKA_DIGEST:
1666
0
            crv = PK11_GETTAB(context->slot)->C_DigestFinal(context->session, buffer, &count);
1667
0
            break;
1668
0
        case CKA_NSS_MESSAGE | CKA_ENCRYPT:
1669
0
            crv = PK11_GETTAB(context->slot)->C_MessageEncryptFinal(context->session);
1670
0
            break;
1671
0
        case CKA_NSS_MESSAGE | CKA_DECRYPT:
1672
0
            crv = PK11_GETTAB(context->slot)->C_MessageDecryptFinal(context->session);
1673
0
            break;
1674
0
        case CKA_NSS_MESSAGE | CKA_SIGN:
1675
0
            crv = PK11_GETTAB(context->slot)->C_MessageSignFinal(context->session);
1676
0
            break;
1677
0
        case CKA_NSS_MESSAGE | CKA_VERIFY:
1678
0
            crv = PK11_GETTAB(context->slot)->C_MessageVerifyFinal(context->session);
1679
0
            break;
1680
0
        default:
1681
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
1682
0
            break;
1683
0
    }
1684
1685
0
    if (crv != CKR_OK) {
1686
0
        if (buffer != stackBuf) {
1687
0
            PORT_Free(buffer);
1688
0
        }
1689
0
        if (crv == CKR_OPERATION_NOT_INITIALIZED) {
1690
            /* if there's no operation, it is finalized */
1691
0
            return SECSuccess;
1692
0
        }
1693
0
        PORT_SetError(PK11_MapError(crv));
1694
0
        return SECFailure;
1695
0
    }
1696
1697
    /* Message interface does not need to allocate a final buffer */
1698
0
    if (((context->operation) & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
1699
0
        return SECSuccess;
1700
0
    }
1701
1702
    /* try to finalize the session with a buffer */
1703
0
    if (buffer == NULL) {
1704
0
        if (count <= sizeof stackBuf) {
1705
0
            buffer = stackBuf;
1706
0
        } else {
1707
0
            buffer = PORT_Alloc(count);
1708
0
            if (buffer == NULL) {
1709
0
                return SECFailure;
1710
0
            }
1711
0
        }
1712
0
        goto finalize;
1713
0
    }
1714
0
    if (buffer != stackBuf) {
1715
0
        PORT_Free(buffer);
1716
0
    }
1717
0
    return SECSuccess;
1718
0
}
1719
1720
/*
1721
 *  Return the final digested or signed data...
1722
 *  this routine can either take pre initialized data, or allocate data
1723
 *  either out of an arena or out of the standard heap.
1724
 */
1725
SECStatus
1726
PK11_DigestFinal(PK11Context *context, unsigned char *data,
1727
                 unsigned int *outLen, unsigned int length)
1728
0
{
1729
0
    CK_ULONG len;
1730
0
    CK_RV crv;
1731
0
    SECStatus rv;
1732
1733
    /* message interface returns no data on Final, Should not use DigestFinal
1734
     * in this case */
1735
0
    if (((context->operation) & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
1736
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1737
0
        return SECFailure;
1738
0
    }
1739
1740
    /* if we ran out of session, we need to restore our previously stored
1741
     * state.
1742
     */
1743
0
    PK11_EnterContextMonitor(context);
1744
0
    if (!context->ownSession) {
1745
0
        rv = pk11_restoreContext(context, context->savedData,
1746
0
                                 context->savedLength);
1747
0
        if (rv != SECSuccess) {
1748
0
            PK11_ExitContextMonitor(context);
1749
0
            return rv;
1750
0
        }
1751
0
    }
1752
1753
0
    len = length;
1754
0
    switch (context->operation) {
1755
0
        case CKA_SIGN:
1756
0
            crv = PK11_GETTAB(context->slot)->C_SignFinal(context->session, data, &len);
1757
0
            break;
1758
0
        case CKA_VERIFY:
1759
0
            crv = PK11_GETTAB(context->slot)->C_VerifyFinal(context->session, data, len);
1760
0
            break;
1761
0
        case CKA_DIGEST:
1762
0
            crv = PK11_GETTAB(context->slot)->C_DigestFinal(context->session, data, &len);
1763
0
            break;
1764
0
        case CKA_ENCRYPT:
1765
0
            crv = PK11_GETTAB(context->slot)->C_EncryptFinal(context->session, data, &len);
1766
0
            break;
1767
0
        case CKA_DECRYPT:
1768
0
            crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session, data, &len);
1769
0
            break;
1770
0
        default:
1771
0
            crv = CKR_OPERATION_NOT_INITIALIZED;
1772
0
            break;
1773
0
    }
1774
0
    PK11_ExitContextMonitor(context);
1775
1776
0
    context->init = PR_FALSE; /* allow Begin to start up again */
1777
1778
0
    if (crv != CKR_OK) {
1779
0
        PORT_SetError(PK11_MapError(crv));
1780
0
        return SECFailure;
1781
0
    }
1782
0
    *outLen = (unsigned int)len;
1783
0
    return SECSuccess;
1784
0
}
1785
1786
PRBool
1787
PK11_ContextGetFIPSStatus(PK11Context *context)
1788
0
{
1789
0
    if (context->slot == NULL) {
1790
0
        return PR_FALSE;
1791
0
    }
1792
0
    return pk11slot_GetFIPSStatus(context->slot, context->session,
1793
0
                                  CK_INVALID_HANDLE, context->init ? CKT_NSS_SESSION_CHECK : CKT_NSS_SESSION_LAST_CHECK);
1794
0
}