Bug Summary

File:root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c
Warning:line 3342, column 17
Value stored to 'crv' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name pk11skey.c -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/security/nss/lib/pk11wrap/pk11wrap_pk11wrap -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/security/nss/lib/pk11wrap/pk11wrap_pk11wrap -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG -D SHLIB_SUFFIX="so" -D SHLIB_PREFIX="lib" -D NSS_SHLIB_VERSION="3" -D SOFTOKEN_SHLIB_VERSION="3" -D NSS_FIPS_DISABLED -D NSS_NO_INIT_SUPPORT -D NSS_X86_OR_X64 -D NSS_X64 -D NSS_USE_64 -D USE_UTIL_DIRECTLY -D NO_NSPR_10_SUPPORT -D SSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES -D LINUX2_1 -D LINUX -D linux -D _DEFAULT_SOURCE -D _BSD_SOURCE -D _POSIX_SOURCE -D SDB_MEASURE_USE_TEMP_DIR -D HAVE_STRERROR -D XP_UNIX -D _REENTRANT -D NSS_DISABLE_DBM -D NSS_DISABLE_LIBPKIX -D NSS_USE_PKCS5_PBKD2_PARAMS2_ONLY -D SOFTOKEN_USE_PKCS5_PBKD2_PARAMS2_ONLY -I /root/firefox-clang/security/nss/lib/pk11wrap -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/security/nss/lib/pk11wrap/pk11wrap_pk11wrap -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/private/nss -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -D MOZILLA_CLIENT -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/15/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=tautological-type-limit-compare -Wno-range-loop-analysis -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-unknown-warning-option -Wno-character-conversion -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-07-16-093543-1626485-1 -x c /root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c
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 implements the Symkey wrapper and the PKCS context
6 * Interfaces.
7 */
8
9#include <stddef.h>
10#include <limits.h>
11
12#include "seccomon.h"
13#include "secmod.h"
14#include "secmodi.h"
15#include "secmodti.h"
16#include "pkcs11.h"
17#include "pk11func.h"
18#include "secitem.h"
19#include "secoid.h"
20#include "secerr.h"
21#include "hasht.h"
22
23static ECPointEncoding pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey);
24
25static void
26pk11_EnterKeyMonitor(PK11SymKey *symKey)
27{
28 if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
29 PK11_EnterSlotMonitor(symKey->slot);
30}
31
32static void
33pk11_ExitKeyMonitor(PK11SymKey *symKey)
34{
35 if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
36 PK11_ExitSlotMonitor(symKey->slot);
37}
38
39/*
40 * pk11_getKeyFromList returns a symKey that has a session (if needSession
41 * was specified), or explicitly does not have a session (if needSession
42 * was not specified).
43 */
44static PK11SymKey *
45pk11_getKeyFromList(PK11SlotInfo *slot, PRBool needSession)
46{
47 PK11SymKey *symKey = NULL((void*)0);
48
49 PR_Lock(slot->freeListLock);
50 /* own session list are symkeys with sessions that the symkey owns.
51 * 'most' symkeys will own their own session. */
52 if (needSession) {
53 if (slot->freeSymKeysWithSessionHead) {
54 symKey = slot->freeSymKeysWithSessionHead;
55 slot->freeSymKeysWithSessionHead = symKey->next;
56 slot->keyCount--;
57 }
58 }
59 /* if we don't need a symkey with its own session, or we couldn't find
60 * one on the owner list, get one from the non-owner free list. */
61 if (!symKey) {
62 if (slot->freeSymKeysHead) {
63 symKey = slot->freeSymKeysHead;
64 slot->freeSymKeysHead = symKey->next;
65 slot->keyCount--;
66 }
67 }
68 PR_Unlock(slot->freeListLock);
69 if (symKey) {
70 symKey->next = NULL((void*)0);
71 if (!needSession) {
72 return symKey;
73 }
74 /* if we are getting an owner key, make sure we have a valid session.
75 * session could be invalid if the token has been removed or because
76 * we got it from the non-owner free list */
77 if ((symKey->series != slot->series) ||
78 (symKey->session == CK_INVALID_HANDLE0)) {
79 symKey->session = pk11_GetNewSession(slot, &symKey->sessionOwner);
80 }
81 PORT_Assert(symKey->session != CK_INVALID_HANDLE)((symKey->session != 0)?((void)0):PR_Assert("symKey->session != CK_INVALID_HANDLE"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",81
))
;
82 if (symKey->session != CK_INVALID_HANDLE0)
83 return symKey;
84 PK11_FreeSymKey(symKey);
85 /* if we are here, we need a session, but couldn't get one, it's
86 * unlikely we pk11_GetNewSession will succeed if we call it a second
87 * time. */
88 return NULL((void*)0);
89 }
90
91 symKey = PORT_New(PK11SymKey)(PK11SymKey *)PORT_Alloc_Util(sizeof(PK11SymKey));
92 if (symKey == NULL((void*)0)) {
93 return NULL((void*)0);
94 }
95
96 symKey->next = NULL((void*)0);
97 if (needSession) {
98 symKey->session = pk11_GetNewSession(slot, &symKey->sessionOwner);
99 PORT_Assert(symKey->session != CK_INVALID_HANDLE)((symKey->session != 0)?((void)0):PR_Assert("symKey->session != CK_INVALID_HANDLE"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",99
))
;
100 if (symKey->session == CK_INVALID_HANDLE0) {
101 PK11_FreeSymKey(symKey);
102 symKey = NULL((void*)0);
103 }
104 } else {
105 symKey->session = CK_INVALID_HANDLE0;
106 }
107 return symKey;
108}
109
110/* Caller MUST hold slot->freeListLock (or ref count == 0?) !! */
111void
112PK11_CleanKeyList(PK11SlotInfo *slot)
113{
114 PK11SymKey *symKey = NULL((void*)0);
115
116 while (slot->freeSymKeysWithSessionHead) {
117 symKey = slot->freeSymKeysWithSessionHead;
118 slot->freeSymKeysWithSessionHead = symKey->next;
119 pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
120 PORT_FreePORT_Free_Util(symKey);
121 }
122 while (slot->freeSymKeysHead) {
123 symKey = slot->freeSymKeysHead;
124 slot->freeSymKeysHead = symKey->next;
125 pk11_CloseSession(slot, symKey->session, symKey->sessionOwner);
126 PORT_FreePORT_Free_Util(symKey);
127 }
128 return;
129}
130
131/*
132 * create a symetric key:
133 * Slot is the slot to create the key in.
134 * type is the mechanism type
135 * owner is does this symKey structure own it's object handle (rare
136 * that this is false).
137 * needSession means the returned symKey will return with a valid session
138 * allocated already.
139 */
140static PK11SymKey *
141pk11_CreateSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
142 PRBool owner, PRBool needSession, void *wincx)
143{
144
145 PK11SymKey *symKey = pk11_getKeyFromList(slot, needSession);
146
147 if (symKey == NULL((void*)0)) {
148 return NULL((void*)0);
149 }
150 /* if needSession was specified, make sure we have a valid session.
151 * callers which specify needSession as false should do their own
152 * check of the session before returning the symKey */
153 if (needSession && symKey->session == CK_INVALID_HANDLE0) {
154 PK11_FreeSymKey(symKey);
155 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
156 return NULL((void*)0);
157 }
158
159 symKey->type = type;
160 symKey->data.type = siBuffer;
161 symKey->data.data = NULL((void*)0);
162 symKey->data.len = 0;
163 symKey->owner = owner;
164 symKey->objectID = CK_INVALID_HANDLE0;
165 symKey->slot = slot;
166 symKey->series = slot->series;
167 symKey->cx = wincx;
168 symKey->size = 0;
169 symKey->refCount = 1;
170 symKey->origin = PK11_OriginNULL;
171 symKey->parent = NULL((void*)0);
172 symKey->freeFunc = NULL((void*)0);
173 symKey->userData = NULL((void*)0);
174 PK11_ReferenceSlot(slot);
175 return symKey;
176}
177
178/*
179 * destroy a symetric key
180 */
181void
182PK11_FreeSymKey(PK11SymKey *symKey)
183{
184 PK11SlotInfo *slot;
185 PRBool freeit = PR_TRUE1;
186
187 if (!symKey) {
188 return;
189 }
190
191 if (PR_ATOMIC_DECREMENT(&symKey->refCount)__sync_sub_and_fetch(&symKey->refCount, 1) == 0) {
192 PK11SymKey *parent = symKey->parent;
193
194 symKey->parent = NULL((void*)0);
195 if ((symKey->owner) && symKey->objectID != CK_INVALID_HANDLE0) {
196 pk11_EnterKeyMonitor(symKey);
197 (void)PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_DestroyObject(symKey->session, symKey->objectID);
198 pk11_ExitKeyMonitor(symKey);
199 }
200 if (symKey->data.data) {
201 PORT_Memsetmemset(symKey->data.data, 0, symKey->data.len);
202 PORT_FreePORT_Free_Util(symKey->data.data);
203 }
204 /* free any existing data */
205 if (symKey->userData && symKey->freeFunc) {
206 (*symKey->freeFunc)(symKey->userData);
207 }
208 slot = symKey->slot;
209 PR_Lock(slot->freeListLock);
210 if (slot->keyCount < slot->maxKeyCount) {
211 /*
212 * freeSymkeysWithSessionHead contain a list of reusable
213 * SymKey structures with valid sessions.
214 * sessionOwner must be true.
215 * session must be valid.
216 * freeSymKeysHead contain a list of SymKey structures without
217 * valid session.
218 * session must be CK_INVALID_HANDLE.
219 * though sessionOwner is false, callers should not depend on
220 * this fact.
221 */
222 if (symKey->sessionOwner) {
223 PORT_Assert(symKey->session != CK_INVALID_HANDLE)((symKey->session != 0)?((void)0):PR_Assert("symKey->session != CK_INVALID_HANDLE"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",223
))
;
224 symKey->next = slot->freeSymKeysWithSessionHead;
225 slot->freeSymKeysWithSessionHead = symKey;
226 } else {
227 symKey->session = CK_INVALID_HANDLE0;
228 symKey->next = slot->freeSymKeysHead;
229 slot->freeSymKeysHead = symKey;
230 }
231 slot->keyCount++;
232 symKey->slot = NULL((void*)0);
233 freeit = PR_FALSE0;
234 }
235 PR_Unlock(slot->freeListLock);
236 if (freeit) {
237 pk11_CloseSession(symKey->slot, symKey->session,
238 symKey->sessionOwner);
239 PORT_FreePORT_Free_Util(symKey);
240 }
241 PK11_FreeSlot(slot);
242
243 if (parent) {
244 PK11_FreeSymKey(parent);
245 }
246 }
247}
248
249PK11SymKey *
250PK11_ReferenceSymKey(PK11SymKey *symKey)
251{
252 PR_ATOMIC_INCREMENT(&symKey->refCount)__sync_add_and_fetch(&symKey->refCount, 1);
253 return symKey;
254}
255
256/*
257 * Accessors
258 */
259CK_MECHANISM_TYPE
260PK11_GetMechanism(PK11SymKey *symKey)
261{
262 return symKey->type;
263}
264
265/*
266 * return the slot associated with a symetric key
267 */
268PK11SlotInfo *
269PK11_GetSlotFromKey(PK11SymKey *symKey)
270{
271 return PK11_ReferenceSlot(symKey->slot);
272}
273
274CK_KEY_TYPE
275PK11_GetSymKeyType(PK11SymKey *symKey)
276{
277 return PK11_GetKeyType(symKey->type, symKey->size);
278}
279
280PK11SymKey *
281PK11_GetNextSymKey(PK11SymKey *symKey)
282{
283 return symKey ? symKey->next : NULL((void*)0);
284}
285
286char *
287PK11_GetSymKeyNickname(PK11SymKey *symKey)
288{
289 return PK11_GetObjectNickname(symKey->slot, symKey->objectID);
290}
291
292SECStatus
293PK11_SetSymKeyNickname(PK11SymKey *symKey, const char *nickname)
294{
295 return PK11_SetObjectNickname(symKey->slot, symKey->objectID, nickname);
296}
297
298void *
299PK11_GetSymKeyUserData(PK11SymKey *symKey)
300{
301 return symKey->userData;
302}
303
304void
305PK11_SetSymKeyUserData(PK11SymKey *symKey, void *userData,
306 PK11FreeDataFunc freeFunc)
307{
308 /* free any existing data */
309 if (symKey->userData && symKey->freeFunc) {
310 (*symKey->freeFunc)(symKey->userData);
311 }
312 symKey->userData = userData;
313 symKey->freeFunc = freeFunc;
314 return;
315}
316
317/*
318 * turn key handle into an appropriate key object
319 */
320PK11SymKey *
321PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent, PK11Origin origin,
322 CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID, PRBool owner, void *wincx)
323{
324 PK11SymKey *symKey;
325 PRBool needSession = !(owner && parent);
326
327 if (keyID == CK_INVALID_HANDLE0) {
328 return NULL((void*)0);
329 }
330
331 symKey = pk11_CreateSymKey(slot, type, owner, needSession, wincx);
332 if (symKey == NULL((void*)0)) {
333 return NULL((void*)0);
334 }
335
336 symKey->objectID = keyID;
337 symKey->origin = origin;
338
339 /* adopt the parent's session */
340 /* This is only used by SSL. What we really want here is a session
341 * structure with a ref count so the session goes away only after all the
342 * keys do. */
343 if (!needSession) {
344 symKey->sessionOwner = PR_FALSE0;
345 symKey->session = parent->session;
346 symKey->parent = PK11_ReferenceSymKey(parent);
347 /* This is the only case where pk11_CreateSymKey does not explicitly
348 * check symKey->session. We need to assert here to make sure.
349 * the session isn't invalid. */
350 PORT_Assert(parent->session != CK_INVALID_HANDLE)((parent->session != 0)?((void)0):PR_Assert("parent->session != CK_INVALID_HANDLE"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",350
))
;
351 if (parent->session == CK_INVALID_HANDLE0) {
352 PK11_FreeSymKey(symKey);
353 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
354 return NULL((void*)0);
355 }
356 }
357
358 return symKey;
359}
360
361/*
362 * Restore a symmetric wrapping key that was saved using PK11_SetWrapKey.
363 *
364 * This function is provided for ABI compatibility; see PK11_SetWrapKey below.
365 */
366PK11SymKey *
367PK11_GetWrapKey(PK11SlotInfo *slot, int wrap, CK_MECHANISM_TYPE type,
368 int series, void *wincx)
369{
370 PK11SymKey *symKey = NULL((void*)0);
371 CK_OBJECT_HANDLE keyHandle;
372
373 PK11_EnterSlotMonitor(slot);
374 /* refKeys is a fixed-size array; bounds-check wrap to match
375 * PK11_SetWrapKey. */
376 if (wrap < 0 || (size_t)wrap >= PR_ARRAY_SIZE(slot->refKeys)(sizeof(slot->refKeys)/sizeof((slot->refKeys)[0])) ||
377 slot->series != series ||
378 slot->refKeys[wrap] == CK_INVALID_HANDLE0) {
379 PK11_ExitSlotMonitor(slot);
380 return NULL((void*)0);
381 }
382
383 if (type == CKM_INVALID_MECHANISM0xffffffffUL) {
384 type = slot->wrapMechanism;
385 }
386
387 keyHandle = slot->refKeys[wrap];
388 PK11_ExitSlotMonitor(slot);
389 symKey = PK11_SymKeyFromHandle(slot, NULL((void*)0), PK11_OriginDerive,
390 slot->wrapMechanism, keyHandle, PR_FALSE0, wincx);
391 return symKey;
392}
393
394/*
395 * This function sets an attribute on the current slot with a wrapping key. The
396 * data saved is ephemeral; it needs to be run every time the program is
397 * invoked.
398 *
399 * Since NSS 3.45, this function is marginally more thread safe. It uses the
400 * slot lock (if present) and fails silently if a value is already set. Use
401 * PK11_GetWrapKey() after calling this function to get the current wrapping key
402 * in case there was an update on another thread.
403 *
404 * Either way, using this function is inadvisable. It's provided for ABI
405 * compatibility only.
406 */
407void
408PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey)
409{
410 PK11_EnterSlotMonitor(slot);
411 if (wrap >= 0) {
412 size_t uwrap = (size_t)wrap;
413 if (uwrap < PR_ARRAY_SIZE(slot->refKeys)(sizeof(slot->refKeys)/sizeof((slot->refKeys)[0])) &&
414 slot->refKeys[uwrap] == CK_INVALID_HANDLE0) {
415 /* save the handle and mechanism for the wrapping key */
416 /* mark the key and session as not owned by us so they don't get
417 * freed when the key goes way... that lets us reuse the key
418 * later */
419 slot->refKeys[uwrap] = wrapKey->objectID;
420 wrapKey->owner = PR_FALSE0;
421 wrapKey->sessionOwner = PR_FALSE0;
422 slot->wrapMechanism = wrapKey->type;
423 }
424 }
425 PK11_ExitSlotMonitor(slot);
426}
427
428/*
429 * figure out if a key is still valid or if it is stale.
430 */
431PRBool
432PK11_VerifyKeyOK(PK11SymKey *key)
433{
434 if (!PK11_IsPresent(key->slot)) {
435 return PR_FALSE0;
436 }
437 return (PRBool)(key->series == key->slot->series);
438}
439
440static PK11SymKey *
441pk11_ImportSymKeyWithTempl(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
442 PK11Origin origin, PRBool isToken, CK_ATTRIBUTE *keyTemplate,
443 unsigned int templateCount, SECItem *key, void *wincx)
444{
445 PK11SymKey *symKey;
446 SECStatus rv;
447
448 symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE1, wincx);
449 if (symKey == NULL((void*)0)) {
450 return NULL((void*)0);
451 }
452
453 symKey->size = key->len;
454
455 PK11_SETATTRS(&keyTemplate[templateCount], CKA_VALUE, key->data, key->len)(&keyTemplate[templateCount])->type = (0x00000011UL); (
&keyTemplate[templateCount])->pValue = (key->data);
(&keyTemplate[templateCount])->ulValueLen = (key->
len);
;
456 templateCount++;
457
458 if (SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &symKey->data, key) != SECSuccess) {
459 PK11_FreeSymKey(symKey);
460 return NULL((void*)0);
461 }
462
463 symKey->origin = origin;
464
465 /* import the keys */
466 rv = PK11_CreateNewObject(slot, symKey->session, keyTemplate,
467 templateCount, isToken, &symKey->objectID);
468 if (rv != SECSuccess) {
469 PK11_FreeSymKey(symKey);
470 return NULL((void*)0);
471 }
472
473 return symKey;
474}
475
476/*
477 * turn key bits into an appropriate key object
478 */
479PK11SymKey *
480PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
481 PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx)
482{
483 PK11SymKey *symKey;
484 unsigned int templateCount = 0;
485 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
486 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
487 CK_BBOOL cktrue = CK_TRUE1; /* sigh */
488 CK_ATTRIBUTE keyTemplate[5];
489 CK_ATTRIBUTE *attrs = keyTemplate;
490
491 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
492 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
493 * it as a real attribute */
494 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
495 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
496 * etc. Strip out the real attribute here */
497 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
498 }
499
500 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
501 attrs++;
502 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
503 attrs++;
504 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
505 attrs++;
506 templateCount = attrs - keyTemplate;
507 PR_ASSERT(templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",507
))
;
508
509 keyType = PK11_GetKeyType(type, key->len);
510 symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, PR_FALSE0,
511 keyTemplate, templateCount, key, wincx);
512 return symKey;
513}
514/* Import a PKCS #11 data object and return it as a key. This key is
515 * only useful in a limited number of mechanisms, such as HKDF. */
516PK11SymKey *
517PK11_ImportDataKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, PK11Origin origin,
518 CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx)
519{
520 CK_OBJECT_CLASS ckoData = CKO_DATA0x00000000UL;
521 CK_ATTRIBUTE template[2] = { { CKA_CLASS0x00000000UL, (CK_BYTE_PTR)&ckoData, sizeof(ckoData) },
522 { CKA_VALUE0x00000011UL, (CK_BYTE_PTR)key->data, key->len } };
523 CK_OBJECT_HANDLE handle;
524 PK11GenericObject *genObject;
525
526 genObject = PK11_CreateGenericObject(slot, template, PR_ARRAY_SIZE(template)(sizeof(template)/sizeof((template)[0])), PR_FALSE0);
527 if (genObject == NULL((void*)0)) {
528 return NULL((void*)0);
529 }
530 handle = PK11_GetObjectHandle(PK11_TypeGeneric, genObject, NULL((void*)0));
531 /* A note about ownership of the PKCS #11 handle:
532 * PK11_CreateGenericObject() will not destroy the object it creates
533 * on Free, For that you want PK11_CreateManagedGenericObject().
534 * Below we import the handle into the symKey structure. We pass
535 * PR_TRUE as the owner so that the symKey will destroy the object
536 * once it's freed. This is why it's safe to destroy genObject now. */
537 PK11_DestroyGenericObject(genObject);
538 if (handle == CK_INVALID_HANDLE0) {
539 return NULL((void*)0);
540 }
541 return PK11_SymKeyFromHandle(slot, NULL((void*)0), origin, type, handle, PR_TRUE1, wincx);
542}
543
544/* turn key bits into an appropriate key object */
545PK11SymKey *
546PK11_ImportSymKeyWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
547 PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
548 CK_FLAGS flags, PRBool isPerm, void *wincx)
549{
550 PK11SymKey *symKey;
551 unsigned int templateCount = 0;
552 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
553 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
554 CK_BBOOL cktrue = CK_TRUE1; /* sigh */
555 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
556 CK_ATTRIBUTE *attrs = keyTemplate;
557
558 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
559 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
560 * it as a real attribute */
561 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
562 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
563 * etc. Strip out the real attribute here */
564 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
565 }
566
567 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
568 attrs++;
569 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
570 attrs++;
571 if (isPerm) {
572 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(cktrue));
;
573 attrs++;
574 /* sigh some tokens think CKA_PRIVATE = false is a reasonable
575 * default for secret keys */
576 PK11_SETATTRS(attrs, CKA_PRIVATE, &cktrue, sizeof(cktrue))(attrs)->type = (0x00000002UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(cktrue));
;
577 attrs++;
578 }
579 attrs += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
580 if ((operation != CKA_FLAGS_ONLY0) &&
581 !pk11_FindAttrInTemplate(keyTemplate, attrs - keyTemplate, operation)) {
582 PK11_SETATTRS(attrs, operation, &cktrue, sizeof(cktrue))(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (sizeof(cktrue));
;
583 attrs++;
584 }
585 templateCount = attrs - keyTemplate;
586 PR_ASSERT(templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount + 1 <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",586
))
;
587
588 keyType = PK11_GetKeyType(type, key->len);
589 symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, isPerm,
590 keyTemplate, templateCount, key, wincx);
591 if (symKey && isPerm) {
592 symKey->owner = PR_FALSE0;
593 }
594 return symKey;
595}
596
597PK11SymKey *
598PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *keyID,
599 void *wincx)
600{
601 CK_ATTRIBUTE findTemp[5];
602 CK_ATTRIBUTE *attrs;
603 CK_BBOOL ckTrue = CK_TRUE1;
604 CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY0x00000004UL;
605 size_t tsize = 0;
606 CK_OBJECT_HANDLE key_id;
607 CK_KEY_TYPE keyType = PK11_GetKeyType(type, 0);
608
609 attrs = findTemp;
610 PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyclass); (attrs)->ulValueLen = (sizeof(keyclass));
;
611 attrs++;
612 PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
ckTrue); (attrs)->ulValueLen = (sizeof(ckTrue));
;
613 attrs++;
614 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
615 attrs++;
616 if (keyID) {
617 PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len)(attrs)->type = (0x00000102UL); (attrs)->pValue = (keyID
->data); (attrs)->ulValueLen = (keyID->len);
;
618 attrs++;
619 }
620 tsize = attrs - findTemp;
621 PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE))((tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE))?((void
)0):PR_Assert("tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",621
))
;
622
623 key_id = pk11_FindObjectByTemplate(slot, findTemp, tsize);
624 if (key_id == CK_INVALID_HANDLE0) {
625 return NULL((void*)0);
626 }
627 return PK11_SymKeyFromHandle(slot, NULL((void*)0), PK11_OriginDerive, type, key_id,
628 PR_FALSE0, wincx);
629}
630
631PK11SymKey *
632PK11_ListFixedKeysInSlot(PK11SlotInfo *slot, char *nickname, void *wincx)
633{
634 CK_ATTRIBUTE findTemp[4];
635 CK_ATTRIBUTE *attrs;
636 CK_BBOOL ckTrue = CK_TRUE1;
637 CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY0x00000004UL;
638 int tsize = 0;
639 int objCount = 0;
640 CK_OBJECT_HANDLE *key_ids;
641 PK11SymKey *nextKey = NULL((void*)0);
642 PK11SymKey *topKey = NULL((void*)0);
643 int i, len;
644
645 attrs = findTemp;
646 PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyclass); (attrs)->ulValueLen = (sizeof(keyclass));
;
647 attrs++;
648 PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
ckTrue); (attrs)->ulValueLen = (sizeof(ckTrue));
;
649 attrs++;
650 if (nickname) {
651 len = PORT_Strlen(nickname)strlen(nickname);
652 PK11_SETATTRS(attrs, CKA_LABEL, nickname, len)(attrs)->type = (0x00000003UL); (attrs)->pValue = (nickname
); (attrs)->ulValueLen = (len);
;
653 attrs++;
654 }
655 tsize = attrs - findTemp;
656 PORT_Assert(tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE))((tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE))?((void
)0):PR_Assert("tsize <= sizeof(findTemp) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",656
))
;
657
658 key_ids = pk11_FindObjectsByTemplate(slot, findTemp, tsize, &objCount);
659 if (key_ids == NULL((void*)0)) {
660 return NULL((void*)0);
661 }
662
663 for (i = 0; i < objCount; i++) {
664 SECItem typeData;
665 CK_KEY_TYPE type = CKK_GENERIC_SECRET0x00000010UL;
666 SECStatus rv = PK11_ReadAttribute(slot, key_ids[i],
667 CKA_KEY_TYPE0x00000100UL, NULL((void*)0), &typeData);
668 if (rv == SECSuccess) {
669 if (typeData.len == sizeof(CK_KEY_TYPE)) {
670 type = *(CK_KEY_TYPE *)typeData.data;
671 }
672 PORT_FreePORT_Free_Util(typeData.data);
673 }
674 nextKey = PK11_SymKeyFromHandle(slot, NULL((void*)0), PK11_OriginDerive,
675 PK11_GetKeyMechanism(type), key_ids[i], PR_FALSE0, wincx);
676 if (nextKey) {
677 nextKey->next = topKey;
678 topKey = nextKey;
679 }
680 }
681 PORT_FreePORT_Free_Util(key_ids);
682 return topKey;
683}
684
685void *
686PK11_GetWindow(PK11SymKey *key)
687{
688 return key->cx;
689}
690
691/*
692 * extract a symmetric key value. NOTE: if the key is sensitive, we will
693 * not be able to do this operation. This function is used to move
694 * keys from one token to another */
695SECStatus
696PK11_ExtractKeyValue(PK11SymKey *symKey)
697{
698 SECStatus rv;
699
700 if (symKey == NULL((void*)0)) {
701 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
702 return SECFailure;
703 }
704
705 if (symKey->data.data != NULL((void*)0)) {
706 if (symKey->size == 0) {
707 symKey->size = symKey->data.len;
708 }
709 return SECSuccess;
710 }
711
712 if (symKey->slot == NULL((void*)0)) {
713 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_KEY);
714 return SECFailure;
715 }
716
717 rv = PK11_ReadAttribute(symKey->slot, symKey->objectID, CKA_VALUE0x00000011UL, NULL((void*)0),
718 &symKey->data);
719 if (rv == SECSuccess) {
720 symKey->size = symKey->data.len;
721 }
722 return rv;
723}
724
725SECStatus
726PK11_DeleteTokenSymKey(PK11SymKey *symKey)
727{
728 if (!PK11_IsPermObject(symKey->slot, symKey->objectID)) {
729 return SECFailure;
730 }
731 PK11_DestroyTokenObject(symKey->slot, symKey->objectID);
732 symKey->objectID = CK_INVALID_HANDLE0;
733 return SECSuccess;
734}
735
736SECItem *
737PK11_GetKeyData(PK11SymKey *symKey)
738{
739 return &symKey->data;
740}
741
742/* This symbol is exported for backward compatibility. */
743SECItem *
744__PK11_GetKeyData(PK11SymKey *symKey)
745{
746 return PK11_GetKeyData(symKey);
747}
748
749/*
750 * PKCS #11 key Types with predefined length
751 */
752unsigned int
753pk11_GetPredefinedKeyLength(CK_KEY_TYPE keyType)
754{
755 int length = 0;
756 switch (keyType) {
757 case CKK_DES0x00000013UL:
758 length = 8;
759 break;
760 case CKK_DES20x00000014UL:
761 length = 16;
762 break;
763 case CKK_DES30x00000015UL:
764 length = 24;
765 break;
766 case CKK_SKIPJACK0x0000001BUL:
767 length = 10;
768 break;
769 case CKK_BATON0x0000001CUL:
770 length = 20;
771 break;
772 case CKK_JUNIPER0x0000001DUL:
773 length = 20;
774 break;
775 default:
776 break;
777 }
778 return length;
779}
780
781/* return the keylength if possible. '0' if not */
782unsigned int
783PK11_GetKeyLength(PK11SymKey *key)
784{
785 CK_KEY_TYPE keyType;
786
787 if (key->size != 0)
788 return key->size;
789
790 /* First try to figure out the key length from its type */
791 keyType = PK11_ReadULongAttribute(key->slot, key->objectID, CKA_KEY_TYPE0x00000100UL);
792 key->size = pk11_GetPredefinedKeyLength(keyType);
793 if ((keyType == CKK_GENERIC_SECRET0x00000010UL) &&
794 (key->type == CKM_SSL3_PRE_MASTER_KEY_GEN0x00000370UL)) {
795 key->size = 48;
796 }
797
798 if (key->size != 0)
799 return key->size;
800
801 if (key->data.data == NULL((void*)0)) {
802 PK11_ExtractKeyValue(key);
803 }
804 /* key is probably secret. Look up its length */
805 /* this is new PKCS #11 version 2.0 functionality. */
806 if (key->size == 0) {
807 CK_ULONG keyLength;
808
809 keyLength = PK11_ReadULongAttribute(key->slot, key->objectID, CKA_VALUE_LEN0x00000161UL);
810 if (keyLength != CK_UNAVAILABLE_INFORMATION(~0UL)) {
811 key->size = (unsigned int)keyLength;
812 }
813 }
814
815 return key->size;
816}
817
818/* return the strength of a key. This is different from length in that
819 * 1) it returns the size in bits, and 2) it returns only the secret portions
820 * of the key minus any checksums or parity.
821 */
822unsigned int
823PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid)
824{
825 int size = 0;
826 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM0xffffffffUL; /* RC2 only */
827 SECItem *param = NULL((void*)0); /* RC2 only */
828 CK_RC2_CBC_PARAMS *rc2_params = NULL((void*)0); /* RC2 ONLY */
829 unsigned int effectiveBits = 0; /* RC2 ONLY */
830
831 switch (PK11_GetKeyType(key->type, 0)) {
832 case CKK_CDMF0x0000001EUL:
833 return 40;
834 case CKK_DES0x00000013UL:
835 return 56;
836 case CKK_DES30x00000015UL:
837 case CKK_DES20x00000014UL:
838 size = PK11_GetKeyLength(key);
839 if (size == 16) {
840 /* double des */
841 return 112; /* 16*7 */
842 }
843 return 168;
844 /*
845 * RC2 has is different than other ciphers in that it allows the user
846 * to deprecating keysize while still requiring all the bits for the
847 * original key. The info
848 * on what the effective key strength is in the parameter for the key.
849 * In S/MIME this parameter is stored in the DER encoded algid. In Our
850 * other uses of RC2, effectiveBits == keyBits, so this code functions
851 * correctly without an algid.
852 */
853 case CKK_RC20x00000011UL:
854 /* if no algid was provided, fall through to default */
855 if (!algid) {
856 break;
857 }
858 /* verify that the algid is for RC2 */
859 mechanism = PK11_AlgtagToMechanism(SECOID_GetAlgorithmTagSECOID_GetAlgorithmTag_Util(algid));
860 if ((mechanism != CKM_RC2_CBC0x00000102UL) && (mechanism != CKM_RC2_ECB0x00000101UL)) {
861 break;
862 }
863
864 /* now get effective bits from the algorithm ID. */
865 param = PK11_ParamFromAlgid(algid);
866 /* if we couldn't get memory just use key length */
867 if (param == NULL((void*)0)) {
868 break;
869 }
870
871 rc2_params = (CK_RC2_CBC_PARAMS *)param->data;
872 /* paranoia... shouldn't happen */
873 PORT_Assert(param->data != NULL)((param->data != ((void*)0))?((void)0):PR_Assert("param->data != NULL"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",873
))
;
874 if (param->data == NULL((void*)0)) {
875 SECITEM_FreeItemSECITEM_FreeItem_Util(param, PR_TRUE1);
876 break;
877 }
878 effectiveBits = (unsigned int)rc2_params->ulEffectiveBits;
879 SECITEM_FreeItemSECITEM_FreeItem_Util(param, PR_TRUE1);
880 param = NULL((void*)0);
881 rc2_params = NULL((void*)0); /* paranoia */
882
883 /* we have effective bits, is and allocated memory is free, now
884 * we need to return the smaller of effective bits and keysize */
885 size = PK11_GetKeyLength(key);
886 if ((unsigned int)size * 8 > effectiveBits) {
887 return effectiveBits;
888 }
889
890 return size * 8; /* the actual key is smaller, the strength can't be
891 * greater than the actual key size */
892
893 default:
894 break;
895 }
896 return PK11_GetKeyLength(key) * 8;
897}
898
899/*
900 * The next three utilities are to deal with the fact that a given operation
901 * may be a multi-slot affair. This creates a new key object that is copied
902 * into the new slot.
903 */
904PK11SymKey *
905pk11_CopyToSlotPerm(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
906 CK_ATTRIBUTE_TYPE operation, CK_FLAGS flags,
907 PRBool isPerm, PK11SymKey *symKey)
908{
909 SECStatus rv;
910 PK11SymKey *newKey = NULL((void*)0);
911
912 /* Extract the raw key data if possible */
913 if (symKey->data.data == NULL((void*)0)) {
914 rv = PK11_ExtractKeyValue(symKey);
915 /* KEY is sensitive, we're try key exchanging it. */
916 if (rv != SECSuccess) {
917 return pk11_KeyExchange(slot, type, operation,
918 flags, isPerm, symKey);
919 }
920 }
921
922 newKey = PK11_ImportSymKeyWithFlags(slot, type, symKey->origin,
923 operation, &symKey->data, flags, isPerm, symKey->cx);
924 if (newKey == NULL((void*)0)) {
925 newKey = pk11_KeyExchange(slot, type, operation, flags, isPerm, symKey);
926 }
927 return newKey;
928}
929
930PK11SymKey *
931pk11_CopyToSlot(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
932 CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey)
933{
934 return pk11_CopyToSlotPerm(slot, type, operation, 0, PR_FALSE0, symKey);
935}
936
937/*
938 * Make sure the slot we are in is the correct slot for the operation
939 * by verifying that it supports all of the specified mechanism types.
940 */
941PK11SymKey *
942pk11_ForceSlotMultiple(PK11SymKey *symKey, CK_MECHANISM_TYPE *type,
943 int mechCount, CK_ATTRIBUTE_TYPE operation)
944{
945 PK11SlotInfo *slot = symKey->slot;
946 PK11SymKey *newKey = NULL((void*)0);
947 PRBool needToCopy = PR_FALSE0;
948 int i;
949
950 if (slot == NULL((void*)0)) {
951 needToCopy = PR_TRUE1;
952 } else {
953 i = 0;
954 while ((i < mechCount) && (needToCopy == PR_FALSE0)) {
955 if (!PK11_DoesMechanism(slot, type[i])) {
956 needToCopy = PR_TRUE1;
957 }
958 i++;
959 }
960 }
961
962 if (needToCopy == PR_TRUE1) {
963 slot = PK11_GetBestSlotMultiple(type, mechCount, symKey->cx);
964 if (slot == NULL((void*)0)) {
965 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
966 return NULL((void*)0);
967 }
968 newKey = pk11_CopyToSlot(slot, type[0], operation, symKey);
969 PK11_FreeSlot(slot);
970 }
971 return newKey;
972}
973
974/*
975 * Make sure the slot we are in is the correct slot for the operation
976 */
977PK11SymKey *
978pk11_ForceSlot(PK11SymKey *symKey, CK_MECHANISM_TYPE type,
979 CK_ATTRIBUTE_TYPE operation)
980{
981 return pk11_ForceSlotMultiple(symKey, &type, 1, operation);
982}
983
984PK11SymKey *
985PK11_MoveSymKey(PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation,
986 CK_FLAGS flags, PRBool perm, PK11SymKey *symKey)
987{
988 if (symKey->slot == slot) {
989 if (perm) {
990 return PK11_ConvertSessionSymKeyToTokenSymKey(symKey, symKey->cx);
991 } else {
992 return PK11_ReferenceSymKey(symKey);
993 }
994 }
995
996 return pk11_CopyToSlotPerm(slot, symKey->type,
997 operation, flags, perm, symKey);
998}
999
1000/*
1001 * Use the token to generate a key.
1002 *
1003 * keySize must be 'zero' for fixed key length algorithms. A nonzero
1004 * keySize causes the CKA_VALUE_LEN attribute to be added to the template
1005 * for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN
1006 * attribute for keys with fixed length. The exception is DES2. If you
1007 * select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
1008 * parameter and use the key size to determine which underlying DES keygen
1009 * function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
1010 *
1011 * keyType must be -1 for most algorithms. Some PBE algorthims cannot
1012 * determine the correct key type from the mechanism or the parameters,
1013 * so key type must be specified. Other PKCS #11 mechanisms may do so in
1014 * the future. Currently there is no need to export this publically.
1015 * Keep it private until there is a need in case we need to expand the
1016 * keygen parameters again...
1017 *
1018 * CK_FLAGS flags: key operation flags
1019 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
1020 */
1021PK11SymKey *
1022pk11_TokenKeyGenWithFlagsAndKeyType(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1023 SECItem *param, CK_KEY_TYPE keyType, int keySize, SECItem *keyid,
1024 CK_FLAGS opFlags, PK11AttrFlags attrFlags, void *wincx)
1025{
1026 PK11SymKey *symKey;
1027 CK_ATTRIBUTE genTemplate[MAX_TEMPL_ATTRS16];
1028 CK_ATTRIBUTE *attrs = genTemplate;
1029 int count = sizeof(genTemplate) / sizeof(genTemplate[0]);
1030 CK_MECHANISM_TYPE keyGenType;
1031 CK_BBOOL cktrue = CK_TRUE1;
1032 CK_BBOOL ckfalse = CK_FALSE0;
1033 CK_ULONG ck_key_size; /* only used for variable-length keys */
1034
1035 if (pk11_BadAttrFlags(attrFlags)) {
1036 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1037 return NULL((void*)0);
1038 }
1039
1040 if ((keySize != 0) && (type != CKM_DES3_CBC0x00000133UL) &&
1041 (type != CKM_DES3_CBC_PAD0x00000136UL) && (type != CKM_DES3_ECB0x00000132UL)) {
1042 ck_key_size = keySize; /* Convert to PK11 type */
1043
1044 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &ck_key_size, sizeof(ck_key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
ck_key_size); (attrs)->ulValueLen = (sizeof(ck_key_size));
;
1045 attrs++;
1046 }
1047
1048 if (keyType != -1) {
1049 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(CK_KEY_TYPE))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(CK_KEY_TYPE));
;
1050 attrs++;
1051 }
1052
1053 /* Include key id value if provided */
1054 if (keyid) {
1055 PK11_SETATTRS(attrs, CKA_ID, keyid->data, keyid->len)(attrs)->type = (0x00000102UL); (attrs)->pValue = (keyid
->data); (attrs)->ulValueLen = (keyid->len);
;
1056 attrs++;
1057 }
1058
1059 attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
1060 attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
1061
1062 count = attrs - genTemplate;
1063 PR_ASSERT(count <= sizeof(genTemplate) / sizeof(CK_ATTRIBUTE))((count <= sizeof(genTemplate) / sizeof(CK_ATTRIBUTE))?((void
)0):PR_Assert("count <= sizeof(genTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",1063
))
;
1064
1065 keyGenType = PK11_GetKeyGenWithSize(type, keySize);
1066 if (keyGenType == CKM_FAKE_RANDOM0x80000efeUL) {
1067 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
1068 return NULL((void*)0);
1069 }
1070 symKey = PK11_KeyGenWithTemplate(slot, type, keyGenType,
1071 param, genTemplate, count, wincx);
1072 if (symKey != NULL((void*)0)) {
1073 symKey->size = keySize;
1074 }
1075 return symKey;
1076}
1077
1078/*
1079 * Use the token to generate a key. - Public
1080 *
1081 * keySize must be 'zero' for fixed key length algorithms. A nonzero
1082 * keySize causes the CKA_VALUE_LEN attribute to be added to the template
1083 * for the key. Most PKCS #11 modules fail if you specify the CKA_VALUE_LEN
1084 * attribute for keys with fixed length. The exception is DES2. If you
1085 * select a CKM_DES3_CBC mechanism, this code will not add the CKA_VALUE_LEN
1086 * parameter and use the key size to determine which underlying DES keygen
1087 * function to use (CKM_DES2_KEY_GEN or CKM_DES3_KEY_GEN).
1088 *
1089 * CK_FLAGS flags: key operation flags
1090 * PK11AttrFlags attrFlags: PK11_ATTR_XXX key attribute flags
1091 */
1092PK11SymKey *
1093PK11_TokenKeyGenWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1094 SECItem *param, int keySize, SECItem *keyid, CK_FLAGS opFlags,
1095 PK11AttrFlags attrFlags, void *wincx)
1096{
1097 return pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param, -1, keySize,
1098 keyid, opFlags, attrFlags, wincx);
1099}
1100
1101/*
1102 * Use the token to generate a key. keySize must be 'zero' for fixed key
1103 * length algorithms. A nonzero keySize causes the CKA_VALUE_LEN attribute
1104 * to be added to the template for the key. PKCS #11 modules fail if you
1105 * specify the CKA_VALUE_LEN attribute for keys with fixed length.
1106 * NOTE: this means to generate a DES2 key from this interface you must
1107 * specify CKM_DES2_KEY_GEN as the mechanism directly; specifying
1108 * CKM_DES3_CBC as the mechanism and 16 as keySize currently doesn't work.
1109 */
1110PK11SymKey *
1111PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
1112 int keySize, SECItem *keyid, PRBool isToken, void *wincx)
1113{
1114 PK11SymKey *symKey;
1115 PRBool weird = PR_FALSE0; /* hack for fortezza */
1116 CK_FLAGS opFlags = CKF_SIGN0x00000800UL;
1117 PK11AttrFlags attrFlags = 0;
1118
1119 if ((keySize == -1) && (type == CKM_SKIPJACK_CBC640x00001002UL)) {
1120 weird = PR_TRUE1;
1121 keySize = 0;
1122 }
1123
1124 opFlags |= weird ? CKF_DECRYPT0x00000200UL : CKF_ENCRYPT0x00000100UL;
1125
1126 if (isToken) {
1127 attrFlags |= (PK11_ATTR_TOKEN0x00000001L | PK11_ATTR_PRIVATE0x00000004L);
1128 }
1129
1130 symKey = pk11_TokenKeyGenWithFlagsAndKeyType(slot, type, param,
1131 -1, keySize, keyid, opFlags, attrFlags, wincx);
1132 if (symKey && weird) {
1133 PK11_SetFortezzaHack(symKey);
1134 }
1135
1136 return symKey;
1137}
1138
1139PK11SymKey *
1140PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
1141 int keySize, void *wincx)
1142{
1143 return PK11_TokenKeyGen(slot, type, param, keySize, 0, PR_FALSE0, wincx);
1144}
1145
1146PK11SymKey *
1147PK11_KeyGenWithTemplate(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
1148 CK_MECHANISM_TYPE keyGenType,
1149 SECItem *param, CK_ATTRIBUTE *attrs,
1150 unsigned int attrsCount, void *wincx)
1151{
1152 PK11SymKey *symKey;
1153 CK_SESSION_HANDLE session;
1154 CK_MECHANISM mechanism;
1155 CK_RV crv;
1156 PRBool isToken = CK_FALSE0;
1157 CK_ULONG keySize = 0;
1158 unsigned i;
1159
1160 /* Extract the template's CKA_VALUE_LEN into keySize and CKA_TOKEN into
1161 isToken. */
1162 for (i = 0; i < attrsCount; ++i) {
1163 switch (attrs[i].type) {
1164 case CKA_VALUE_LEN0x00000161UL:
1165 if (attrs[i].pValue == NULL((void*)0) ||
1166 attrs[i].ulValueLen != sizeof(CK_ULONG)) {
1167 PORT_SetErrorPORT_SetError_Util(PK11_MapError(CKR_TEMPLATE_INCONSISTENT0x000000D1UL));
1168 return NULL((void*)0);
1169 }
1170 keySize = *(CK_ULONG *)attrs[i].pValue;
1171 break;
1172 case CKA_TOKEN0x00000001UL:
1173 if (attrs[i].pValue == NULL((void*)0) ||
1174 attrs[i].ulValueLen != sizeof(CK_BBOOL)) {
1175 PORT_SetErrorPORT_SetError_Util(PK11_MapError(CKR_TEMPLATE_INCONSISTENT0x000000D1UL));
1176 return NULL((void*)0);
1177 }
1178 isToken = (*(CK_BBOOL *)attrs[i].pValue) ? PR_TRUE1 : PR_FALSE0;
1179 break;
1180 }
1181 }
1182
1183 /* find a slot to generate the key into */
1184 /* Only do slot management if this is not a token key */
1185 if (!isToken && (slot == NULL((void*)0) || !PK11_DoesMechanism(slot, type))) {
1186 PK11SlotInfo *bestSlot = PK11_GetBestSlot(type, wincx);
1187 if (bestSlot == NULL((void*)0)) {
1188 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
1189 return NULL((void*)0);
1190 }
1191 symKey = pk11_CreateSymKey(bestSlot, type, !isToken, PR_TRUE1, wincx);
1192 PK11_FreeSlot(bestSlot);
1193 } else {
1194 symKey = pk11_CreateSymKey(slot, type, !isToken, PR_TRUE1, wincx);
1195 }
1196 if (symKey == NULL((void*)0))
1197 return NULL((void*)0);
1198
1199 symKey->size = keySize;
1200 symKey->origin = PK11_OriginGenerated;
1201
1202 /* Set the parameters for the key gen if provided */
1203 mechanism.mechanism = keyGenType;
1204 mechanism.pParameter = NULL((void*)0);
1205 mechanism.ulParameterLen = 0;
1206 if (param) {
1207 mechanism.pParameter = param->data;
1208 mechanism.ulParameterLen = param->len;
1209 }
1210
1211 /* Get session and perform locking */
1212 if (isToken) {
1213 PK11_Authenticate(symKey->slot, PR_TRUE1, wincx);
1214 /* Should always be original slot */
1215 session = PK11_GetRWSession(symKey->slot);
1216 symKey->owner = PR_FALSE0;
1217 } else {
1218 session = symKey->session;
1219 if (session != CK_INVALID_HANDLE0)
1220 pk11_EnterKeyMonitor(symKey);
1221 }
1222 if (session == CK_INVALID_HANDLE0) {
1223 PK11_FreeSymKey(symKey);
1224 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_DATA);
1225 return NULL((void*)0);
1226 }
1227
1228 crv = PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_GenerateKey(session, &mechanism, attrs, attrsCount, &symKey->objectID);
1229
1230 /* Release lock and session */
1231 if (isToken) {
1232 PK11_RestoreROSession(symKey->slot, session);
1233 } else {
1234 pk11_ExitKeyMonitor(symKey);
1235 }
1236
1237 if (crv != CKR_OK0x00000000UL) {
1238 PK11_FreeSymKey(symKey);
1239 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1240 return NULL((void*)0);
1241 }
1242
1243 return symKey;
1244}
1245
1246PK11SymKey *
1247PK11_ConvertSessionSymKeyToTokenSymKey(PK11SymKey *symk, void *wincx)
1248{
1249 PK11SlotInfo *slot = symk->slot;
1250 CK_ATTRIBUTE template[1];
1251 CK_ATTRIBUTE *attrs = template;
1252 CK_BBOOL cktrue = CK_TRUE1;
1253 CK_RV crv;
1254 CK_OBJECT_HANDLE newKeyID;
1255 CK_SESSION_HANDLE rwsession;
1256
1257 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(cktrue));
;
1258 attrs++;
1259
1260 PK11_Authenticate(slot, PR_TRUE1, wincx);
1261 rwsession = PK11_GetRWSession(slot);
1262 if (rwsession == CK_INVALID_HANDLE0) {
1263 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_DATA);
1264 return NULL((void*)0);
1265 }
1266 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_CopyObject(rwsession, symk->objectID,
1267 template, 1, &newKeyID);
1268 PK11_RestoreROSession(slot, rwsession);
1269
1270 if (crv != CKR_OK0x00000000UL) {
1271 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1272 return NULL((void*)0);
1273 }
1274
1275 return PK11_SymKeyFromHandle(slot, NULL((void*)0) /*parent*/, symk->origin,
1276 symk->type, newKeyID, PR_FALSE0 /*owner*/, NULL((void*)0) /*wincx*/);
1277}
1278
1279/* This function does a straight public key wrap with the CKM_RSA_PKCS
1280 * mechanism. */
1281SECStatus
1282PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
1283 PK11SymKey *symKey, SECItem *wrappedKey)
1284{
1285 CK_MECHANISM_TYPE inferred = pk11_mapWrapKeyType(pubKey->keyType);
1286 return PK11_PubWrapSymKeyWithMechanism(pubKey, inferred, NULL((void*)0), symKey,
1287 wrappedKey);
1288}
1289
1290/* This function wraps a symmetric key with a public key, such as with the
1291 * CKM_RSA_PKCS and CKM_RSA_PKCS_OAEP mechanisms. */
1292SECStatus
1293PK11_PubWrapSymKeyWithMechanism(SECKEYPublicKey *pubKey,
1294 CK_MECHANISM_TYPE mechType, SECItem *param,
1295 PK11SymKey *symKey, SECItem *wrappedKey)
1296{
1297 PK11SlotInfo *slot;
1298 CK_ULONG len = wrappedKey->len;
1299 PK11SymKey *newKey = NULL((void*)0);
1300 CK_OBJECT_HANDLE id;
1301 CK_MECHANISM mechanism;
1302 PRBool owner = PR_TRUE1;
1303 CK_SESSION_HANDLE session;
1304 CK_RV crv;
1305
1306 if (symKey == NULL((void*)0)) {
1307 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1308 return SECFailure;
1309 }
1310
1311 /* if this slot doesn't support the mechanism, go to a slot that does */
1312 newKey = pk11_ForceSlot(symKey, mechType, CKA_ENCRYPT0x00000104UL);
1313 if (newKey != NULL((void*)0)) {
1314 symKey = newKey;
1315 }
1316
1317 if (symKey->slot == NULL((void*)0)) {
1318 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
1319 return SECFailure;
1320 }
1321
1322 slot = symKey->slot;
1323
1324 mechanism.mechanism = mechType;
1325 if (param == NULL((void*)0)) {
1326 mechanism.pParameter = NULL((void*)0);
1327 mechanism.ulParameterLen = 0;
1328 } else {
1329 mechanism.pParameter = param->data;
1330 mechanism.ulParameterLen = param->len;
1331 }
1332
1333 id = PK11_ImportPublicKey(slot, pubKey, PR_FALSE0);
1334 if (id == CK_INVALID_HANDLE0) {
1335 if (newKey) {
1336 PK11_FreeSymKey(newKey);
1337 }
1338 return SECFailure; /* Error code has been set. */
1339 }
1340
1341 session = pk11_GetNewSession(slot, &owner);
1342 if (!owner || !(slot->isThreadSafe))
1343 PK11_EnterSlotMonitor(slot);
1344 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_WrapKey(session, &mechanism,
1345 id, symKey->objectID, wrappedKey->data, &len);
1346 if (!owner || !(slot->isThreadSafe))
1347 PK11_ExitSlotMonitor(slot);
1348 pk11_CloseSession(slot, session, owner);
1349 if (newKey) {
1350 PK11_FreeSymKey(newKey);
1351 }
1352
1353 if (crv != CKR_OK0x00000000UL) {
1354 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1355 return SECFailure;
1356 }
1357 wrappedKey->len = len;
1358 return SECSuccess;
1359}
1360
1361/*
1362 * this little function uses the Encrypt function to wrap a key, just in
1363 * case we have problems with the wrap implementation for a token.
1364 */
1365static SECStatus
1366pk11_HandWrap(PK11SymKey *wrappingKey, SECItem *param, CK_MECHANISM_TYPE type,
1367 SECItem *inKey, SECItem *outKey)
1368{
1369 PK11SlotInfo *slot;
1370 CK_ULONG len;
1371 SECItem *data;
1372 CK_MECHANISM mech;
1373 PRBool owner = PR_TRUE1;
1374 CK_SESSION_HANDLE session;
1375 CK_RV crv;
1376
1377 slot = wrappingKey->slot;
1378 /* use NULL IV's for wrapping */
1379 mech.mechanism = type;
1380 if (param) {
1381 mech.pParameter = param->data;
1382 mech.ulParameterLen = param->len;
1383 } else {
1384 mech.pParameter = NULL((void*)0);
1385 mech.ulParameterLen = 0;
1386 }
1387 session = pk11_GetNewSession(slot, &owner);
1388 if (!owner || !(slot->isThreadSafe))
1389 PK11_EnterSlotMonitor(slot);
1390 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_EncryptInit(session, &mech,
1391 wrappingKey->objectID);
1392 if (crv != CKR_OK0x00000000UL) {
1393 if (!owner || !(slot->isThreadSafe))
1394 PK11_ExitSlotMonitor(slot);
1395 pk11_CloseSession(slot, session, owner);
1396 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1397 return SECFailure;
1398 }
1399
1400 /* keys are almost always aligned, but if we get this far,
1401 * we've gone above and beyond anyway... */
1402 data = PK11_BlockData(inKey, PK11_GetBlockSize(type, param));
1403 if (data == NULL((void*)0)) {
1404 if (!owner || !(slot->isThreadSafe))
1405 PK11_ExitSlotMonitor(slot);
1406 pk11_CloseSession(slot, session, owner);
1407 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
1408 return SECFailure;
1409 }
1410 len = outKey->len;
1411 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_Encrypt(session, data->data, data->len,
1412 outKey->data, &len);
1413 if (!owner || !(slot->isThreadSafe))
1414 PK11_ExitSlotMonitor(slot);
1415 pk11_CloseSession(slot, session, owner);
1416 SECITEM_FreeItemSECITEM_FreeItem_Util(data, PR_TRUE1);
1417 outKey->len = len;
1418 if (crv != CKR_OK0x00000000UL) {
1419 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1420 return SECFailure;
1421 }
1422 return SECSuccess;
1423}
1424
1425/*
1426 * helper function which moves two keys into a new slot based on the
1427 * desired mechanism.
1428 */
1429static SECStatus
1430pk11_moveTwoKeys(CK_MECHANISM_TYPE mech,
1431 CK_ATTRIBUTE_TYPE preferedOperation,
1432 CK_ATTRIBUTE_TYPE movingOperation,
1433 PK11SymKey *preferedKey, PK11SymKey *movingKey,
1434 PK11SymKey **newPreferedKey, PK11SymKey **newMovingKey)
1435{
1436 PK11SlotInfo *newSlot;
1437 *newMovingKey = NULL((void*)0);
1438 *newPreferedKey = NULL((void*)0);
1439
1440 newSlot = PK11_GetBestSlot(mech, preferedKey->cx);
1441 if (newSlot == NULL((void*)0)) {
1442 return SECFailure;
1443 }
1444 *newMovingKey = pk11_CopyToSlot(newSlot, movingKey->type,
1445 movingOperation, movingKey);
1446 if (*newMovingKey == NULL((void*)0)) {
1447 goto loser;
1448 }
1449 *newPreferedKey = pk11_CopyToSlot(newSlot, preferedKey->type,
1450 preferedOperation, preferedKey);
1451 if (*newPreferedKey == NULL((void*)0)) {
1452 goto loser;
1453 }
1454
1455 PK11_FreeSlot(newSlot);
1456 return SECSuccess;
1457loser:
1458 PK11_FreeSlot(newSlot);
1459 PK11_FreeSymKey(*newMovingKey);
1460 PK11_FreeSymKey(*newPreferedKey);
1461 *newMovingKey = NULL((void*)0);
1462 *newPreferedKey = NULL((void*)0);
1463 return SECFailure;
1464}
1465
1466/*
1467 * To do joint operations, we often need two keys in the same slot.
1468 * Usually the PKCS #11 wrappers handle this correctly (like for PK11_WrapKey),
1469 * but sometimes the wrappers don't know about mechanism specific keys in
1470 * the Mechanism params. This function makes sure the two keys are in the
1471 * same slot by copying one or both of the keys into a common slot. This
1472 * functions makes sure the slot can handle the target mechanism. If the copy
1473 * is warranted, this function will prefer to move the movingKey first, then
1474 * the preferedKey. If the keys are moved, the new keys are returned in
1475 * newMovingKey and/or newPreferedKey. The application is responsible
1476 * for freeing those keys once the operation is complete.
1477 */
1478SECStatus
1479PK11_SymKeysToSameSlot(CK_MECHANISM_TYPE mech,
1480 CK_ATTRIBUTE_TYPE preferedOperation,
1481 CK_ATTRIBUTE_TYPE movingOperation,
1482 PK11SymKey *preferedKey, PK11SymKey *movingKey,
1483 PK11SymKey **newPreferedKey, PK11SymKey **newMovingKey)
1484{
1485 /* usually don't return new keys */
1486 *newMovingKey = NULL((void*)0);
1487 *newPreferedKey = NULL((void*)0);
1488 if (movingKey->slot == preferedKey->slot) {
1489
1490 /* this should be the most common case */
1491 if ((preferedKey->slot != NULL((void*)0)) &&
1492 PK11_DoesMechanism(preferedKey->slot, mech)) {
1493 return SECSuccess;
1494 }
1495
1496 /* we are in the same slot, but it doesn't do the operation,
1497 * move both keys to an appropriate target slot */
1498 return pk11_moveTwoKeys(mech, preferedOperation, movingOperation,
1499 preferedKey, movingKey,
1500 newPreferedKey, newMovingKey);
1501 }
1502
1503 /* keys are in different slot, try moving the moving key to the prefered
1504 * key's slot */
1505 if ((preferedKey->slot != NULL((void*)0)) &&
1506 PK11_DoesMechanism(preferedKey->slot, mech)) {
1507 *newMovingKey = pk11_CopyToSlot(preferedKey->slot, movingKey->type,
1508 movingOperation, movingKey);
1509 if (*newMovingKey != NULL((void*)0)) {
1510 return SECSuccess;
1511 }
1512 }
1513 /* couldn't moving the moving key to the prefered slot, try moving
1514 * the prefered key */
1515 if ((movingKey->slot != NULL((void*)0)) &&
1516 PK11_DoesMechanism(movingKey->slot, mech)) {
1517 *newPreferedKey = pk11_CopyToSlot(movingKey->slot, preferedKey->type,
1518 preferedOperation, preferedKey);
1519 if (*newPreferedKey != NULL((void*)0)) {
1520 return SECSuccess;
1521 }
1522 }
1523 /* Neither succeeded, but that could be that they were not in slots that
1524 * supported the operation, try moving both keys into a common slot that
1525 * can do the operation. */
1526 return pk11_moveTwoKeys(mech, preferedOperation, movingOperation,
1527 preferedKey, movingKey,
1528 newPreferedKey, newMovingKey);
1529}
1530
1531/*
1532 * This function does a symetric based wrap.
1533 */
1534SECStatus
1535PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *param,
1536 PK11SymKey *wrappingKey, PK11SymKey *symKey,
1537 SECItem *wrappedKey)
1538{
1539 PK11SlotInfo *slot;
1540 CK_ULONG len = wrappedKey->len;
1541 PK11SymKey *newSymKey = NULL((void*)0);
1542 PK11SymKey *newWrappingKey = NULL((void*)0);
1543 SECItem *param_save = NULL((void*)0);
1544 CK_MECHANISM mechanism;
1545 PRBool owner = PR_TRUE1;
1546 CK_SESSION_HANDLE session;
1547 CK_RV crv;
1548 SECStatus rv;
1549
1550 /* force the keys into same slot */
1551 rv = PK11_SymKeysToSameSlot(type, CKA_ENCRYPT0x00000104UL, CKA_WRAP0x00000106UL,
1552 symKey, wrappingKey,
1553 &newSymKey, &newWrappingKey);
1554 if (rv != SECSuccess) {
1555 /* Couldn't move the keys as desired, try to hand unwrap if possible */
1556 if (symKey->data.data == NULL((void*)0)) {
1557 rv = PK11_ExtractKeyValue(symKey);
1558 if (rv != SECSuccess) {
1559 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
1560 return SECFailure;
1561 }
1562 }
1563 if (param == NULL((void*)0)) {
1564 param_save = param = PK11_ParamFromIV(type, NULL((void*)0));
1565 }
1566 rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data, wrappedKey);
1567 if (param_save)
1568 SECITEM_FreeItemSECITEM_FreeItem_Util(param_save, PR_TRUE1);
1569 return rv;
1570 }
1571 if (newSymKey) {
1572 symKey = newSymKey;
1573 }
1574 if (newWrappingKey) {
1575 wrappingKey = newWrappingKey;
1576 }
1577
1578 /* at this point both keys are in the same token */
1579 slot = wrappingKey->slot;
1580 mechanism.mechanism = type;
1581 /* use NULL IV's for wrapping */
1582 if (param == NULL((void*)0)) {
1583 param_save = param = PK11_ParamFromIV(type, NULL((void*)0));
1584 }
1585 if (param) {
1586 mechanism.pParameter = param->data;
1587 mechanism.ulParameterLen = param->len;
1588 } else {
1589 mechanism.pParameter = NULL((void*)0);
1590 mechanism.ulParameterLen = 0;
1591 }
1592
1593 len = wrappedKey->len;
1594
1595 session = pk11_GetNewSession(slot, &owner);
1596 if (!owner || !(slot->isThreadSafe))
1597 PK11_EnterSlotMonitor(slot);
1598 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_WrapKey(session, &mechanism,
1599 wrappingKey->objectID, symKey->objectID,
1600 wrappedKey->data, &len);
1601 if (!owner || !(slot->isThreadSafe))
1602 PK11_ExitSlotMonitor(slot);
1603 pk11_CloseSession(slot, session, owner);
1604 rv = SECSuccess;
1605 if (crv != CKR_OK0x00000000UL) {
1606 /* can't wrap it? try hand wrapping it... */
1607 do {
1608 if (symKey->data.data == NULL((void*)0)) {
1609 rv = PK11_ExtractKeyValue(symKey);
1610 if (rv != SECSuccess)
1611 break;
1612 }
1613 rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data,
1614 wrappedKey);
1615 } while (PR_FALSE0);
1616 } else {
1617 wrappedKey->len = len;
1618 }
1619 PK11_FreeSymKey(newSymKey);
1620 PK11_FreeSymKey(newWrappingKey);
1621 if (param_save)
1622 SECITEM_FreeItemSECITEM_FreeItem_Util(param_save, PR_TRUE1);
1623 return rv;
1624}
1625
1626/*
1627 * This Generates a new key based on a symetricKey
1628 */
1629PK11SymKey *
1630PK11_Derive(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, SECItem *param,
1631 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1632 int keySize)
1633{
1634 return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1635 keySize, NULL((void*)0), 0, PR_FALSE0);
1636}
1637
1638PK11SymKey *
1639PK11_DeriveWithFlags(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1640 SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1641 int keySize, CK_FLAGS flags)
1642{
1643 CK_BBOOL ckTrue = CK_TRUE1;
1644 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
1645 unsigned int templateCount;
1646
1647 templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
1648 return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1649 keySize, keyTemplate, templateCount, PR_FALSE0);
1650}
1651
1652PK11SymKey *
1653PK11_DeriveWithFlagsPerm(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1654 SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1655 int keySize, CK_FLAGS flags, PRBool isPerm)
1656{
1657 CK_BBOOL cktrue = CK_TRUE1;
1658 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
1659 CK_ATTRIBUTE *attrs;
1660 unsigned int templateCount = 0;
1661
1662 attrs = keyTemplate;
1663 if (isPerm) {
1664 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(CK_BBOOL));
;
1665 attrs++;
1666 }
1667 templateCount = attrs - keyTemplate;
1668 templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
1669 return PK11_DeriveWithTemplate(baseKey, derive, param, target, operation,
1670 keySize, keyTemplate, templateCount, isPerm);
1671}
1672
1673PK11SymKey *
1674PK11_DeriveWithTemplate(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
1675 SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1676 int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs,
1677 PRBool isPerm)
1678{
1679 PK11SlotInfo *slot = baseKey->slot;
1680 PK11SymKey *symKey;
1681 PK11SymKey *newBaseKey = NULL((void*)0);
1682 CK_BBOOL cktrue = CK_TRUE1;
1683 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
1684 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
1685 CK_ULONG valueLen = 0;
1686 CK_MECHANISM mechanism;
1687 CK_RV crv;
1688#define MAX_ADD_ATTRS 4
1689 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16 + MAX_ADD_ATTRS];
1690#undef MAX_ADD_ATTRS
1691 CK_ATTRIBUTE *attrs = keyTemplate;
1692 CK_SESSION_HANDLE session;
1693 unsigned int templateCount;
1694
1695 if (numAttrs > MAX_TEMPL_ATTRS16) {
1696 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1697 return NULL((void*)0);
1698 }
1699 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
1700 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
1701 * it as a real attribute */
1702 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
1703 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
1704 * etc. Strip out the real attribute here */
1705 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
1706 }
1707
1708 /* first copy caller attributes in. */
1709 for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
1710 *attrs++ = *userAttr++;
1711 }
1712
1713 /* We only add the following attributes to the template if the caller
1714 ** didn't already supply them.
1715 */
1716 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS0x00000000UL)) {
1717 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass)(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof keyClass);
;
1718 attrs++;
1719 }
1720 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE0x00000100UL)) {
1721 keyType = PK11_GetKeyType(target, keySize);
1722 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType)(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof keyType);
;
1723 attrs++;
1724 }
1725 if (keySize > 0 &&
1726 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN0x00000161UL)) {
1727 valueLen = (CK_ULONG)keySize;
1728 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen)(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
valueLen); (attrs)->ulValueLen = (sizeof valueLen);
;
1729 attrs++;
1730 }
1731 if ((operation != CKA_FLAGS_ONLY0) &&
1732 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
1733 PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (sizeof cktrue);
;
1734 attrs++;
1735 }
1736
1737 templateCount = attrs - keyTemplate;
1738 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",1738
))
;
1739
1740 /* move the key to a slot that can do the function */
1741 if (!PK11_DoesMechanism(slot, derive)) {
1742 /* get a new base key & slot */
1743 PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
1744
1745 if (newSlot == NULL((void*)0))
1746 return NULL((void*)0);
1747
1748 newBaseKey = pk11_CopyToSlot(newSlot, derive, CKA_DERIVE0x0000010CUL,
1749 baseKey);
1750 PK11_FreeSlot(newSlot);
1751 if (newBaseKey == NULL((void*)0))
1752 return NULL((void*)0);
1753 baseKey = newBaseKey;
1754 slot = baseKey->slot;
1755 }
1756
1757 /* get our key Structure */
1758 symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE1, baseKey->cx);
1759 if (symKey == NULL((void*)0)) {
1760 return NULL((void*)0);
1761 }
1762
1763 symKey->size = keySize;
1764
1765 mechanism.mechanism = derive;
1766 if (param) {
1767 mechanism.pParameter = param->data;
1768 mechanism.ulParameterLen = param->len;
1769 } else {
1770 mechanism.pParameter = NULL((void*)0);
1771 mechanism.ulParameterLen = 0;
1772 }
1773 symKey->origin = PK11_OriginDerive;
1774
1775 if (isPerm) {
1776 session = PK11_GetRWSession(slot);
1777 } else {
1778 pk11_EnterKeyMonitor(symKey);
1779 session = symKey->session;
1780 }
1781 if (session == CK_INVALID_HANDLE0) {
1782 if (!isPerm)
1783 pk11_ExitKeyMonitor(symKey);
1784 crv = CKR_SESSION_HANDLE_INVALID0x000000B3UL;
1785 } else {
1786 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(session, &mechanism,
1787 baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
1788 if (isPerm) {
1789 PK11_RestoreROSession(slot, session);
1790 } else {
1791 pk11_ExitKeyMonitor(symKey);
1792 }
1793 }
1794 if (newBaseKey)
1795 PK11_FreeSymKey(newBaseKey);
1796 if (crv != CKR_OK0x00000000UL) {
1797 PK11_FreeSymKey(symKey);
1798 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1799 return NULL((void*)0);
1800 }
1801 return symKey;
1802}
1803
1804/* Create a new key by concatenating base and data
1805 */
1806static PK11SymKey *
1807pk11_ConcatenateBaseAndData(PK11SymKey *base,
1808 CK_BYTE *data, CK_ULONG dataLen, CK_MECHANISM_TYPE target,
1809 CK_ATTRIBUTE_TYPE operation)
1810{
1811 CK_KEY_DERIVATION_STRING_DATA mechParams;
1812 SECItem param;
1813
1814 if (base == NULL((void*)0)) {
1815 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1816 return NULL((void*)0);
1817 }
1818
1819 mechParams.pData = data;
1820 mechParams.ulLen = dataLen;
1821 param.data = (unsigned char *)&mechParams;
1822 param.len = sizeof(CK_KEY_DERIVATION_STRING_DATA);
1823
1824 return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_DATA0x00000362UL,
1825 &param, target, operation, 0);
1826}
1827
1828/* Create a new key by concatenating base and key
1829 */
1830static PK11SymKey *
1831pk11_ConcatenateBaseAndKey(PK11SymKey *base,
1832 PK11SymKey *key, CK_MECHANISM_TYPE target,
1833 CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1834{
1835 SECItem param;
1836
1837 if ((base == NULL((void*)0)) || (key == NULL((void*)0))) {
1838 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1839 return NULL((void*)0);
1840 }
1841
1842 param.data = (unsigned char *)&(key->objectID);
1843 param.len = sizeof(CK_OBJECT_HANDLE);
1844
1845 return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
1846 &param, target, operation, keySize);
1847}
1848
1849PK11SymKey *
1850PK11_ConcatSymKeys(PK11SymKey *left, PK11SymKey *right, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation)
1851{
1852 PK11SymKey *out = NULL((void*)0);
1853 PK11SymKey *copyOfLeft = NULL((void*)0);
1854 PK11SymKey *copyOfRight = NULL((void*)0);
1855
1856 if ((left == NULL((void*)0)) || (right == NULL((void*)0))) {
1857 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1858 return NULL((void*)0);
1859 }
1860
1861 SECStatus rv = PK11_SymKeysToSameSlot(CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
1862 CKA_DERIVE0x0000010CUL, CKA_DERIVE0x0000010CUL, left, right,
1863 &copyOfLeft, &copyOfRight);
1864 if (rv != SECSuccess) {
1865 /* error code already set */
1866 return NULL((void*)0);
1867 }
1868
1869 out = pk11_ConcatenateBaseAndKey(copyOfLeft ? copyOfLeft : left, copyOfRight ? copyOfRight : right, target, operation, 0);
1870 PK11_FreeSymKey(copyOfLeft);
1871 PK11_FreeSymKey(copyOfRight);
1872 return out;
1873}
1874
1875/* Create a new key whose value is the hash of tobehashed.
1876 * type is the mechanism for the derived key.
1877 */
1878static PK11SymKey *
1879pk11_HashKeyDerivation(PK11SymKey *toBeHashed,
1880 CK_MECHANISM_TYPE hashMechanism, CK_MECHANISM_TYPE target,
1881 CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1882{
1883 return PK11_Derive(toBeHashed, hashMechanism, NULL((void*)0), target, operation, keySize);
1884}
1885
1886/* This function implements the ANSI X9.63 key derivation function
1887 */
1888static PK11SymKey *
1889pk11_ANSIX963Derive(PK11SymKey *sharedSecret,
1890 CK_EC_KDF_TYPE kdf, SECItem *sharedData,
1891 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1892 CK_ULONG keySize)
1893{
1894 CK_KEY_TYPE keyType;
1895 CK_MECHANISM_TYPE hashMechanism, mechanismArray[4];
1896 CK_ULONG derivedKeySize, HashLen, counter, maxCounter, bufferLen;
1897 CK_ULONG SharedInfoLen;
1898 CK_BYTE *buffer = NULL((void*)0);
1899 PK11SymKey *toBeHashed, *hashOutput;
1900 PK11SymKey *newSharedSecret = NULL((void*)0);
1901 PK11SymKey *oldIntermediateResult, *intermediateResult = NULL((void*)0);
1902
1903 if (sharedSecret == NULL((void*)0)) {
1904 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1905 return NULL((void*)0);
1906 }
1907
1908 switch (kdf) {
1909 case CKD_SHA1_KDF0x00000002UL:
1910 HashLen = SHA1_LENGTH20;
1911 hashMechanism = CKM_SHA1_KEY_DERIVATION0x00000392UL;
1912 break;
1913 case CKD_SHA224_KDF0x00000005UL:
1914 HashLen = SHA224_LENGTH28;
1915 hashMechanism = CKM_SHA224_KEY_DERIVATION0x00000396UL;
1916 break;
1917 case CKD_SHA256_KDF0x00000006UL:
1918 HashLen = SHA256_LENGTH32;
1919 hashMechanism = CKM_SHA256_KEY_DERIVATION0x00000393UL;
1920 break;
1921 case CKD_SHA384_KDF0x00000007UL:
1922 HashLen = SHA384_LENGTH48;
1923 hashMechanism = CKM_SHA384_KEY_DERIVATION0x00000394UL;
1924 break;
1925 case CKD_SHA512_KDF0x00000008UL:
1926 HashLen = SHA512_LENGTH64;
1927 hashMechanism = CKM_SHA512_KEY_DERIVATION0x00000395UL;
1928 break;
1929 default:
1930 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1931 return NULL((void*)0);
1932 }
1933
1934 derivedKeySize = keySize;
1935 if (derivedKeySize == 0) {
1936 keyType = PK11_GetKeyType(target, keySize);
1937 derivedKeySize = pk11_GetPredefinedKeyLength(keyType);
1938 if (derivedKeySize == 0) {
1939 derivedKeySize = HashLen;
1940 }
1941 }
1942
1943 /* Check that key_len isn't too long. The maximum key length could be
1944 * greatly increased if the code below did not limit the 4-byte counter
1945 * to a maximum value of 255. */
1946 if (derivedKeySize > 254 * HashLen) {
1947 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1948 return NULL((void*)0);
1949 }
1950
1951 maxCounter = derivedKeySize / HashLen;
1952 if (derivedKeySize > maxCounter * HashLen)
1953 maxCounter++;
1954
1955 if ((sharedData == NULL((void*)0)) || (sharedData->data == NULL((void*)0)))
1956 SharedInfoLen = 0;
1957 else
1958 SharedInfoLen = sharedData->len;
1959
1960 if (SharedInfoLen > PR_UINT32_MAX4294967295U - 4) {
1961 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1962 return NULL((void*)0);
1963 }
1964
1965 bufferLen = SharedInfoLen + 4;
1966
1967 /* Populate buffer with Counter || sharedData
1968 * where Counter is 0x00000001. */
1969 buffer = (unsigned char *)PORT_AllocPORT_Alloc_Util(bufferLen);
1970 if (buffer == NULL((void*)0)) {
1971 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
1972 return NULL((void*)0);
1973 }
1974
1975 buffer[0] = 0;
1976 buffer[1] = 0;
1977 buffer[2] = 0;
1978 buffer[3] = 1;
1979 if (SharedInfoLen > 0) {
1980 PORT_Memcpymemcpy(&buffer[4], sharedData->data, SharedInfoLen);
1981 }
1982
1983 /* Look for a slot that supports the mechanisms needed
1984 * to implement the ANSI X9.63 KDF as well as the
1985 * target mechanism.
1986 */
1987 mechanismArray[0] = CKM_CONCATENATE_BASE_AND_DATA0x00000362UL;
1988 mechanismArray[1] = hashMechanism;
1989 mechanismArray[2] = CKM_CONCATENATE_BASE_AND_KEY0x00000360UL;
1990 mechanismArray[3] = target;
1991
1992 newSharedSecret = pk11_ForceSlotMultiple(sharedSecret,
1993 mechanismArray, 4, operation);
1994 if (newSharedSecret != NULL((void*)0)) {
1995 sharedSecret = newSharedSecret;
1996 }
1997
1998 for (counter = 1; counter <= maxCounter; counter++) {
1999 /* Concatenate shared_secret and buffer */
2000 toBeHashed = pk11_ConcatenateBaseAndData(sharedSecret, buffer,
2001 bufferLen, hashMechanism, operation);
2002 if (toBeHashed == NULL((void*)0)) {
2003 goto loser;
2004 }
2005
2006 /* Hash value */
2007 if (maxCounter == 1) {
2008 /* In this case the length of the key to be derived is
2009 * less than or equal to the length of the hash output.
2010 * So, the output of the hash operation will be the
2011 * dervied key. */
2012 hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2013 target, operation, keySize);
2014 } else {
2015 /* In this case, the output of the hash operation will be
2016 * concatenated with other data to create the derived key. */
2017 hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2018 CKM_CONCATENATE_BASE_AND_KEY0x00000360UL, operation, 0);
2019 }
2020 PK11_FreeSymKey(toBeHashed);
2021 if (hashOutput == NULL((void*)0)) {
2022 goto loser;
2023 }
2024
2025 /* Append result to intermediate result, if necessary */
2026 oldIntermediateResult = intermediateResult;
2027
2028 if (oldIntermediateResult == NULL((void*)0)) {
2029 intermediateResult = hashOutput;
2030 } else {
2031 if (counter == maxCounter) {
2032 /* This is the final concatenation, and so the output
2033 * will be the derived key. */
2034 intermediateResult =
2035 pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2036 hashOutput, target, operation, keySize);
2037 } else {
2038 /* The output of this concatenation will be concatenated
2039 * with other data to create the derived key. */
2040 intermediateResult =
2041 pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2042 hashOutput, CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
2043 operation, 0);
2044 }
2045
2046 PK11_FreeSymKey(hashOutput);
2047 PK11_FreeSymKey(oldIntermediateResult);
2048 if (intermediateResult == NULL((void*)0)) {
2049 goto loser;
2050 }
2051 }
2052
2053 /* Increment counter (assumes maxCounter < 255) */
2054 buffer[3]++;
2055 }
2056
2057 PORT_ZFreePORT_ZFree_Util(buffer, bufferLen);
2058 if (newSharedSecret != NULL((void*)0))
2059 PK11_FreeSymKey(newSharedSecret);
2060 return intermediateResult;
2061
2062loser:
2063 PORT_ZFreePORT_ZFree_Util(buffer, bufferLen);
2064 if (newSharedSecret != NULL((void*)0))
2065 PK11_FreeSymKey(newSharedSecret);
2066 if (intermediateResult != NULL((void*)0))
2067 PK11_FreeSymKey(intermediateResult);
2068 return NULL((void*)0);
2069}
2070
2071/*
2072 * This regenerate a public key from a private key. This function is currently
2073 * NSS private. If we want to make it public, we need to add and optional
2074 * template or at least flags (a.la. PK11_DeriveWithFlags).
2075 */
2076CK_OBJECT_HANDLE
2077PK11_DerivePubKeyFromPrivKey(SECKEYPrivateKey *privKey)
2078{
2079 PK11SlotInfo *slot = privKey->pkcs11Slot;
2080 CK_MECHANISM mechanism;
2081 CK_OBJECT_HANDLE objectID = CK_INVALID_HANDLE0;
2082 CK_RV crv;
2083
2084 mechanism.mechanism = CKM_NSS_PUB_FROM_PRIV((0x80000000UL | 0x4E534350) + 40);
2085 mechanism.pParameter = NULL((void*)0);
2086 mechanism.ulParameterLen = 0;
2087
2088 PK11_EnterSlotMonitor(slot);
2089 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(slot->session, &mechanism,
2090 privKey->pkcs11ID, NULL((void*)0), 0,
2091 &objectID);
2092 PK11_ExitSlotMonitor(slot);
2093 if (crv != CKR_OK0x00000000UL) {
2094 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2095 return CK_INVALID_HANDLE0;
2096 }
2097 return objectID;
2098}
2099
2100/*
2101 * This Generates a wrapping key based on a privateKey, publicKey, and two
2102 * random numbers. For Mail usage RandomB should be NULL. In the Sender's
2103 * case RandomA is generate, otherwise it is passed.
2104 */
2105PK11SymKey *
2106PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2107 PRBool isSender, SECItem *randomA, SECItem *randomB,
2108 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2109 CK_ATTRIBUTE_TYPE operation, int keySize, void *wincx)
2110{
2111 PK11SlotInfo *slot = privKey->pkcs11Slot;
2112 CK_MECHANISM mechanism;
2113 PK11SymKey *symKey;
2114 CK_RV crv;
2115
2116 /* get our key Structure */
2117 symKey = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, wincx);
2118 if (symKey == NULL((void*)0)) {
2119 return NULL((void*)0);
2120 }
2121
2122 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2123 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2124 * it as a real attribute */
2125 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2126 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2127 * etc. Strip out the real attribute here */
2128 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2129 }
2130
2131 symKey->origin = PK11_OriginDerive;
2132
2133 switch (privKey->keyType) {
2134 case keaKey:
2135 case fortezzaKey: {
2136 static unsigned char rb_email[128] = { 0 };
2137 CK_KEA_DERIVE_PARAMS param;
2138 param.isSender = (CK_BBOOL)isSender;
2139 param.ulRandomLen = randomA->len;
2140 param.pRandomA = randomA->data;
2141 param.pRandomB = rb_email;
2142 param.pRandomB[127] = 1;
2143 if (randomB)
2144 param.pRandomB = randomB->data;
2145 if (pubKey->keyType == fortezzaKey) {
2146 param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2147 param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2148 } else {
2149 /* assert type == keaKey */
2150 /* XXX change to match key key types */
2151 param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2152 param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2153 }
2154
2155 mechanism.mechanism = derive;
2156 mechanism.pParameter = &param;
2157 mechanism.ulParameterLen = sizeof(param);
2158
2159 /* get a new symKey structure */
2160 pk11_EnterKeyMonitor(symKey);
2161 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2162 privKey->pkcs11ID, NULL((void*)0), 0,
2163 &symKey->objectID);
2164 pk11_ExitKeyMonitor(symKey);
2165 if (crv == CKR_OK0x00000000UL)
2166 return symKey;
2167 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2168 } break;
2169 case dhKey: {
2170 CK_BBOOL cktrue = CK_TRUE1;
2171 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2172 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2173 CK_ULONG key_size = 0;
2174 CK_ATTRIBUTE keyTemplate[4];
2175 int templateCount;
2176 CK_ATTRIBUTE *attrs = keyTemplate;
2177
2178 if (pubKey->keyType != dhKey) {
2179 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2180 break;
2181 }
2182
2183 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2184 attrs++;
2185 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2186 attrs++;
2187 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2188 attrs++;
2189 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2190 attrs++;
2191 templateCount = attrs - keyTemplate;
2192 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",2192
))
;
2193
2194 keyType = PK11_GetKeyType(target, keySize);
2195 key_size = keySize;
2196 symKey->size = keySize;
2197 if (key_size == 0)
2198 templateCount--;
2199
2200 mechanism.mechanism = derive;
2201
2202 /* we can undefine these when we define diffie-helman keys */
2203
2204 mechanism.pParameter = pubKey->u.dh.publicValue.data;
2205 mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
2206
2207 pk11_EnterKeyMonitor(symKey);
2208 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2209 privKey->pkcs11ID, keyTemplate,
2210 templateCount, &symKey->objectID);
2211 pk11_ExitKeyMonitor(symKey);
2212 if (crv == CKR_OK0x00000000UL)
2213 return symKey;
2214 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2215 } break;
2216 case ecKey: {
2217 CK_BBOOL cktrue = CK_TRUE1;
2218 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2219 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2220 CK_ULONG key_size = 0;
2221 CK_ATTRIBUTE keyTemplate[4];
2222 int templateCount;
2223 CK_ATTRIBUTE *attrs = keyTemplate;
2224 CK_ECDH1_DERIVE_PARAMS *mechParams = NULL((void*)0);
2225
2226 if (pubKey->keyType != ecKey) {
2227 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2228 break;
2229 }
2230
2231 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2232 attrs++;
2233 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2234 attrs++;
2235 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2236 attrs++;
2237 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2238 attrs++;
2239 templateCount = attrs - keyTemplate;
2240 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",2240
))
;
2241
2242 keyType = PK11_GetKeyType(target, keySize);
2243 key_size = keySize;
2244 if (key_size == 0) {
2245 if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2246 templateCount--;
2247 } else {
2248 /* sigh, some tokens can't figure this out and require
2249 * CKA_VALUE_LEN to be set */
2250 key_size = SHA1_LENGTH20;
2251 }
2252 }
2253 symKey->size = key_size;
2254
2255 mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS)(CK_ECDH1_DERIVE_PARAMS *)PORT_ZAlloc_Util(sizeof(CK_ECDH1_DERIVE_PARAMS
))
;
2256 mechParams->kdf = CKD_SHA1_KDF0x00000002UL;
2257 mechParams->ulSharedDataLen = 0;
2258 mechParams->pSharedData = NULL((void*)0);
2259 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2260 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2261
2262 mechanism.mechanism = derive;
2263 mechanism.pParameter = mechParams;
2264 mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2265
2266 pk11_EnterKeyMonitor(symKey);
2267 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2268 &mechanism, privKey->pkcs11ID, keyTemplate,
2269 templateCount, &symKey->objectID);
2270 pk11_ExitKeyMonitor(symKey);
2271
2272 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2273 * try this again with and encoded public key */
2274 if (crv != CKR_OK0x00000000UL && pk11_ECGetPubkeyEncoding(pubKey) != ECPoint_XOnly) {
2275 SECItem *pubValue = SEC_ASN1EncodeItemSEC_ASN1EncodeItem_Util(NULL((void*)0), NULL((void*)0),
2276 &pubKey->u.ec.publicValue,
2277 SEC_ASN1_GET(SEC_OctetStringTemplate)SEC_OctetStringTemplate_Util);
2278 if (pubValue == NULL((void*)0)) {
2279 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2280 break;
2281 }
2282 mechParams->ulPublicDataLen = pubValue->len;
2283 mechParams->pPublicData = pubValue->data;
2284
2285 pk11_EnterKeyMonitor(symKey);
2286 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2287 &mechanism, privKey->pkcs11ID, keyTemplate,
2288 templateCount, &symKey->objectID);
2289 pk11_ExitKeyMonitor(symKey);
2290
2291 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2292 }
2293
2294 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2295
2296 if (crv == CKR_OK0x00000000UL)
2297 return symKey;
2298 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2299 }
2300 /* most keys are not KEA keys, so assume they are bad if they
2301 * are not handled explicitly */
2302 default:
2303 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2304 break;
2305 }
2306
2307 PK11_FreeSymKey(symKey);
2308 return NULL((void*)0);
2309}
2310
2311/* Test for curves that are known to use a special encoding.
2312 * Extend this function when additional curves are added. */
2313static ECPointEncoding
2314pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey)
2315{
2316 SECItem oid;
2317 SECStatus rv;
2318 PORTCheapArenaPool tmpArena;
2319 ECPointEncoding encoding = ECPoint_Undefined;
2320
2321 PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE(2048));
2322
2323 /* decode the OID tag */
2324 rv = SEC_QuickDERDecodeItemSEC_QuickDERDecodeItem_Util(&tmpArena.arena, &oid,
2325 SEC_ASN1_GET(SEC_ObjectIDTemplate)SEC_ObjectIDTemplate_Util,
2326 &pubKey->u.ec.DEREncodedParams);
2327 if (rv == SECSuccess) {
2328 SECOidTag tag = SECOID_FindOIDTagSECOID_FindOIDTag_Util(&oid);
2329 switch (tag) {
2330 case SEC_OID_X25519:
2331 case SEC_OID_CURVE25519:
2332 encoding = ECPoint_XOnly;
2333 break;
2334 case SEC_OID_SECG_EC_SECP256R1SEC_OID_ANSIX962_EC_PRIME256V1:
2335 case SEC_OID_SECG_EC_SECP384R1:
2336 case SEC_OID_SECG_EC_SECP521R1:
2337 default:
2338 /* unknown curve, default to uncompressed */
2339 encoding = ECPoint_Uncompressed;
2340 }
2341 }
2342 PORT_DestroyCheapArena(&tmpArena);
2343 return encoding;
2344}
2345
2346/* Returns the size of the public key, or 0 if there
2347 * is an error. */
2348static CK_ULONG
2349pk11_ECPubKeySize(SECKEYPublicKey *pubKey)
2350{
2351 SECItem *publicValue = &pubKey->u.ec.publicValue;
2352
2353 ECPointEncoding encoding = pk11_ECGetPubkeyEncoding(pubKey);
2354 if (encoding == ECPoint_XOnly) {
2355 return publicValue->len;
2356 }
2357 if (encoding == ECPoint_Uncompressed) {
2358 /* key encoded in uncompressed form */
2359 return ((publicValue->len - 1) / 2);
2360 }
2361 /* key encoding not recognized */
2362 return 0;
2363}
2364
2365static PK11SymKey *
2366pk11_PubDeriveECKeyWithKDF(
2367 SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2368 PRBool isSender, SECItem *randomA, SECItem *randomB,
2369 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2370 CK_ATTRIBUTE_TYPE operation, int keySize,
2371 CK_ULONG kdf, SECItem *sharedData, void *wincx)
2372{
2373 PK11SlotInfo *slot = privKey->pkcs11Slot;
2374 PK11SymKey *symKey;
2375 PK11SymKey *SharedSecret;
2376 CK_MECHANISM mechanism;
2377 CK_RV crv;
2378 CK_BBOOL cktrue = CK_TRUE1;
2379 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2380 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2381 CK_ULONG key_size = 0;
2382 CK_ATTRIBUTE keyTemplate[4];
2383 int templateCount;
2384 CK_ATTRIBUTE *attrs = keyTemplate;
2385 CK_ECDH1_DERIVE_PARAMS *mechParams = NULL((void*)0);
2386
2387 if (pubKey->keyType != ecKey && pubKey->keyType != ecMontKey) {
2388 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2389 return NULL((void*)0);
2390 }
2391 if ((kdf != CKD_NULL0x00000001UL) && (kdf != CKD_SHA1_KDF0x00000002UL) &&
2392 (kdf != CKD_SHA224_KDF0x00000005UL) && (kdf != CKD_SHA256_KDF0x00000006UL) &&
2393 (kdf != CKD_SHA384_KDF0x00000007UL) && (kdf != CKD_SHA512_KDF0x00000008UL)) {
2394 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ALGORITHM);
2395 return NULL((void*)0);
2396 }
2397
2398 /* get our key Structure */
2399 symKey = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, wincx);
2400 if (symKey == NULL((void*)0)) {
2401 return NULL((void*)0);
2402 }
2403 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2404 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2405 * it as a real attribute */
2406 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2407 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2408 * etc. Strip out the real attribute here */
2409 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2410 }
2411
2412 symKey->origin = PK11_OriginDerive;
2413
2414 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2415 attrs++;
2416 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2417 attrs++;
2418 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2419 attrs++;
2420 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2421 attrs++;
2422 templateCount = attrs - keyTemplate;
2423 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",2423
))
;
2424
2425 keyType = PK11_GetKeyType(target, keySize);
2426 key_size = keySize;
2427 if (key_size == 0) {
2428 if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2429 templateCount--;
2430 } else {
2431 /* sigh, some tokens can't figure this out and require
2432 * CKA_VALUE_LEN to be set */
2433 switch (kdf) {
2434 case CKD_NULL0x00000001UL:
2435 key_size = pk11_ECPubKeySize(pubKey);
2436 if (key_size == 0) {
2437 PK11_FreeSymKey(symKey);
2438 return NULL((void*)0);
2439 }
2440 break;
2441 case CKD_SHA1_KDF0x00000002UL:
2442 key_size = SHA1_LENGTH20;
2443 break;
2444 case CKD_SHA224_KDF0x00000005UL:
2445 key_size = SHA224_LENGTH28;
2446 break;
2447 case CKD_SHA256_KDF0x00000006UL:
2448 key_size = SHA256_LENGTH32;
2449 break;
2450 case CKD_SHA384_KDF0x00000007UL:
2451 key_size = SHA384_LENGTH48;
2452 break;
2453 case CKD_SHA512_KDF0x00000008UL:
2454 key_size = SHA512_LENGTH64;
2455 break;
2456 default:
2457 PORT_AssertNotReached("Invalid CKD")PR_Assert("Invalid CKD","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,2457)
;
2458 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ALGORITHM);
2459 PK11_FreeSymKey(symKey);
2460 return NULL((void*)0);
2461 }
2462 }
2463 }
2464 symKey->size = key_size;
2465
2466 mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS)(CK_ECDH1_DERIVE_PARAMS *)PORT_ZAlloc_Util(sizeof(CK_ECDH1_DERIVE_PARAMS
))
;
2467 if (!mechParams) {
2468 PK11_FreeSymKey(symKey);
2469 return NULL((void*)0);
2470 }
2471 mechParams->kdf = kdf;
2472 if (sharedData == NULL((void*)0)) {
2473 mechParams->ulSharedDataLen = 0;
2474 mechParams->pSharedData = NULL((void*)0);
2475 } else {
2476 mechParams->ulSharedDataLen = sharedData->len;
2477 mechParams->pSharedData = sharedData->data;
2478 }
2479 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2480 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2481
2482 mechanism.mechanism = derive;
2483 mechanism.pParameter = mechParams;
2484 mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2485
2486 pk11_EnterKeyMonitor(symKey);
2487 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2488 privKey->pkcs11ID, keyTemplate,
2489 templateCount, &symKey->objectID);
2490 pk11_ExitKeyMonitor(symKey);
2491
2492 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2493 * try this again with an encoded public key */
2494 if (crv != CKR_OK0x00000000UL) {
2495 /* For curves that only use X as public value and no encoding we don't
2496 * have to try again. (Currently only Curve25519) */
2497 if (pk11_ECGetPubkeyEncoding(pubKey) == ECPoint_XOnly) {
2498 goto loser;
2499 }
2500 SECItem *pubValue = SEC_ASN1EncodeItemSEC_ASN1EncodeItem_Util(NULL((void*)0), NULL((void*)0),
2501 &pubKey->u.ec.publicValue,
2502 SEC_ASN1_GET(SEC_OctetStringTemplate)SEC_OctetStringTemplate_Util);
2503 if (pubValue == NULL((void*)0)) {
2504 goto loser;
2505 }
2506 mechParams->ulPublicDataLen = pubValue->len;
2507 mechParams->pPublicData = pubValue->data;
2508
2509 pk11_EnterKeyMonitor(symKey);
2510 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2511 &mechanism, privKey->pkcs11ID, keyTemplate,
2512 templateCount, &symKey->objectID);
2513 pk11_ExitKeyMonitor(symKey);
2514
2515 if ((crv != CKR_OK0x00000000UL) && (kdf != CKD_NULL0x00000001UL)) {
2516 /* Some PKCS #11 libraries cannot perform the key derivation
2517 * function. So, try calling C_DeriveKey with CKD_NULL and then
2518 * performing the KDF separately.
2519 */
2520 CK_ULONG derivedKeySize = key_size;
2521
2522 keyType = CKK_GENERIC_SECRET0x00000010UL;
2523 key_size = pk11_ECPubKeySize(pubKey);
2524 if (key_size == 0) {
2525 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2526 goto loser;
2527 }
2528 SharedSecret = symKey;
2529 SharedSecret->size = key_size;
2530
2531 mechParams->kdf = CKD_NULL0x00000001UL;
2532 mechParams->ulSharedDataLen = 0;
2533 mechParams->pSharedData = NULL((void*)0);
2534 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2535 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2536
2537 pk11_EnterKeyMonitor(SharedSecret);
2538 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(SharedSecret->session,
2539 &mechanism, privKey->pkcs11ID, keyTemplate,
2540 templateCount, &SharedSecret->objectID);
2541 pk11_ExitKeyMonitor(SharedSecret);
2542
2543 if (crv != CKR_OK0x00000000UL) {
2544 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2545 * try this one final time with an encoded public key */
2546 mechParams->ulPublicDataLen = pubValue->len;
2547 mechParams->pPublicData = pubValue->data;
2548
2549 pk11_EnterKeyMonitor(SharedSecret);
2550 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(SharedSecret->session,
2551 &mechanism, privKey->pkcs11ID, keyTemplate,
2552 templateCount, &SharedSecret->objectID);
2553 pk11_ExitKeyMonitor(SharedSecret);
2554 }
2555
2556 /* Perform KDF. */
2557 if (crv == CKR_OK0x00000000UL) {
2558 symKey = pk11_ANSIX963Derive(SharedSecret, kdf,
2559 sharedData, target, operation,
2560 derivedKeySize);
2561 PK11_FreeSymKey(SharedSecret);
2562 if (symKey == NULL((void*)0)) {
2563 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2564 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2565 return NULL((void*)0);
2566 }
2567 }
2568 }
2569 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2570 }
2571
2572loser:
2573 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2574
2575 if (crv != CKR_OK0x00000000UL) {
2576 PK11_FreeSymKey(symKey);
2577 symKey = NULL((void*)0);
2578 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2579 }
2580 return symKey;
2581}
2582
2583PK11SymKey *
2584PK11_PubDeriveWithKDF(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2585 PRBool isSender, SECItem *randomA, SECItem *randomB,
2586 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2587 CK_ATTRIBUTE_TYPE operation, int keySize,
2588 CK_ULONG kdf, SECItem *sharedData, void *wincx)
2589{
2590
2591 switch (privKey->keyType) {
2592 case keaKey:
2593 case fortezzaKey:
2594 case dhKey:
2595 return PK11_PubDerive(privKey, pubKey, isSender, randomA, randomB,
2596 derive, target, operation, keySize, wincx);
2597 case ecKey:
2598 case ecMontKey:
2599 return pk11_PubDeriveECKeyWithKDF(privKey, pubKey, isSender,
2600 randomA, randomB, derive, target,
2601 operation, keySize,
2602 kdf, sharedData, wincx);
2603 default:
2604 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2605 break;
2606 }
2607
2608 return NULL((void*)0);
2609}
2610
2611/*
2612 * this little function uses the Decrypt function to unwrap a key, just in
2613 * case we are having problem with unwrap. NOTE: The key size may
2614 * not be preserved properly for some algorithms!
2615 */
2616static PK11SymKey *
2617pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2618 CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target,
2619 CK_ATTRIBUTE *keyTemplate, unsigned int templateCount,
2620 int key_size, void *wincx, CK_RV *crvp, PRBool isPerm)
2621{
2622 CK_ULONG len;
2623 SECItem outKey;
2624 PK11SymKey *symKey;
2625 CK_RV crv;
2626 PRBool owner = PR_TRUE1;
2627 CK_SESSION_HANDLE session;
2628
2629 /* remove any VALUE_LEN parameters */
2630 if (keyTemplate[templateCount - 1].type == CKA_VALUE_LEN0x00000161UL) {
2631 templateCount--;
2632 }
2633
2634 if (key_size != 0 && (CK_ULONG)key_size > inKey->len) {
2635 PORT_SetErrorPORT_SetError_Util(PK11_MapError(CKR_UNWRAPPING_KEY_SIZE_RANGE0x000000F1UL));
2636 if (crvp)
2637 *crvp = CKR_UNWRAPPING_KEY_SIZE_RANGE0x000000F1UL;
2638 return NULL((void*)0);
2639 }
2640
2641 /* keys are almost always aligned, but if we get this far,
2642 * we've gone above and beyond anyway... */
2643 outKey.data = (unsigned char *)PORT_ZAllocPORT_ZAlloc_Util(inKey->len);
2644 if (outKey.data == NULL((void*)0)) {
2645 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
2646 if (crvp)
2647 *crvp = CKR_HOST_MEMORY0x00000002UL;
2648 return NULL((void*)0);
2649 }
2650 len = inKey->len;
2651
2652 /* use NULL IV's for wrapping */
2653 session = pk11_GetNewSession(slot, &owner);
2654 if (!owner || !(slot->isThreadSafe))
2655 PK11_EnterSlotMonitor(slot);
2656 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DecryptInit(session, mech, wrappingKey);
2657 if (crv != CKR_OK0x00000000UL) {
2658 if (!owner || !(slot->isThreadSafe))
2659 PK11_ExitSlotMonitor(slot);
2660 pk11_CloseSession(slot, session, owner);
2661 PORT_FreePORT_Free_Util(outKey.data);
2662 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2663 if (crvp)
2664 *crvp = crv;
2665 return NULL((void*)0);
2666 }
2667 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_Decrypt(session, inKey->data, inKey->len,
2668 outKey.data, &len);
2669 if (!owner || !(slot->isThreadSafe))
2670 PK11_ExitSlotMonitor(slot);
2671 pk11_CloseSession(slot, session, owner);
2672 if (crv != CKR_OK0x00000000UL) {
2673 PORT_FreePORT_Free_Util(outKey.data);
2674 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2675 if (crvp)
2676 *crvp = crv;
2677 return NULL((void*)0);
2678 }
2679
2680 outKey.len = (key_size == 0) ? len : key_size;
2681 outKey.type = siBuffer;
2682
2683 if (PK11_DoesMechanism(slot, target)) {
2684 symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2685 isPerm, keyTemplate,
2686 templateCount, &outKey, wincx);
2687 } else {
2688 slot = PK11_GetBestSlot(target, wincx);
2689 if (slot == NULL((void*)0)) {
2690 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
2691 PORT_FreePORT_Free_Util(outKey.data);
2692 if (crvp)
2693 *crvp = CKR_DEVICE_ERROR0x00000030UL;
2694 return NULL((void*)0);
2695 }
2696 symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2697 isPerm, keyTemplate,
2698 templateCount, &outKey, wincx);
2699 PK11_FreeSlot(slot);
2700 }
2701 PORT_FreePORT_Free_Util(outKey.data);
2702
2703 if (crvp)
2704 *crvp = symKey ? CKR_OK0x00000000UL : CKR_DEVICE_ERROR0x00000030UL;
2705 return symKey;
2706}
2707
2708/*
2709 * The wrap/unwrap function is pretty much the same for private and
2710 * public keys. It's just getting the Object ID and slot right. This is
2711 * the combined unwrap function.
2712 */
2713static PK11SymKey *
2714pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2715 CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
2716 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
2717 void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs, PRBool isPerm)
2718{
2719 PK11SymKey *symKey;
2720 SECItem *param_free = NULL((void*)0);
2721 CK_BBOOL cktrue = CK_TRUE1;
2722 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2723 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2724 CK_ULONG valueLen = 0;
2725 CK_MECHANISM mechanism;
2726 CK_SESSION_HANDLE rwsession;
2727 CK_RV crv;
2728 CK_MECHANISM_INFO mechanism_info;
2729#define MAX_ADD_ATTRS 4
2730 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16 + MAX_ADD_ATTRS];
2731#undef MAX_ADD_ATTRS
2732 CK_ATTRIBUTE *attrs = keyTemplate;
2733 unsigned int templateCount;
2734
2735 if (numAttrs > MAX_TEMPL_ATTRS16) {
2736 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
2737 return NULL((void*)0);
2738 }
2739 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2740 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2741 * it as a real attribute */
2742 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2743 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2744 * etc. Strip out the real attribute here */
2745 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2746 }
2747
2748 /* first copy caller attributes in. */
2749 for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
2750 *attrs++ = *userAttr++;
2751 }
2752
2753 /* We only add the following attributes to the template if the caller
2754 ** didn't already supply them.
2755 */
2756 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS0x00000000UL)) {
2757 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass)(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof keyClass);
;
2758 attrs++;
2759 }
2760 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE0x00000100UL)) {
2761 keyType = PK11_GetKeyType(target, keySize);
2762 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType)(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof keyType);
;
2763 attrs++;
2764 }
2765 if ((operation != CKA_FLAGS_ONLY0) &&
2766 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
2767 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2768 attrs++;
2769 }
2770
2771 /*
2772 * must be last in case we need to use this template to import the key
2773 */
2774 if (keySize > 0 &&
2775 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN0x00000161UL)) {
2776 valueLen = (CK_ULONG)keySize;
2777 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen)(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
valueLen); (attrs)->ulValueLen = (sizeof valueLen);
;
2778 attrs++;
2779 }
2780
2781 templateCount = attrs - keyTemplate;
2782 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",2782
))
;
2783
2784 /* find out if we can do wrap directly. Because the RSA case if *very*
2785 * common, cache the results for it. */
2786 if ((wrapType == CKM_RSA_PKCS0x00000001UL) && (slot->hasRSAInfo)) {
2787 mechanism_info.flags = slot->RSAInfoFlags;
2788 } else {
2789 if (!slot->isThreadSafe)
2790 PK11_EnterSlotMonitor(slot);
2791 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetMechanismInfo(slot->slotID, wrapType,
2792 &mechanism_info);
2793 if (!slot->isThreadSafe)
2794 PK11_ExitSlotMonitor(slot);
2795 if (crv != CKR_OK0x00000000UL) {
2796 mechanism_info.flags = 0;
2797 }
2798 if (wrapType == CKM_RSA_PKCS0x00000001UL) {
2799 slot->RSAInfoFlags = mechanism_info.flags;
2800 slot->hasRSAInfo = PR_TRUE1;
2801 }
2802 }
2803
2804 /* initialize the mechanism structure */
2805 mechanism.mechanism = wrapType;
2806 /* use NULL IV's for wrapping */
2807 if (param == NULL((void*)0))
2808 param = param_free = PK11_ParamFromIV(wrapType, NULL((void*)0));
2809 if (param) {
2810 mechanism.pParameter = param->data;
2811 mechanism.ulParameterLen = param->len;
2812 } else {
2813 mechanism.pParameter = NULL((void*)0);
2814 mechanism.ulParameterLen = 0;
2815 }
2816
2817 if ((mechanism_info.flags & CKF_DECRYPT0x00000200UL) && !PK11_DoesMechanism(slot, target)) {
2818 symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2819 target, keyTemplate, templateCount, keySize,
2820 wincx, &crv, isPerm);
2821 if (symKey) {
2822 if (param_free)
2823 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2824 return symKey;
2825 }
2826 /*
2827 * if the RSA OP simply failed, don't try to unwrap again
2828 * with this module.
2829 */
2830 if (crv == CKR_DEVICE_ERROR0x00000030UL) {
2831 if (param_free)
2832 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2833 return NULL((void*)0);
2834 }
2835 /* fall through, maybe they incorrectly set CKF_DECRYPT */
2836 }
2837
2838 /* get our key Structure */
2839 symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE1, wincx);
2840 if (symKey == NULL((void*)0)) {
2841 if (param_free)
2842 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2843 return NULL((void*)0);
2844 }
2845
2846 symKey->size = keySize;
2847 symKey->origin = PK11_OriginUnwrap;
2848
2849 if (isPerm) {
2850 rwsession = PK11_GetRWSession(slot);
2851 } else {
2852 pk11_EnterKeyMonitor(symKey);
2853 rwsession = symKey->session;
2854 }
2855 PORT_Assert(rwsession != CK_INVALID_HANDLE)((rwsession != 0)?((void)0):PR_Assert("rwsession != CK_INVALID_HANDLE"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",2855
))
;
2856 if (rwsession == CK_INVALID_HANDLE0)
2857 crv = CKR_SESSION_HANDLE_INVALID0x000000B3UL;
2858 else
2859 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_UnwrapKey(rwsession, &mechanism, wrappingKey,
2860 wrappedKey->data, wrappedKey->len,
2861 keyTemplate, templateCount,
2862 &symKey->objectID);
2863 if (isPerm) {
2864 if (rwsession != CK_INVALID_HANDLE0)
2865 PK11_RestoreROSession(slot, rwsession);
2866 } else {
2867 pk11_ExitKeyMonitor(symKey);
2868 }
2869 if (param_free)
2870 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2871 if (crv != CKR_OK0x00000000UL) {
2872 PK11_FreeSymKey(symKey);
2873 symKey = NULL((void*)0);
2874 if (crv != CKR_DEVICE_ERROR0x00000030UL) {
2875 /* try hand Unwrapping */
2876 symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2877 target, keyTemplate, templateCount,
2878 keySize, wincx, NULL((void*)0), isPerm);
2879 }
2880 }
2881
2882 return symKey;
2883}
2884
2885/* use a symetric key to unwrap another symetric key */
2886PK11SymKey *
2887PK11_UnwrapSymKey(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2888 SECItem *param, SECItem *wrappedKey,
2889 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2890 int keySize)
2891{
2892 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2893 wrapType, param, wrappedKey, target, operation, keySize,
2894 wrappingKey->cx, NULL((void*)0), 0, PR_FALSE0);
2895}
2896
2897/* use a symetric key to unwrap another symetric key */
2898PK11SymKey *
2899PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2900 SECItem *param, SECItem *wrappedKey,
2901 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2902 int keySize, CK_FLAGS flags)
2903{
2904 CK_BBOOL ckTrue = CK_TRUE1;
2905 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2906 unsigned int templateCount;
2907
2908 templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2909 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2910 wrapType, param, wrappedKey, target, operation, keySize,
2911 wrappingKey->cx, keyTemplate, templateCount, PR_FALSE0);
2912}
2913
2914PK11SymKey *
2915PK11_UnwrapSymKeyWithFlagsPerm(PK11SymKey *wrappingKey,
2916 CK_MECHANISM_TYPE wrapType,
2917 SECItem *param, SECItem *wrappedKey,
2918 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2919 int keySize, CK_FLAGS flags, PRBool isPerm)
2920{
2921 CK_BBOOL cktrue = CK_TRUE1;
2922 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2923 CK_ATTRIBUTE *attrs;
2924 unsigned int templateCount;
2925
2926 attrs = keyTemplate;
2927 if (isPerm) {
2928 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(CK_BBOOL));
;
2929 attrs++;
2930 }
2931 templateCount = attrs - keyTemplate;
2932 templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
2933
2934 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2935 wrapType, param, wrappedKey, target, operation, keySize,
2936 wrappingKey->cx, keyTemplate, templateCount, isPerm);
2937}
2938
2939/* unwrap a symmetric key with a private key. Only supports CKM_RSA_PKCS. */
2940PK11SymKey *
2941PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
2942 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
2943{
2944 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2945
2946 return PK11_PubUnwrapSymKeyWithMechanism(wrappingKey, wrapType, NULL((void*)0),
2947 wrappedKey, target, operation,
2948 keySize);
2949}
2950
2951/* unwrap a symmetric key with a private key with the given parameters. */
2952PK11SymKey *
2953PK11_PubUnwrapSymKeyWithMechanism(SECKEYPrivateKey *wrappingKey,
2954 CK_MECHANISM_TYPE mechType, SECItem *param,
2955 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2956 CK_ATTRIBUTE_TYPE operation, int keySize)
2957{
2958 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2959
2960 if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)(0 != (wrappingKey->staticflags & 0x1)) ? (0 != (wrappingKey
->staticflags & (1U << 1))) : PK11_HasAttributeSet
(wrappingKey->pkcs11Slot, wrappingKey->pkcs11ID, 0x00000002UL
, 0)
) {
2961 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2962 }
2963
2964 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID, mechType, param,
2965 wrappedKey, target, operation, keySize,
2966 wrappingKey->wincx, NULL((void*)0), 0, PR_FALSE0);
2967}
2968
2969/* unwrap a symetric key with a private key. */
2970PK11SymKey *
2971PK11_PubUnwrapSymKeyWithFlags(SECKEYPrivateKey *wrappingKey,
2972 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2973 CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags)
2974{
2975 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2976 CK_BBOOL ckTrue = CK_TRUE1;
2977 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2978 unsigned int templateCount;
2979 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2980
2981 templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2982
2983 if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)(0 != (wrappingKey->staticflags & 0x1)) ? (0 != (wrappingKey
->staticflags & (1U << 1))) : PK11_HasAttributeSet
(wrappingKey->pkcs11Slot, wrappingKey->pkcs11ID, 0x00000002UL
, 0)
) {
2984 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2985 }
2986
2987 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
2988 wrapType, NULL((void*)0), wrappedKey, target, operation, keySize,
2989 wrappingKey->wincx, keyTemplate, templateCount, PR_FALSE0);
2990}
2991
2992PK11SymKey *
2993PK11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey,
2994 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2995 CK_ATTRIBUTE_TYPE operation, int keySize,
2996 CK_FLAGS flags, PRBool isPerm)
2997{
2998 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2999 CK_BBOOL cktrue = CK_TRUE1;
3000 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3001 CK_ATTRIBUTE *attrs;
3002 unsigned int templateCount;
3003 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
3004
3005 attrs = keyTemplate;
3006 if (isPerm) {
3007 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(CK_BBOOL));
;
3008 attrs++;
3009 }
3010 templateCount = attrs - keyTemplate;
3011
3012 templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
3013
3014 if (SECKEY_HAS_ATTRIBUTE_SET(wrappingKey, CKA_PRIVATE)(0 != (wrappingKey->staticflags & 0x1)) ? (0 != (wrappingKey
->staticflags & (1U << 1))) : PK11_HasAttributeSet
(wrappingKey->pkcs11Slot, wrappingKey->pkcs11ID, 0x00000002UL
, 0)
) {
3015 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
3016 }
3017
3018 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
3019 wrapType, NULL((void*)0), wrappedKey, target, operation, keySize,
3020 wrappingKey->wincx, keyTemplate, templateCount, isPerm);
3021}
3022
3023PK11SymKey *
3024PK11_CopySymKeyForSigning(PK11SymKey *originalKey, CK_MECHANISM_TYPE mech)
3025{
3026 CK_RV crv;
3027 CK_ATTRIBUTE setTemplate;
3028 CK_BBOOL ckTrue = CK_TRUE1;
3029 PK11SlotInfo *slot = originalKey->slot;
3030
3031 /* first just try to set this key up for signing */
3032 PK11_SETATTRS(&setTemplate, CKA_SIGN, &ckTrue, sizeof(ckTrue))(&setTemplate)->type = (0x00000108UL); (&setTemplate
)->pValue = (&ckTrue); (&setTemplate)->ulValueLen
= (sizeof(ckTrue));
;
3033 pk11_EnterKeyMonitor(originalKey);
3034 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_SetAttributeValue(originalKey->session,
3035 originalKey->objectID, &setTemplate, 1);
3036 pk11_ExitKeyMonitor(originalKey);
3037 if (crv == CKR_OK0x00000000UL) {
3038 return PK11_ReferenceSymKey(originalKey);
3039 }
3040
3041 /* nope, doesn't like it, use the pk11 copy object command */
3042 return pk11_CopyToSlot(slot, mech, CKA_SIGN0x00000108UL, originalKey);
3043}
3044
3045void
3046PK11_SetFortezzaHack(PK11SymKey *symKey)
3047{
3048 symKey->origin = PK11_OriginFortezzaHack;
3049}
3050
3051/*
3052 * This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
3053 * working. This function simply gets a valid IV for the keys.
3054 */
3055SECStatus
3056PK11_GenerateFortezzaIV(PK11SymKey *symKey, unsigned char *iv, int len)
3057{
3058 CK_MECHANISM mech_info;
3059 CK_ULONG count = 0;
3060 CK_RV crv;
3061 SECStatus rv = SECFailure;
3062
3063 mech_info.mechanism = CKM_SKIPJACK_CBC640x00001002UL;
3064 mech_info.pParameter = iv;
3065 mech_info.ulParameterLen = len;
3066
3067 /* generate the IV for fortezza */
3068 PK11_EnterSlotMonitor(symKey->slot);
3069 crv = PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_EncryptInit(symKey->slot->session, &mech_info, symKey->objectID);
3070 if (crv == CKR_OK0x00000000UL) {
3071 PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_EncryptFinal(symKey->slot->session, NULL((void*)0), &count);
3072 rv = SECSuccess;
3073 }
3074 PK11_ExitSlotMonitor(symKey->slot);
3075 return rv;
3076}
3077
3078CK_OBJECT_HANDLE
3079PK11_GetSymKeyHandle(PK11SymKey *symKey)
3080{
3081 return symKey->objectID;
3082}
3083
3084SECStatus
3085PK11_Encapsulate(SECKEYPublicKey *pubKey, CK_MECHANISM_TYPE target,
3086 PK11AttrFlags attrFlags, CK_FLAGS opFlags,
3087 PK11SymKey **outKey, SECItem **outCiphertext)
3088{
3089 PORT_Assert(pubKey)((pubKey)?((void)0):PR_Assert("pubKey","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3089))
;
3090 PORT_Assert(outKey)((outKey)?((void)0):PR_Assert("outKey","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3090))
;
3091 PORT_Assert(outCiphertext)((outCiphertext)?((void)0):PR_Assert("outCiphertext","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3091))
;
3092
3093 PK11SlotInfo *slot = pubKey->pkcs11Slot;
3094
3095 PK11SymKey *sharedSecret = NULL((void*)0);
3096 SECItem *ciphertext = NULL((void*)0);
3097
3098 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3099 unsigned int templateCount;
3100
3101 CK_ATTRIBUTE *attrs;
3102 CK_BBOOL cktrue = CK_TRUE1;
3103 CK_BBOOL ckfalse = CK_FALSE0;
3104 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
3105 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
3106 CK_MECHANISM_TYPE kemType = pk11_mapKemKeyType(pubKey->keyType);
3107 CK_MECHANISM mech = { kemType, NULL((void*)0), 0 };
3108 CK_ULONG ciphertextLen = 0;
3109 CK_RV crv;
3110
3111 /* set up the target key template */
3112 attrs = keyTemplate;
3113 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
3114 attrs++;
3115
3116 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
3117 attrs++;
3118
3119 attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3120 attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3121
3122 templateCount = attrs - keyTemplate;
3123 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",3123
))
;
3124
3125 *outKey = NULL((void*)0);
3126 *outCiphertext = NULL((void*)0);
3127
3128 /* create a struxture for the target key */
3129 sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, NULL((void*)0));
3130 if (sharedSecret == NULL((void*)0)) {
3131 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
3132 return SECFailure;
3133 }
3134 sharedSecret->origin = PK11_OriginDerive;
3135
3136 /* this path is KEM mechanism agnostic */
3137 if (PK11_CheckPKCS11Version(slot, 3, 2, PR_TRUE1) >= 0) {
3138 pk11_EnterKeyMonitor(sharedSecret);
3139 /* get the length the normal PKCS #11 way. This works no matter
3140 * what the KEM is and we don't have to try to guess the KEM length
3141 * from the key */
3142 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_EncapsulateKey(sharedSecret->session,
3143 &mech,
3144 pubKey->pkcs11ID,
3145 keyTemplate,
3146 templateCount,
3147 NULL((void*)0),
3148 &ciphertextLen,
3149 &sharedSecret->objectID);
3150 pk11_ExitKeyMonitor(sharedSecret);
3151 if ((crv != CKR_OK0x00000000UL) && (crv != CKR_BUFFER_TOO_SMALL0x00000150UL) &&
3152 (crv != CKR_KEY_SIZE_RANGE0x00000062UL)) {
3153 goto loser;
3154 }
3155 ciphertext = SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), NULL((void*)0), ciphertextLen);
3156 if (ciphertext == NULL((void*)0)) {
3157 crv = CKR_HOST_MEMORY0x00000002UL;
3158 goto loser;
3159 }
3160 pk11_EnterKeyMonitor(sharedSecret);
3161 /* Now do the encapsulate */
3162 /* NOTE: the PKCS #11 order of the parameters is different from
3163 * the vendor interface */
3164 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_EncapsulateKey(sharedSecret->session,
3165 &mech,
3166 pubKey->pkcs11ID,
3167 keyTemplate,
3168 templateCount,
3169 ciphertext->data,
3170 &ciphertextLen,
3171 &sharedSecret->objectID);
3172 pk11_ExitKeyMonitor(sharedSecret);
3173 if (crv != CKR_OK0x00000000UL) {
3174 goto loser;
3175 }
3176 ciphertext->len = ciphertextLen;
3177 } else {
3178 /* use the old NSS private interface */
3179 CK_INTERFACE_PTR KEMInterface = NULL((void*)0);
3180 CK_UTF8CHAR_PTR KEMInterfaceName =
3181 (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3182 CK_VERSION KEMInterfaceVersion = { 1, 0 };
3183 CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL((void*)0);
3184 CK_NSS_KEM_PARAMETER_SET_TYPE kemParameterSet;
3185
3186 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetInterface(KEMInterfaceName,
3187 &KEMInterfaceVersion,
3188 &KEMInterface, 0);
3189 if (crv != CKR_OK0x00000000UL) {
3190 goto loser;
3191 }
3192 KEMInterfaceFunctions = (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3193
3194 /* the old API expected the parameter set as a parameter, the
3195 * pkcs11 v3.2 gets it from the key */
3196 kemParameterSet = PK11_ReadULongAttribute(slot,
3197 pubKey->pkcs11ID,
3198 CKA_NSS_PARAMETER_SET((0x80000000UL | 0x4E534350) + 40));
3199 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3200 kemParameterSet = PK11_ReadULongAttribute(slot,
3201 pubKey->pkcs11ID,
3202 CKA_PARAMETER_SET0x0000061dUL);
3203 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3204 crv = CKR_PUBLIC_KEY_INVALID0x000001B9UL;
3205 goto loser;
3206 }
3207 }
3208 /* The old interface only ever supported KYBER768 and MLKEM768
3209 * SOME versions of RHEL has MLKEM1024 support, if we want to
3210 * make sure this works with those versions of softoken (without their
3211 * NSS) we should check the kemParamSet and set the mech to
3212 * CKM_NSS_ML_KEM if the key isn't KYBER and the cipher test to
3213 * MLKEM104_CIPHERTEXT_BYTES if the kemParmset is MLKEM1024 */
3214 mech.mechanism = CKM_NSS_KYBER((0x80000000UL | 0x4E534350) + 46);
3215 mech.pParameter = (CK_VOID_PTR)&kemParameterSet;
3216 mech.ulParameterLen = sizeof(kemParameterSet);
3217 ciphertextLen = KYBER768_CIPHERTEXT_BYTES1088U;
3218
3219 ciphertext = SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), NULL((void*)0), ciphertextLen);
3220 if (ciphertext == NULL((void*)0)) {
3221 crv = CKR_HOST_MEMORY0x00000002UL;
3222 goto loser;
3223 }
3224
3225 pk11_EnterKeyMonitor(sharedSecret);
3226 crv = KEMInterfaceFunctions->C_Encapsulate(sharedSecret->session,
3227 &mech,
3228 pubKey->pkcs11ID,
3229 keyTemplate,
3230 templateCount,
3231 &sharedSecret->objectID,
3232 ciphertext->data,
3233 &ciphertextLen);
3234 pk11_ExitKeyMonitor(sharedSecret);
3235 if (crv != CKR_OK0x00000000UL) {
3236 goto loser;
3237 }
3238
3239 PORT_Assert(ciphertextLen == ciphertext->len)((ciphertextLen == ciphertext->len)?((void)0):PR_Assert("ciphertextLen == ciphertext->len"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",3239
))
;
3240 }
3241
3242 *outKey = sharedSecret;
3243 *outCiphertext = ciphertext;
3244
3245 return SECSuccess;
3246
3247loser:
3248 PK11_FreeSymKey(sharedSecret);
3249 SECITEM_FreeItemSECITEM_FreeItem_Util(ciphertext, PR_TRUE1);
3250 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
3251 return SECFailure;
3252}
3253
3254SECStatus
3255PK11_Decapsulate(SECKEYPrivateKey *privKey, const SECItem *ciphertext,
3256 CK_MECHANISM_TYPE target, PK11AttrFlags attrFlags,
3257 CK_FLAGS opFlags, PK11SymKey **outKey)
3258{
3259 PORT_Assert(privKey)((privKey)?((void)0):PR_Assert("privKey","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3259))
;
3260 PORT_Assert(ciphertext)((ciphertext)?((void)0):PR_Assert("ciphertext","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3260))
;
3261 PORT_Assert(outKey)((outKey)?((void)0):PR_Assert("outKey","/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
,3261))
;
3262
3263 PK11SlotInfo *slot = privKey->pkcs11Slot;
3264
3265 PK11SymKey *sharedSecret;
3266
3267 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3268 unsigned int templateCount;
3269
3270 CK_ATTRIBUTE *attrs;
3271 CK_BBOOL cktrue = CK_TRUE1;
3272 CK_BBOOL ckfalse = CK_FALSE0;
3273 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
3274 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
3275 CK_MECHANISM_TYPE kemType = pk11_mapKemKeyType(privKey->keyType);
3276 CK_MECHANISM mech = { kemType, NULL((void*)0), 0 };
3277
3278 CK_RV crv;
3279
3280 *outKey = NULL((void*)0);
3281 sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, NULL((void*)0));
3282 if (sharedSecret == NULL((void*)0)) {
3283 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
3284 return SECFailure;
3285 }
3286 sharedSecret->origin = PK11_OriginUnwrap;
3287
3288 attrs = keyTemplate;
3289 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
3290 attrs++;
3291
3292 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
3293 attrs++;
3294
3295 attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3296 attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3297
3298 templateCount = attrs - keyTemplate;
3299 PR_ASSERT(templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE))((templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE
))?((void)0):PR_Assert("templateCount <= sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)"
,"/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c",3299
))
;
3300
3301 if (PK11_CheckPKCS11Version(slot, 3, 2, PR_TRUE1) >= 0) {
3302 pk11_EnterKeyMonitor(sharedSecret);
3303 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DecapsulateKey(sharedSecret->session,
3304 &mech,
3305 privKey->pkcs11ID,
3306 keyTemplate,
3307 templateCount,
3308 ciphertext->data,
3309 ciphertext->len,
3310 &sharedSecret->objectID);
3311 pk11_ExitKeyMonitor(sharedSecret);
3312 if (crv != CKR_OK0x00000000UL) {
3313 goto loser;
3314 }
3315 } else {
3316 CK_INTERFACE_PTR KEMInterface = NULL((void*)0);
3317 CK_UTF8CHAR_PTR KEMInterfaceName =
3318 (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3319 CK_VERSION KEMInterfaceVersion = { 1, 0 };
3320 CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL((void*)0);
3321
3322 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetInterface(KEMInterfaceName,
3323 &KEMInterfaceVersion,
3324 &KEMInterface, 0);
3325 if (crv != CKR_OK0x00000000UL) {
3326 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
3327 goto loser;
3328 }
3329 KEMInterfaceFunctions =
3330 (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3331
3332 /* the old API expected the parameter set as a parameter, the
3333 * pkcs11 v3.2 gets it from the key */
3334 CK_ULONG kemParameterSet = PK11_ReadULongAttribute(slot,
3335 privKey->pkcs11ID,
3336 CKA_NSS_PARAMETER_SET((0x80000000UL | 0x4E534350) + 40));
3337 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3338 kemParameterSet = PK11_ReadULongAttribute(slot,
3339 privKey->pkcs11ID,
3340 CKA_PARAMETER_SET0x0000061dUL);
3341 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3342 crv = CKR_KEY_HANDLE_INVALID0x00000060UL;
Value stored to 'crv' is never read
3343 goto loser;
3344 }
3345 }
3346 /* The old interface only ever supported KYBER768 and MLKEM768
3347 * SOME versions of RHEL has MLKEM1024 support, if we want to
3348 * make sure this works with those versions of softoken (without their
3349 * NSS) we should check the kemParamSet and set the mech to
3350 * CKM_NSS_ML_KEM if the key isn't KYBER and the cipher test to
3351 * MLKEM104_CIPHERTEXT_BYTES if the kemParmset is MLKEM1024 */
3352 mech.mechanism = CKM_NSS_KYBER((0x80000000UL | 0x4E534350) + 46);
3353 mech.pParameter = (CK_VOID_PTR)&kemParameterSet;
3354 mech.ulParameterLen = sizeof(kemParameterSet);
3355
3356 pk11_EnterKeyMonitor(sharedSecret);
3357 crv = KEMInterfaceFunctions->C_Decapsulate(sharedSecret->session,
3358 &mech,
3359 privKey->pkcs11ID,
3360 ciphertext->data,
3361 ciphertext->len,
3362 keyTemplate,
3363 templateCount,
3364 &sharedSecret->objectID);
3365 pk11_ExitKeyMonitor(sharedSecret);
3366 if (crv != CKR_OK0x00000000UL) {
3367 goto loser;
3368 }
3369 }
3370
3371 *outKey = sharedSecret;
3372 return SECSuccess;
3373
3374loser:
3375 PK11_FreeSymKey(sharedSecret);
3376 return SECFailure;
3377}