Bug Summary

File:root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c
Warning:line 3377, 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/16/../../../../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-09-01-224014-2642839-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 /* PKCS #11 Mechanisms v3.0 Sec 2.62.4: CKM_HKDF_DATA output is a CKO_DATA object */
1684 PRBool cko_data = (derive == CKM_HKDF_DATA0x0000402bUL);
1685 CK_OBJECT_CLASS keyClass = cko_data ? CKO_DATA0x00000000UL : CKO_SECRET_KEY0x00000004UL;
1686 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
1687 CK_ULONG valueLen = 0;
1688 CK_MECHANISM mechanism;
1689 CK_RV crv;
1690#define MAX_ADD_ATTRS 4
1691 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16 + MAX_ADD_ATTRS];
1692#undef MAX_ADD_ATTRS
1693 CK_ATTRIBUTE *attrs = keyTemplate;
1694 CK_SESSION_HANDLE session;
1695 unsigned int templateCount;
1696
1697 if (numAttrs > MAX_TEMPL_ATTRS16) {
1698 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1699 return NULL((void*)0);
1700 }
1701 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
1702 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
1703 * it as a real attribute */
1704 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
1705 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
1706 * etc. Strip out the real attribute here */
1707 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
1708 }
1709
1710 /* first copy caller attributes in. */
1711 for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
1712 *attrs++ = *userAttr++;
1713 }
1714
1715 /* We only add the following attributes to the template if the caller
1716 ** didn't already supply them.
1717 */
1718 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS0x00000000UL)) {
1719 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass)(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof keyClass);
;
1720 attrs++;
1721 }
1722 /* PKCS #11 v3.0 Sec 4.5.2: Adding CKA_KEY_TYPE to CKO_DATA is invalid */
1723 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE0x00000100UL) && !cko_data) {
1724 keyType = PK11_GetKeyType(target, keySize);
1725 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType)(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof keyType);
;
1726 attrs++;
1727 }
1728 if (keySize > 0 &&
1729 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN0x00000161UL)) {
1730 valueLen = (CK_ULONG)keySize;
1731 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen)(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
valueLen); (attrs)->ulValueLen = (sizeof valueLen);
;
1732 attrs++;
1733 }
1734 /* PKCS #11 v3.0 Sec 4.5.2: CKO_DATA objects do not support
1735 * cryptographic operation flags */
1736 if ((operation != CKA_FLAGS_ONLY0) && !cko_data &&
1737 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
1738 PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (sizeof cktrue);
;
1739 attrs++;
1740 }
1741
1742 templateCount = attrs - keyTemplate;
1743 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",
1743))
;
1744
1745 /* move the key to a slot that can do the function */
1746 if (!PK11_DoesMechanism(slot, derive)) {
1747 /* get a new base key & slot */
1748 PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
1749
1750 if (newSlot == NULL((void*)0))
1751 return NULL((void*)0);
1752
1753 newBaseKey = pk11_CopyToSlot(newSlot, derive, CKA_DERIVE0x0000010CUL,
1754 baseKey);
1755 PK11_FreeSlot(newSlot);
1756 if (newBaseKey == NULL((void*)0))
1757 return NULL((void*)0);
1758 baseKey = newBaseKey;
1759 slot = baseKey->slot;
1760 }
1761
1762 /* get our key Structure */
1763 symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE1, baseKey->cx);
1764 if (symKey == NULL((void*)0)) {
1765 return NULL((void*)0);
1766 }
1767
1768 symKey->size = keySize;
1769
1770 mechanism.mechanism = derive;
1771 if (param) {
1772 mechanism.pParameter = param->data;
1773 mechanism.ulParameterLen = param->len;
1774 } else {
1775 mechanism.pParameter = NULL((void*)0);
1776 mechanism.ulParameterLen = 0;
1777 }
1778 symKey->origin = PK11_OriginDerive;
1779
1780 if (isPerm) {
1781 session = PK11_GetRWSession(slot);
1782 } else {
1783 pk11_EnterKeyMonitor(symKey);
1784 session = symKey->session;
1785 }
1786 if (session == CK_INVALID_HANDLE0) {
1787 if (!isPerm)
1788 pk11_ExitKeyMonitor(symKey);
1789 crv = CKR_SESSION_HANDLE_INVALID0x000000B3UL;
1790 } else {
1791 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(session, &mechanism,
1792 baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
1793 if (isPerm) {
1794 PK11_RestoreROSession(slot, session);
1795 } else {
1796 pk11_ExitKeyMonitor(symKey);
1797 }
1798 }
1799 if (newBaseKey)
1800 PK11_FreeSymKey(newBaseKey);
1801 if (crv != CKR_OK0x00000000UL) {
1802 PK11_FreeSymKey(symKey);
1803 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
1804 return NULL((void*)0);
1805 }
1806 return symKey;
1807}
1808
1809/* Create a new key by concatenating base and data
1810 */
1811static PK11SymKey *
1812pk11_ConcatenateBaseAndData(PK11SymKey *base,
1813 CK_BYTE *data, CK_ULONG dataLen, CK_MECHANISM_TYPE target,
1814 CK_ATTRIBUTE_TYPE operation)
1815{
1816 CK_KEY_DERIVATION_STRING_DATA mechParams;
1817 SECItem param;
1818
1819 if (base == NULL((void*)0)) {
1820 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1821 return NULL((void*)0);
1822 }
1823
1824 mechParams.pData = data;
1825 mechParams.ulLen = dataLen;
1826 param.data = (unsigned char *)&mechParams;
1827 param.len = sizeof(CK_KEY_DERIVATION_STRING_DATA);
1828
1829 return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_DATA0x00000362UL,
1830 &param, target, operation, 0);
1831}
1832
1833/* Create a new key by concatenating base and key
1834 */
1835static PK11SymKey *
1836pk11_ConcatenateBaseAndKey(PK11SymKey *base,
1837 PK11SymKey *key, CK_MECHANISM_TYPE target,
1838 CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1839{
1840 SECItem param;
1841
1842 if ((base == NULL((void*)0)) || (key == NULL((void*)0))) {
1843 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1844 return NULL((void*)0);
1845 }
1846
1847 param.data = (unsigned char *)&(key->objectID);
1848 param.len = sizeof(CK_OBJECT_HANDLE);
1849
1850 return PK11_Derive(base, CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
1851 &param, target, operation, keySize);
1852}
1853
1854PK11SymKey *
1855PK11_ConcatSymKeys(PK11SymKey *left, PK11SymKey *right, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation)
1856{
1857 PK11SymKey *out = NULL((void*)0);
1858 PK11SymKey *copyOfLeft = NULL((void*)0);
1859 PK11SymKey *copyOfRight = NULL((void*)0);
1860
1861 if ((left == NULL((void*)0)) || (right == NULL((void*)0))) {
1862 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1863 return NULL((void*)0);
1864 }
1865
1866 SECStatus rv = PK11_SymKeysToSameSlot(CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
1867 CKA_DERIVE0x0000010CUL, CKA_DERIVE0x0000010CUL, left, right,
1868 &copyOfLeft, &copyOfRight);
1869 if (rv != SECSuccess) {
1870 /* error code already set */
1871 return NULL((void*)0);
1872 }
1873
1874 out = pk11_ConcatenateBaseAndKey(copyOfLeft ? copyOfLeft : left, copyOfRight ? copyOfRight : right, target, operation, 0);
1875 PK11_FreeSymKey(copyOfLeft);
1876 PK11_FreeSymKey(copyOfRight);
1877 return out;
1878}
1879
1880/* Create a new key whose value is the hash of tobehashed.
1881 * type is the mechanism for the derived key.
1882 */
1883static PK11SymKey *
1884pk11_HashKeyDerivation(PK11SymKey *toBeHashed,
1885 CK_MECHANISM_TYPE hashMechanism, CK_MECHANISM_TYPE target,
1886 CK_ATTRIBUTE_TYPE operation, CK_ULONG keySize)
1887{
1888 return PK11_Derive(toBeHashed, hashMechanism, NULL((void*)0), target, operation, keySize);
1889}
1890
1891/* This function implements the ANSI X9.63 key derivation function
1892 */
1893static PK11SymKey *
1894pk11_ANSIX963Derive(PK11SymKey *sharedSecret,
1895 CK_EC_KDF_TYPE kdf, SECItem *sharedData,
1896 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1897 CK_ULONG keySize)
1898{
1899 CK_KEY_TYPE keyType;
1900 CK_MECHANISM_TYPE hashMechanism, mechanismArray[4];
1901 CK_ULONG derivedKeySize, HashLen, counter, maxCounter, bufferLen;
1902 CK_ULONG SharedInfoLen;
1903 CK_BYTE *buffer = NULL((void*)0);
1904 PK11SymKey *toBeHashed, *hashOutput;
1905 PK11SymKey *newSharedSecret = NULL((void*)0);
1906 PK11SymKey *oldIntermediateResult, *intermediateResult = NULL((void*)0);
1907
1908 if (sharedSecret == NULL((void*)0)) {
1909 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1910 return NULL((void*)0);
1911 }
1912
1913 switch (kdf) {
1914 case CKD_SHA1_KDF0x00000002UL:
1915 HashLen = SHA1_LENGTH20;
1916 hashMechanism = CKM_SHA1_KEY_DERIVATION0x00000392UL;
1917 break;
1918 case CKD_SHA224_KDF0x00000005UL:
1919 HashLen = SHA224_LENGTH28;
1920 hashMechanism = CKM_SHA224_KEY_DERIVATION0x00000396UL;
1921 break;
1922 case CKD_SHA256_KDF0x00000006UL:
1923 HashLen = SHA256_LENGTH32;
1924 hashMechanism = CKM_SHA256_KEY_DERIVATION0x00000393UL;
1925 break;
1926 case CKD_SHA384_KDF0x00000007UL:
1927 HashLen = SHA384_LENGTH48;
1928 hashMechanism = CKM_SHA384_KEY_DERIVATION0x00000394UL;
1929 break;
1930 case CKD_SHA512_KDF0x00000008UL:
1931 HashLen = SHA512_LENGTH64;
1932 hashMechanism = CKM_SHA512_KEY_DERIVATION0x00000395UL;
1933 break;
1934 default:
1935 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1936 return NULL((void*)0);
1937 }
1938
1939 derivedKeySize = keySize;
1940 if (derivedKeySize == 0) {
1941 keyType = PK11_GetKeyType(target, keySize);
1942 derivedKeySize = pk11_GetPredefinedKeyLength(keyType);
1943 if (derivedKeySize == 0) {
1944 derivedKeySize = HashLen;
1945 }
1946 }
1947
1948 /* Check that key_len isn't too long. The maximum key length could be
1949 * greatly increased if the code below did not limit the 4-byte counter
1950 * to a maximum value of 255. */
1951 if (derivedKeySize > 254 * HashLen) {
1952 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1953 return NULL((void*)0);
1954 }
1955
1956 maxCounter = derivedKeySize / HashLen;
1957 if (derivedKeySize > maxCounter * HashLen)
1958 maxCounter++;
1959
1960 if ((sharedData == NULL((void*)0)) || (sharedData->data == NULL((void*)0)))
1961 SharedInfoLen = 0;
1962 else
1963 SharedInfoLen = sharedData->len;
1964
1965 if (SharedInfoLen > PR_UINT32_MAX4294967295U - 4) {
1966 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1967 return NULL((void*)0);
1968 }
1969
1970 bufferLen = SharedInfoLen + 4;
1971
1972 /* Populate buffer with Counter || sharedData
1973 * where Counter is 0x00000001. */
1974 buffer = (unsigned char *)PORT_AllocPORT_Alloc_Util(bufferLen);
1975 if (buffer == NULL((void*)0)) {
1976 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
1977 return NULL((void*)0);
1978 }
1979
1980 buffer[0] = 0;
1981 buffer[1] = 0;
1982 buffer[2] = 0;
1983 buffer[3] = 1;
1984 if (SharedInfoLen > 0) {
1985 PORT_Memcpymemcpy(&buffer[4], sharedData->data, SharedInfoLen);
1986 }
1987
1988 /* Look for a slot that supports the mechanisms needed
1989 * to implement the ANSI X9.63 KDF as well as the
1990 * target mechanism.
1991 */
1992 mechanismArray[0] = CKM_CONCATENATE_BASE_AND_DATA0x00000362UL;
1993 mechanismArray[1] = hashMechanism;
1994 mechanismArray[2] = CKM_CONCATENATE_BASE_AND_KEY0x00000360UL;
1995 mechanismArray[3] = target;
1996
1997 newSharedSecret = pk11_ForceSlotMultiple(sharedSecret,
1998 mechanismArray, 4, operation);
1999 if (newSharedSecret != NULL((void*)0)) {
2000 sharedSecret = newSharedSecret;
2001 }
2002
2003 for (counter = 1; counter <= maxCounter; counter++) {
2004 /* Concatenate shared_secret and buffer */
2005 toBeHashed = pk11_ConcatenateBaseAndData(sharedSecret, buffer,
2006 bufferLen, hashMechanism, operation);
2007 if (toBeHashed == NULL((void*)0)) {
2008 goto loser;
2009 }
2010
2011 /* Hash value */
2012 if (maxCounter == 1) {
2013 /* In this case the length of the key to be derived is
2014 * less than or equal to the length of the hash output.
2015 * So, the output of the hash operation will be the
2016 * dervied key. */
2017 hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2018 target, operation, keySize);
2019 } else {
2020 /* In this case, the output of the hash operation will be
2021 * concatenated with other data to create the derived key. */
2022 hashOutput = pk11_HashKeyDerivation(toBeHashed, hashMechanism,
2023 CKM_CONCATENATE_BASE_AND_KEY0x00000360UL, operation, 0);
2024 }
2025 PK11_FreeSymKey(toBeHashed);
2026 if (hashOutput == NULL((void*)0)) {
2027 goto loser;
2028 }
2029
2030 /* Append result to intermediate result, if necessary */
2031 oldIntermediateResult = intermediateResult;
2032
2033 if (oldIntermediateResult == NULL((void*)0)) {
2034 intermediateResult = hashOutput;
2035 } else {
2036 if (counter == maxCounter) {
2037 /* This is the final concatenation, and so the output
2038 * will be the derived key. */
2039 intermediateResult =
2040 pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2041 hashOutput, target, operation, keySize);
2042 } else {
2043 /* The output of this concatenation will be concatenated
2044 * with other data to create the derived key. */
2045 intermediateResult =
2046 pk11_ConcatenateBaseAndKey(oldIntermediateResult,
2047 hashOutput, CKM_CONCATENATE_BASE_AND_KEY0x00000360UL,
2048 operation, 0);
2049 }
2050
2051 PK11_FreeSymKey(hashOutput);
2052 PK11_FreeSymKey(oldIntermediateResult);
2053 if (intermediateResult == NULL((void*)0)) {
2054 goto loser;
2055 }
2056 }
2057
2058 /* Increment counter (assumes maxCounter < 255) */
2059 buffer[3]++;
2060 }
2061
2062 PORT_ZFreePORT_ZFree_Util(buffer, bufferLen);
2063 if (newSharedSecret != NULL((void*)0))
2064 PK11_FreeSymKey(newSharedSecret);
2065 return intermediateResult;
2066
2067loser:
2068 PORT_ZFreePORT_ZFree_Util(buffer, bufferLen);
2069 if (newSharedSecret != NULL((void*)0))
2070 PK11_FreeSymKey(newSharedSecret);
2071 if (intermediateResult != NULL((void*)0))
2072 PK11_FreeSymKey(intermediateResult);
2073 return NULL((void*)0);
2074}
2075
2076/*
2077 * This regenerate a public key from a private key. This function is currently
2078 * NSS private. If we want to make it public, we need to add and optional
2079 * template or at least flags (a.la. PK11_DeriveWithFlags).
2080 */
2081CK_OBJECT_HANDLE
2082PK11_DerivePubKeyFromPrivKey(SECKEYPrivateKey *privKey)
2083{
2084 PK11SlotInfo *slot = privKey->pkcs11Slot;
2085 CK_MECHANISM mechanism;
2086 CK_OBJECT_HANDLE objectID = CK_INVALID_HANDLE0;
2087 CK_RV crv;
2088
2089 mechanism.mechanism = CKM_NSS_PUB_FROM_PRIV((0x80000000UL | 0x4E534350) + 40);
2090 mechanism.pParameter = NULL((void*)0);
2091 mechanism.ulParameterLen = 0;
2092
2093 PK11_EnterSlotMonitor(slot);
2094 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(slot->session, &mechanism,
2095 privKey->pkcs11ID, NULL((void*)0), 0,
2096 &objectID);
2097 PK11_ExitSlotMonitor(slot);
2098 if (crv != CKR_OK0x00000000UL) {
2099 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2100 return CK_INVALID_HANDLE0;
2101 }
2102 return objectID;
2103}
2104
2105/*
2106 * This Generates a wrapping key based on a privateKey, publicKey, and two
2107 * random numbers. For Mail usage RandomB should be NULL. In the Sender's
2108 * case RandomA is generate, otherwise it is passed.
2109 */
2110PK11SymKey *
2111PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2112 PRBool isSender, SECItem *randomA, SECItem *randomB,
2113 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2114 CK_ATTRIBUTE_TYPE operation, int keySize, void *wincx)
2115{
2116 PK11SlotInfo *slot = privKey->pkcs11Slot;
2117 CK_MECHANISM mechanism;
2118 PK11SymKey *symKey;
2119 CK_RV crv;
2120
2121 /* get our key Structure */
2122 symKey = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, wincx);
2123 if (symKey == NULL((void*)0)) {
2124 return NULL((void*)0);
2125 }
2126
2127 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2128 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2129 * it as a real attribute */
2130 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2131 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2132 * etc. Strip out the real attribute here */
2133 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2134 }
2135
2136 symKey->origin = PK11_OriginDerive;
2137
2138 switch (privKey->keyType) {
2139 case keaKey:
2140 case fortezzaKey: {
2141 static unsigned char rb_email[128] = { 0 };
2142 CK_KEA_DERIVE_PARAMS param;
2143 param.isSender = (CK_BBOOL)isSender;
2144 param.ulRandomLen = randomA->len;
2145 param.pRandomA = randomA->data;
2146 param.pRandomB = rb_email;
2147 param.pRandomB[127] = 1;
2148 if (randomB)
2149 param.pRandomB = randomB->data;
2150 if (pubKey->keyType == fortezzaKey) {
2151 param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2152 param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2153 } else {
2154 /* assert type == keaKey */
2155 /* XXX change to match key key types */
2156 param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
2157 param.pPublicData = pubKey->u.fortezza.KEAKey.data;
2158 }
2159
2160 mechanism.mechanism = derive;
2161 mechanism.pParameter = &param;
2162 mechanism.ulParameterLen = sizeof(param);
2163
2164 /* get a new symKey structure */
2165 pk11_EnterKeyMonitor(symKey);
2166 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2167 privKey->pkcs11ID, NULL((void*)0), 0,
2168 &symKey->objectID);
2169 pk11_ExitKeyMonitor(symKey);
2170 if (crv == CKR_OK0x00000000UL)
2171 return symKey;
2172 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2173 } break;
2174 case dhKey: {
2175 CK_BBOOL cktrue = CK_TRUE1;
2176 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2177 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2178 CK_ULONG key_size = 0;
2179 CK_ATTRIBUTE keyTemplate[4];
2180 int templateCount;
2181 CK_ATTRIBUTE *attrs = keyTemplate;
2182
2183 if (pubKey->keyType != dhKey) {
2184 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2185 break;
2186 }
2187
2188 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2189 attrs++;
2190 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2191 attrs++;
2192 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2193 attrs++;
2194 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2195 attrs++;
2196 templateCount = attrs - keyTemplate;
2197 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",
2197))
;
2198
2199 keyType = PK11_GetKeyType(target, keySize);
2200 key_size = keySize;
2201 symKey->size = keySize;
2202 if (key_size == 0)
2203 templateCount--;
2204
2205 mechanism.mechanism = derive;
2206
2207 /* we can undefine these when we define diffie-helman keys */
2208
2209 mechanism.pParameter = pubKey->u.dh.publicValue.data;
2210 mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
2211
2212 pk11_EnterKeyMonitor(symKey);
2213 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2214 privKey->pkcs11ID, keyTemplate,
2215 templateCount, &symKey->objectID);
2216 pk11_ExitKeyMonitor(symKey);
2217 if (crv == CKR_OK0x00000000UL)
2218 return symKey;
2219 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2220 } break;
2221 case ecKey: {
2222 CK_BBOOL cktrue = CK_TRUE1;
2223 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2224 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2225 CK_ULONG key_size = 0;
2226 CK_ATTRIBUTE keyTemplate[4];
2227 int templateCount;
2228 CK_ATTRIBUTE *attrs = keyTemplate;
2229 CK_ECDH1_DERIVE_PARAMS *mechParams = NULL((void*)0);
2230
2231 if (pubKey->keyType != ecKey) {
2232 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2233 break;
2234 }
2235
2236 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2237 attrs++;
2238 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2239 attrs++;
2240 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2241 attrs++;
2242 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2243 attrs++;
2244 templateCount = attrs - keyTemplate;
2245 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",
2245))
;
2246
2247 keyType = PK11_GetKeyType(target, keySize);
2248 key_size = keySize;
2249 if (key_size == 0) {
2250 if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2251 templateCount--;
2252 } else {
2253 /* sigh, some tokens can't figure this out and require
2254 * CKA_VALUE_LEN to be set */
2255 key_size = SHA1_LENGTH20;
2256 }
2257 }
2258 symKey->size = key_size;
2259
2260 mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS)(CK_ECDH1_DERIVE_PARAMS *)PORT_ZAlloc_Util(sizeof(CK_ECDH1_DERIVE_PARAMS
))
;
2261 mechParams->kdf = CKD_SHA1_KDF0x00000002UL;
2262 mechParams->ulSharedDataLen = 0;
2263 mechParams->pSharedData = NULL((void*)0);
2264 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2265 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2266
2267 mechanism.mechanism = derive;
2268 mechanism.pParameter = mechParams;
2269 mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2270
2271 pk11_EnterKeyMonitor(symKey);
2272 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2273 &mechanism, privKey->pkcs11ID, keyTemplate,
2274 templateCount, &symKey->objectID);
2275 pk11_ExitKeyMonitor(symKey);
2276
2277 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2278 * try this again with and encoded public key */
2279 if (crv != CKR_OK0x00000000UL && pk11_ECGetPubkeyEncoding(pubKey) != ECPoint_XOnly) {
2280 SECItem *pubValue = SEC_ASN1EncodeItemSEC_ASN1EncodeItem_Util(NULL((void*)0), NULL((void*)0),
2281 &pubKey->u.ec.publicValue,
2282 SEC_ASN1_GET(SEC_OctetStringTemplate)SEC_OctetStringTemplate_Util);
2283 if (pubValue == NULL((void*)0)) {
2284 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2285 break;
2286 }
2287 mechParams->ulPublicDataLen = pubValue->len;
2288 mechParams->pPublicData = pubValue->data;
2289
2290 pk11_EnterKeyMonitor(symKey);
2291 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2292 &mechanism, privKey->pkcs11ID, keyTemplate,
2293 templateCount, &symKey->objectID);
2294 pk11_ExitKeyMonitor(symKey);
2295
2296 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2297 }
2298
2299 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2300
2301 if (crv == CKR_OK0x00000000UL)
2302 return symKey;
2303 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2304 }
2305 /* most keys are not KEA keys, so assume they are bad if they
2306 * are not handled explicitly */
2307 default:
2308 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2309 break;
2310 }
2311
2312 PK11_FreeSymKey(symKey);
2313 return NULL((void*)0);
2314}
2315
2316/* Test for curves that are known to use a special encoding.
2317 * Extend this function when additional curves are added. */
2318static ECPointEncoding
2319pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey)
2320{
2321 SECItem oid;
2322 SECStatus rv;
2323 PORTCheapArenaPool tmpArena;
2324 ECPointEncoding encoding = ECPoint_Undefined;
2325
2326 PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE(2048));
2327
2328 /* decode the OID tag */
2329 rv = SEC_QuickDERDecodeItemSEC_QuickDERDecodeItem_Util(&tmpArena.arena, &oid,
2330 SEC_ASN1_GET(SEC_ObjectIDTemplate)SEC_ObjectIDTemplate_Util,
2331 &pubKey->u.ec.DEREncodedParams);
2332 if (rv == SECSuccess) {
2333 SECOidTag tag = SECOID_FindOIDTagSECOID_FindOIDTag_Util(&oid);
2334 switch (tag) {
2335 case SEC_OID_X25519:
2336 case SEC_OID_CURVE25519:
2337 encoding = ECPoint_XOnly;
2338 break;
2339 case SEC_OID_SECG_EC_SECP256R1SEC_OID_ANSIX962_EC_PRIME256V1:
2340 case SEC_OID_SECG_EC_SECP384R1:
2341 case SEC_OID_SECG_EC_SECP521R1:
2342 default:
2343 /* unknown curve, default to uncompressed */
2344 encoding = ECPoint_Uncompressed;
2345 }
2346 }
2347 PORT_DestroyCheapArena(&tmpArena);
2348 return encoding;
2349}
2350
2351/* Returns the size of the public key, or 0 if there
2352 * is an error. */
2353static CK_ULONG
2354pk11_ECPubKeySize(SECKEYPublicKey *pubKey)
2355{
2356 SECItem *publicValue = &pubKey->u.ec.publicValue;
2357
2358 ECPointEncoding encoding = pk11_ECGetPubkeyEncoding(pubKey);
2359 if (encoding == ECPoint_XOnly) {
2360 return publicValue->len;
2361 }
2362 if (encoding == ECPoint_Uncompressed) {
2363 /* key encoded in uncompressed form */
2364 return ((publicValue->len - 1) / 2);
2365 }
2366 /* key encoding not recognized */
2367 return 0;
2368}
2369
2370static PK11SymKey *
2371pk11_PubDeriveECKeyWithKDF(
2372 SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2373 PRBool isSender, SECItem *randomA, SECItem *randomB,
2374 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2375 CK_ATTRIBUTE_TYPE operation, int keySize,
2376 CK_ULONG kdf, SECItem *sharedData, void *wincx)
2377{
2378 PK11SlotInfo *slot = privKey->pkcs11Slot;
2379 PK11SymKey *symKey;
2380 PK11SymKey *SharedSecret;
2381 CK_MECHANISM mechanism;
2382 CK_RV crv;
2383 CK_BBOOL cktrue = CK_TRUE1;
2384 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2385 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2386 CK_ULONG key_size = 0;
2387 CK_ATTRIBUTE keyTemplate[4];
2388 int templateCount;
2389 CK_ATTRIBUTE *attrs = keyTemplate;
2390 CK_ECDH1_DERIVE_PARAMS *mechParams = NULL((void*)0);
2391
2392 if (pubKey->keyType != ecKey && pubKey->keyType != ecMontKey) {
2393 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2394 return NULL((void*)0);
2395 }
2396 if ((kdf != CKD_NULL0x00000001UL) && (kdf != CKD_SHA1_KDF0x00000002UL) &&
2397 (kdf != CKD_SHA224_KDF0x00000005UL) && (kdf != CKD_SHA256_KDF0x00000006UL) &&
2398 (kdf != CKD_SHA384_KDF0x00000007UL) && (kdf != CKD_SHA512_KDF0x00000008UL)) {
2399 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ALGORITHM);
2400 return NULL((void*)0);
2401 }
2402
2403 /* get our key Structure */
2404 symKey = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, wincx);
2405 if (symKey == NULL((void*)0)) {
2406 return NULL((void*)0);
2407 }
2408 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2409 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2410 * it as a real attribute */
2411 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2412 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2413 * etc. Strip out the real attribute here */
2414 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2415 }
2416
2417 symKey->origin = PK11_OriginDerive;
2418
2419 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
2420 attrs++;
2421 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
2422 attrs++;
2423 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2424 attrs++;
2425 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size))(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
key_size); (attrs)->ulValueLen = (sizeof(key_size));
;
2426 attrs++;
2427 templateCount = attrs - keyTemplate;
2428 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",
2428))
;
2429
2430 keyType = PK11_GetKeyType(target, keySize);
2431 key_size = keySize;
2432 if (key_size == 0) {
2433 if ((key_size = pk11_GetPredefinedKeyLength(keyType))) {
2434 templateCount--;
2435 } else {
2436 /* sigh, some tokens can't figure this out and require
2437 * CKA_VALUE_LEN to be set */
2438 switch (kdf) {
2439 case CKD_NULL0x00000001UL:
2440 key_size = pk11_ECPubKeySize(pubKey);
2441 if (key_size == 0) {
2442 PK11_FreeSymKey(symKey);
2443 return NULL((void*)0);
2444 }
2445 break;
2446 case CKD_SHA1_KDF0x00000002UL:
2447 key_size = SHA1_LENGTH20;
2448 break;
2449 case CKD_SHA224_KDF0x00000005UL:
2450 key_size = SHA224_LENGTH28;
2451 break;
2452 case CKD_SHA256_KDF0x00000006UL:
2453 key_size = SHA256_LENGTH32;
2454 break;
2455 case CKD_SHA384_KDF0x00000007UL:
2456 key_size = SHA384_LENGTH48;
2457 break;
2458 case CKD_SHA512_KDF0x00000008UL:
2459 key_size = SHA512_LENGTH64;
2460 break;
2461 default:
2462 PORT_AssertNotReached("Invalid CKD")PR_Assert("Invalid CKD", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 2462)
;
2463 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ALGORITHM);
2464 PK11_FreeSymKey(symKey);
2465 return NULL((void*)0);
2466 }
2467 }
2468 }
2469 symKey->size = key_size;
2470
2471 mechParams = PORT_ZNew(CK_ECDH1_DERIVE_PARAMS)(CK_ECDH1_DERIVE_PARAMS *)PORT_ZAlloc_Util(sizeof(CK_ECDH1_DERIVE_PARAMS
))
;
2472 if (!mechParams) {
2473 PK11_FreeSymKey(symKey);
2474 return NULL((void*)0);
2475 }
2476 mechParams->kdf = kdf;
2477 if (sharedData == NULL((void*)0)) {
2478 mechParams->ulSharedDataLen = 0;
2479 mechParams->pSharedData = NULL((void*)0);
2480 } else {
2481 mechParams->ulSharedDataLen = sharedData->len;
2482 mechParams->pSharedData = sharedData->data;
2483 }
2484 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2485 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2486
2487 mechanism.mechanism = derive;
2488 mechanism.pParameter = mechParams;
2489 mechanism.ulParameterLen = sizeof(CK_ECDH1_DERIVE_PARAMS);
2490
2491 pk11_EnterKeyMonitor(symKey);
2492 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session, &mechanism,
2493 privKey->pkcs11ID, keyTemplate,
2494 templateCount, &symKey->objectID);
2495 pk11_ExitKeyMonitor(symKey);
2496
2497 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2498 * try this again with an encoded public key */
2499 if (crv != CKR_OK0x00000000UL) {
2500 /* For curves that only use X as public value and no encoding we don't
2501 * have to try again. (Currently only Curve25519) */
2502 if (pk11_ECGetPubkeyEncoding(pubKey) == ECPoint_XOnly) {
2503 goto loser;
2504 }
2505 SECItem *pubValue = SEC_ASN1EncodeItemSEC_ASN1EncodeItem_Util(NULL((void*)0), NULL((void*)0),
2506 &pubKey->u.ec.publicValue,
2507 SEC_ASN1_GET(SEC_OctetStringTemplate)SEC_OctetStringTemplate_Util);
2508 if (pubValue == NULL((void*)0)) {
2509 goto loser;
2510 }
2511 mechParams->ulPublicDataLen = pubValue->len;
2512 mechParams->pPublicData = pubValue->data;
2513
2514 pk11_EnterKeyMonitor(symKey);
2515 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(symKey->session,
2516 &mechanism, privKey->pkcs11ID, keyTemplate,
2517 templateCount, &symKey->objectID);
2518 pk11_ExitKeyMonitor(symKey);
2519
2520 if ((crv != CKR_OK0x00000000UL) && (kdf != CKD_NULL0x00000001UL)) {
2521 /* Some PKCS #11 libraries cannot perform the key derivation
2522 * function. So, try calling C_DeriveKey with CKD_NULL and then
2523 * performing the KDF separately.
2524 */
2525 CK_ULONG derivedKeySize = key_size;
2526
2527 keyType = CKK_GENERIC_SECRET0x00000010UL;
2528 key_size = pk11_ECPubKeySize(pubKey);
2529 if (key_size == 0) {
2530 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2531 goto loser;
2532 }
2533 SharedSecret = symKey;
2534 SharedSecret->size = key_size;
2535
2536 mechParams->kdf = CKD_NULL0x00000001UL;
2537 mechParams->ulSharedDataLen = 0;
2538 mechParams->pSharedData = NULL((void*)0);
2539 mechParams->ulPublicDataLen = pubKey->u.ec.publicValue.len;
2540 mechParams->pPublicData = pubKey->u.ec.publicValue.data;
2541
2542 pk11_EnterKeyMonitor(SharedSecret);
2543 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(SharedSecret->session,
2544 &mechanism, privKey->pkcs11ID, keyTemplate,
2545 templateCount, &SharedSecret->objectID);
2546 pk11_ExitKeyMonitor(SharedSecret);
2547
2548 if (crv != CKR_OK0x00000000UL) {
2549 /* old PKCS #11 spec was ambiguous on what needed to be passed,
2550 * try this one final time with an encoded public key */
2551 mechParams->ulPublicDataLen = pubValue->len;
2552 mechParams->pPublicData = pubValue->data;
2553
2554 pk11_EnterKeyMonitor(SharedSecret);
2555 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DeriveKey(SharedSecret->session,
2556 &mechanism, privKey->pkcs11ID, keyTemplate,
2557 templateCount, &SharedSecret->objectID);
2558 pk11_ExitKeyMonitor(SharedSecret);
2559 }
2560
2561 /* Perform KDF. */
2562 if (crv == CKR_OK0x00000000UL) {
2563 symKey = pk11_ANSIX963Derive(SharedSecret, kdf,
2564 sharedData, target, operation,
2565 derivedKeySize);
2566 PK11_FreeSymKey(SharedSecret);
2567 if (symKey == NULL((void*)0)) {
2568 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2569 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2570 return NULL((void*)0);
2571 }
2572 }
2573 }
2574 SECITEM_FreeItemSECITEM_FreeItem_Util(pubValue, PR_TRUE1);
2575 }
2576
2577loser:
2578 PORT_ZFreePORT_ZFree_Util(mechParams, sizeof(CK_ECDH1_DERIVE_PARAMS));
2579
2580 if (crv != CKR_OK0x00000000UL) {
2581 PK11_FreeSymKey(symKey);
2582 symKey = NULL((void*)0);
2583 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2584 }
2585 return symKey;
2586}
2587
2588PK11SymKey *
2589PK11_PubDeriveWithKDF(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
2590 PRBool isSender, SECItem *randomA, SECItem *randomB,
2591 CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
2592 CK_ATTRIBUTE_TYPE operation, int keySize,
2593 CK_ULONG kdf, SECItem *sharedData, void *wincx)
2594{
2595
2596 switch (privKey->keyType) {
2597 case keaKey:
2598 case fortezzaKey:
2599 case dhKey:
2600 return PK11_PubDerive(privKey, pubKey, isSender, randomA, randomB,
2601 derive, target, operation, keySize, wincx);
2602 case ecKey:
2603 case ecMontKey:
2604 return pk11_PubDeriveECKeyWithKDF(privKey, pubKey, isSender,
2605 randomA, randomB, derive, target,
2606 operation, keySize,
2607 kdf, sharedData, wincx);
2608 default:
2609 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
2610 break;
2611 }
2612
2613 return NULL((void*)0);
2614}
2615
2616/*
2617 * this little function uses the Decrypt function to unwrap a key, just in
2618 * case we are having problem with unwrap. NOTE: The key size may
2619 * not be preserved properly for some algorithms!
2620 */
2621static PK11SymKey *
2622pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2623 CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target,
2624 CK_ATTRIBUTE *keyTemplate, unsigned int templateCount,
2625 int key_size, void *wincx, CK_RV *crvp, PRBool isPerm)
2626{
2627 CK_ULONG len;
2628 SECItem outKey;
2629 PK11SymKey *symKey;
2630 CK_RV crv;
2631 PRBool owner = PR_TRUE1;
2632 CK_SESSION_HANDLE session;
2633
2634 /* remove any VALUE_LEN parameters */
2635 if (keyTemplate[templateCount - 1].type == CKA_VALUE_LEN0x00000161UL) {
2636 templateCount--;
2637 }
2638
2639 if (key_size != 0 && (CK_ULONG)key_size > inKey->len) {
2640 PORT_SetErrorPORT_SetError_Util(PK11_MapError(CKR_UNWRAPPING_KEY_SIZE_RANGE0x000000F1UL));
2641 if (crvp)
2642 *crvp = CKR_UNWRAPPING_KEY_SIZE_RANGE0x000000F1UL;
2643 return NULL((void*)0);
2644 }
2645
2646 /* keys are almost always aligned, but if we get this far,
2647 * we've gone above and beyond anyway... */
2648 outKey.data = (unsigned char *)PORT_ZAllocPORT_ZAlloc_Util(inKey->len);
2649 if (outKey.data == NULL((void*)0)) {
2650 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
2651 if (crvp)
2652 *crvp = CKR_HOST_MEMORY0x00000002UL;
2653 return NULL((void*)0);
2654 }
2655 len = inKey->len;
2656
2657 /* use NULL IV's for wrapping */
2658 session = pk11_GetNewSession(slot, &owner);
2659 if (!owner || !(slot->isThreadSafe))
2660 PK11_EnterSlotMonitor(slot);
2661 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DecryptInit(session, mech, wrappingKey);
2662 if (crv != CKR_OK0x00000000UL) {
2663 if (!owner || !(slot->isThreadSafe))
2664 PK11_ExitSlotMonitor(slot);
2665 pk11_CloseSession(slot, session, owner);
2666 PORT_FreePORT_Free_Util(outKey.data);
2667 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2668 if (crvp)
2669 *crvp = crv;
2670 return NULL((void*)0);
2671 }
2672 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_Decrypt(session, inKey->data, inKey->len,
2673 outKey.data, &len);
2674 if (!owner || !(slot->isThreadSafe))
2675 PK11_ExitSlotMonitor(slot);
2676 pk11_CloseSession(slot, session, owner);
2677 if (crv != CKR_OK0x00000000UL) {
2678 PORT_FreePORT_Free_Util(outKey.data);
2679 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
2680 if (crvp)
2681 *crvp = crv;
2682 return NULL((void*)0);
2683 }
2684
2685 outKey.len = (key_size == 0) ? len : key_size;
2686 outKey.type = siBuffer;
2687
2688 if (PK11_DoesMechanism(slot, target)) {
2689 symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2690 isPerm, keyTemplate,
2691 templateCount, &outKey, wincx);
2692 } else {
2693 slot = PK11_GetBestSlot(target, wincx);
2694 if (slot == NULL((void*)0)) {
2695 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
2696 PORT_FreePORT_Free_Util(outKey.data);
2697 if (crvp)
2698 *crvp = CKR_DEVICE_ERROR0x00000030UL;
2699 return NULL((void*)0);
2700 }
2701 symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
2702 isPerm, keyTemplate,
2703 templateCount, &outKey, wincx);
2704 PK11_FreeSlot(slot);
2705 }
2706 PORT_FreePORT_Free_Util(outKey.data);
2707
2708 if (crvp)
2709 *crvp = symKey ? CKR_OK0x00000000UL : CKR_DEVICE_ERROR0x00000030UL;
2710 return symKey;
2711}
2712
2713/*
2714 * The wrap/unwrap function is pretty much the same for private and
2715 * public keys. It's just getting the Object ID and slot right. This is
2716 * the combined unwrap function.
2717 */
2718static PK11SymKey *
2719pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
2720 CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
2721 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
2722 void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs, PRBool isPerm)
2723{
2724 PK11SymKey *symKey;
2725 SECItem *param_free = NULL((void*)0);
2726 CK_BBOOL cktrue = CK_TRUE1;
2727 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
2728 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
2729 CK_ULONG valueLen = 0;
2730 CK_MECHANISM mechanism;
2731 CK_SESSION_HANDLE rwsession;
2732 CK_RV crv;
2733 CK_MECHANISM_INFO mechanism_info;
2734#define MAX_ADD_ATTRS 4
2735 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16 + MAX_ADD_ATTRS];
2736#undef MAX_ADD_ATTRS
2737 CK_ATTRIBUTE *attrs = keyTemplate;
2738 unsigned int templateCount;
2739
2740 if (numAttrs > MAX_TEMPL_ATTRS16) {
2741 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
2742 return NULL((void*)0);
2743 }
2744 /* CKA_NSS_MESSAGE is a fake operation to distinguish between
2745 * Normal Encrypt/Decrypt and MessageEncrypt/Decrypt. Don't try to set
2746 * it as a real attribute */
2747 if ((operation & CKA_NSS_MESSAGE_MASK0xff000000L) == CKA_NSS_MESSAGE0x82000000L) {
2748 /* Message is or'd with a real Attribute (CKA_ENCRYPT, CKA_DECRYPT),
2749 * etc. Strip out the real attribute here */
2750 operation &= ~CKA_NSS_MESSAGE_MASK0xff000000L;
2751 }
2752
2753 /* first copy caller attributes in. */
2754 for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
2755 *attrs++ = *userAttr++;
2756 }
2757
2758 /* We only add the following attributes to the template if the caller
2759 ** didn't already supply them.
2760 */
2761 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS0x00000000UL)) {
2762 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass)(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof keyClass);
;
2763 attrs++;
2764 }
2765 if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE0x00000100UL)) {
2766 keyType = PK11_GetKeyType(target, keySize);
2767 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType)(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof keyType);
;
2768 attrs++;
2769 }
2770 if ((operation != CKA_FLAGS_ONLY0) &&
2771 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
2772 PK11_SETATTRS(attrs, operation, &cktrue, 1)(attrs)->type = (operation); (attrs)->pValue = (&cktrue
); (attrs)->ulValueLen = (1);
;
2773 attrs++;
2774 }
2775
2776 /*
2777 * must be last in case we need to use this template to import the key
2778 */
2779 if (keySize > 0 &&
2780 !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN0x00000161UL)) {
2781 valueLen = (CK_ULONG)keySize;
2782 PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen)(attrs)->type = (0x00000161UL); (attrs)->pValue = (&
valueLen); (attrs)->ulValueLen = (sizeof valueLen);
;
2783 attrs++;
2784 }
2785
2786 templateCount = attrs - keyTemplate;
2787 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",
2787))
;
2788
2789 /* find out if we can do wrap directly. Because the RSA case if *very*
2790 * common, cache the results for it. */
2791 if ((wrapType == CKM_RSA_PKCS0x00000001UL) && (slot->hasRSAInfo)) {
2792 mechanism_info.flags = slot->RSAInfoFlags;
2793 } else {
2794 if (!slot->isThreadSafe)
2795 PK11_EnterSlotMonitor(slot);
2796 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetMechanismInfo(slot->slotID, wrapType,
2797 &mechanism_info);
2798 if (!slot->isThreadSafe)
2799 PK11_ExitSlotMonitor(slot);
2800 if (crv != CKR_OK0x00000000UL) {
2801 mechanism_info.flags = 0;
2802 }
2803 if (wrapType == CKM_RSA_PKCS0x00000001UL) {
2804 slot->RSAInfoFlags = mechanism_info.flags;
2805 slot->hasRSAInfo = PR_TRUE1;
2806 }
2807 }
2808
2809 /* initialize the mechanism structure */
2810 mechanism.mechanism = wrapType;
2811 /* use NULL IV's for wrapping */
2812 if (param == NULL((void*)0))
2813 param = param_free = PK11_ParamFromIV(wrapType, NULL((void*)0));
2814 if (param) {
2815 mechanism.pParameter = param->data;
2816 mechanism.ulParameterLen = param->len;
2817 } else {
2818 mechanism.pParameter = NULL((void*)0);
2819 mechanism.ulParameterLen = 0;
2820 }
2821
2822 if ((mechanism_info.flags & CKF_DECRYPT0x00000200UL) && !PK11_DoesMechanism(slot, target)) {
2823 symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2824 target, keyTemplate, templateCount, keySize,
2825 wincx, &crv, isPerm);
2826 if (symKey) {
2827 if (param_free)
2828 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2829 return symKey;
2830 }
2831 /*
2832 * if the RSA OP simply failed, don't try to unwrap again
2833 * with this module.
2834 */
2835 if (crv == CKR_DEVICE_ERROR0x00000030UL) {
2836 if (param_free)
2837 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2838 return NULL((void*)0);
2839 }
2840 /* fall through, maybe they incorrectly set CKF_DECRYPT */
2841 }
2842
2843 /* get our key Structure */
2844 symKey = pk11_CreateSymKey(slot, target, !isPerm, PR_TRUE1, wincx);
2845 if (symKey == NULL((void*)0)) {
2846 if (param_free)
2847 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2848 return NULL((void*)0);
2849 }
2850
2851 symKey->size = keySize;
2852 symKey->origin = PK11_OriginUnwrap;
2853
2854 if (isPerm) {
2855 rwsession = PK11_GetRWSession(slot);
2856 } else {
2857 pk11_EnterKeyMonitor(symKey);
2858 rwsession = symKey->session;
2859 }
2860 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",
2860))
;
2861 if (rwsession == CK_INVALID_HANDLE0)
2862 crv = CKR_SESSION_HANDLE_INVALID0x000000B3UL;
2863 else
2864 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_UnwrapKey(rwsession, &mechanism, wrappingKey,
2865 wrappedKey->data, wrappedKey->len,
2866 keyTemplate, templateCount,
2867 &symKey->objectID);
2868 if (isPerm) {
2869 if (rwsession != CK_INVALID_HANDLE0)
2870 PK11_RestoreROSession(slot, rwsession);
2871 } else {
2872 pk11_ExitKeyMonitor(symKey);
2873 }
2874 if (param_free)
2875 SECITEM_FreeItemSECITEM_FreeItem_Util(param_free, PR_TRUE1);
2876 if (crv != CKR_OK0x00000000UL) {
2877 PK11_FreeSymKey(symKey);
2878 symKey = NULL((void*)0);
2879 if (crv != CKR_DEVICE_ERROR0x00000030UL) {
2880 /* try hand Unwrapping */
2881 symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
2882 target, keyTemplate, templateCount,
2883 keySize, wincx, NULL((void*)0), isPerm);
2884 }
2885 }
2886
2887 return symKey;
2888}
2889
2890/* use a symetric key to unwrap another symetric key */
2891PK11SymKey *
2892PK11_UnwrapSymKey(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2893 SECItem *param, SECItem *wrappedKey,
2894 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2895 int keySize)
2896{
2897 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2898 wrapType, param, wrappedKey, target, operation, keySize,
2899 wrappingKey->cx, NULL((void*)0), 0, PR_FALSE0);
2900}
2901
2902/* use a symetric key to unwrap another symetric key */
2903PK11SymKey *
2904PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
2905 SECItem *param, SECItem *wrappedKey,
2906 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2907 int keySize, CK_FLAGS flags)
2908{
2909 CK_BBOOL ckTrue = CK_TRUE1;
2910 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2911 unsigned int templateCount;
2912
2913 templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2914 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2915 wrapType, param, wrappedKey, target, operation, keySize,
2916 wrappingKey->cx, keyTemplate, templateCount, PR_FALSE0);
2917}
2918
2919PK11SymKey *
2920PK11_UnwrapSymKeyWithFlagsPerm(PK11SymKey *wrappingKey,
2921 CK_MECHANISM_TYPE wrapType,
2922 SECItem *param, SECItem *wrappedKey,
2923 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
2924 int keySize, CK_FLAGS flags, PRBool isPerm)
2925{
2926 CK_BBOOL cktrue = CK_TRUE1;
2927 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2928 CK_ATTRIBUTE *attrs;
2929 unsigned int templateCount;
2930
2931 attrs = keyTemplate;
2932 if (isPerm) {
2933 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(CK_BBOOL));
;
2934 attrs++;
2935 }
2936 templateCount = attrs - keyTemplate;
2937 templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
2938
2939 return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
2940 wrapType, param, wrappedKey, target, operation, keySize,
2941 wrappingKey->cx, keyTemplate, templateCount, isPerm);
2942}
2943
2944/* unwrap a symmetric key with a private key. Only supports CKM_RSA_PKCS. */
2945PK11SymKey *
2946PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
2947 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
2948{
2949 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2950
2951 return PK11_PubUnwrapSymKeyWithMechanism(wrappingKey, wrapType, NULL((void*)0),
2952 wrappedKey, target, operation,
2953 keySize);
2954}
2955
2956/* unwrap a symmetric key with a private key with the given parameters. */
2957PK11SymKey *
2958PK11_PubUnwrapSymKeyWithMechanism(SECKEYPrivateKey *wrappingKey,
2959 CK_MECHANISM_TYPE mechType, SECItem *param,
2960 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2961 CK_ATTRIBUTE_TYPE operation, int keySize)
2962{
2963 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2964
2965 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)
) {
2966 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2967 }
2968
2969 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID, mechType, param,
2970 wrappedKey, target, operation, keySize,
2971 wrappingKey->wincx, NULL((void*)0), 0, PR_FALSE0);
2972}
2973
2974/* unwrap a symetric key with a private key. */
2975PK11SymKey *
2976PK11_PubUnwrapSymKeyWithFlags(SECKEYPrivateKey *wrappingKey,
2977 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
2978 CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags)
2979{
2980 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
2981 CK_BBOOL ckTrue = CK_TRUE1;
2982 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
2983 unsigned int templateCount;
2984 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
2985
2986 templateCount = pk11_OpFlagsToAttributes(flags, keyTemplate, &ckTrue);
2987
2988 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)
) {
2989 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
2990 }
2991
2992 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
2993 wrapType, NULL((void*)0), wrappedKey, target, operation, keySize,
2994 wrappingKey->wincx, keyTemplate, templateCount, PR_FALSE0);
2995}
2996
2997PK11SymKey *
2998PK11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey,
2999 SECItem *wrappedKey, CK_MECHANISM_TYPE target,
3000 CK_ATTRIBUTE_TYPE operation, int keySize,
3001 CK_FLAGS flags, PRBool isPerm)
3002{
3003 CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
3004 CK_BBOOL cktrue = CK_TRUE1;
3005 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3006 CK_ATTRIBUTE *attrs;
3007 unsigned int templateCount;
3008 PK11SlotInfo *slot = wrappingKey->pkcs11Slot;
3009
3010 attrs = keyTemplate;
3011 if (isPerm) {
3012 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL))(attrs)->type = (0x00000001UL); (attrs)->pValue = (&
cktrue); (attrs)->ulValueLen = (sizeof(CK_BBOOL));
;
3013 attrs++;
3014 }
3015 templateCount = attrs - keyTemplate;
3016
3017 templateCount += pk11_OpFlagsToAttributes(flags, attrs, &cktrue);
3018
3019 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)
) {
3020 PK11_HandlePasswordCheck(slot, wrappingKey->wincx);
3021 }
3022
3023 return pk11_AnyUnwrapKey(slot, wrappingKey->pkcs11ID,
3024 wrapType, NULL((void*)0), wrappedKey, target, operation, keySize,
3025 wrappingKey->wincx, keyTemplate, templateCount, isPerm);
3026}
3027
3028PK11SymKey *
3029PK11_CopySymKeyForSigning(PK11SymKey *originalKey, CK_MECHANISM_TYPE mech)
3030{
3031 CK_RV crv;
3032 CK_ATTRIBUTE setTemplate;
3033 CK_BBOOL ckTrue = CK_TRUE1;
3034 PK11SlotInfo *slot = originalKey->slot;
3035
3036 /* first just try to set this key up for signing */
3037 PK11_SETATTRS(&setTemplate, CKA_SIGN, &ckTrue, sizeof(ckTrue))(&setTemplate)->type = (0x00000108UL); (&setTemplate
)->pValue = (&ckTrue); (&setTemplate)->ulValueLen
= (sizeof(ckTrue));
;
3038 pk11_EnterKeyMonitor(originalKey);
3039 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_SetAttributeValue(originalKey->session,
3040 originalKey->objectID, &setTemplate, 1);
3041 pk11_ExitKeyMonitor(originalKey);
3042 if (crv == CKR_OK0x00000000UL) {
3043 return PK11_ReferenceSymKey(originalKey);
3044 }
3045
3046 /* nope, doesn't like it, use the pk11 copy object command */
3047 return pk11_CopyToSlot(slot, mech, CKA_SIGN0x00000108UL, originalKey);
3048}
3049
3050void
3051PK11_SetFortezzaHack(PK11SymKey *symKey)
3052{
3053 symKey->origin = PK11_OriginFortezzaHack;
3054}
3055
3056/*
3057 * This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
3058 * working. This function simply gets a valid IV for the keys.
3059 */
3060SECStatus
3061PK11_GenerateFortezzaIV(PK11SymKey *symKey, unsigned char *iv, int len)
3062{
3063 CK_MECHANISM mech_info;
3064 CK_ULONG count = 0;
3065 CK_RV crv;
3066 SECStatus rv = SECFailure;
3067
3068 mech_info.mechanism = CKM_SKIPJACK_CBC640x00001002UL;
3069 mech_info.pParameter = iv;
3070 mech_info.ulParameterLen = len;
3071
3072 /* generate the IV for fortezza */
3073 PK11_EnterSlotMonitor(symKey->slot);
3074 crv = PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_EncryptInit(symKey->slot->session, &mech_info, symKey->objectID);
3075 if (crv == CKR_OK0x00000000UL) {
3076 PK11_GETTAB(symKey->slot)((CK_FUNCTION_LIST_3_2_PTR)((symKey->slot)->functionList
))
->C_EncryptFinal(symKey->slot->session, NULL((void*)0), &count);
3077 rv = SECSuccess;
3078 }
3079 PK11_ExitSlotMonitor(symKey->slot);
3080 return rv;
3081}
3082
3083CK_OBJECT_HANDLE
3084PK11_GetSymKeyHandle(PK11SymKey *symKey)
3085{
3086 return symKey->objectID;
3087}
3088
3089SECStatus
3090PK11_Encapsulate(SECKEYPublicKey *pubKey, CK_MECHANISM_TYPE target,
3091 PK11AttrFlags attrFlags, CK_FLAGS opFlags,
3092 PK11SymKey **outKey, SECItem **outCiphertext)
3093{
3094 PORT_Assert(pubKey)((pubKey) ? ((void)0) : PR_Assert("pubKey", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3094))
;
3095 PORT_Assert(outKey)((outKey) ? ((void)0) : PR_Assert("outKey", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3095))
;
3096 PORT_Assert(outCiphertext)((outCiphertext) ? ((void)0) : PR_Assert("outCiphertext", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3096))
;
3097
3098 PK11SlotInfo *slot = pubKey->pkcs11Slot;
3099
3100 PK11SymKey *sharedSecret = NULL((void*)0);
3101 SECItem *ciphertext = NULL((void*)0);
3102
3103 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3104 unsigned int templateCount;
3105
3106 CK_ATTRIBUTE *attrs;
3107 CK_BBOOL cktrue = CK_TRUE1;
3108 CK_BBOOL ckfalse = CK_FALSE0;
3109 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
3110 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
3111 CK_MECHANISM_TYPE kemType = pk11_mapKemKeyType(pubKey->keyType);
3112 CK_MECHANISM mech = { kemType, NULL((void*)0), 0 };
3113 CK_ULONG ciphertextLen = 0;
3114 CK_RV crv;
3115
3116 /* set up the target key template */
3117 attrs = keyTemplate;
3118 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
3119 attrs++;
3120
3121 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
3122 attrs++;
3123
3124 attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3125 attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3126
3127 templateCount = attrs - keyTemplate;
3128 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",
3128))
;
3129
3130 *outKey = NULL((void*)0);
3131 *outCiphertext = NULL((void*)0);
3132
3133 if (kemType == CKM_INVALID_MECHANISM0xffffffffUL) {
3134 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_UNSUPPORTED_KEYALG);
3135 return SECFailure;
3136 }
3137
3138 if (slot == NULL((void*)0)) {
3139 slot = PK11_GetBestSlot(kemType, NULL((void*)0));
3140 if (slot == NULL((void*)0)) {
3141 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MODULE);
3142 return SECFailure;
3143 }
3144 if (PK11_ImportPublicKey(slot, pubKey, PR_FALSE0) == CK_INVALID_HANDLE0) {
3145 PK11_FreeSlot(slot);
3146 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
3147 return SECFailure;
3148 }
3149 PK11_FreeSlot(slot); /* pubKey holds a slot reference on success. */
3150 slot = pubKey->pkcs11Slot;
3151 }
3152
3153 /* create a struxture for the target key */
3154 sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, NULL((void*)0));
3155 if (sharedSecret == NULL((void*)0)) {
3156 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
3157 return SECFailure;
3158 }
3159 sharedSecret->origin = PK11_OriginDerive;
3160
3161 /* this path is KEM mechanism agnostic */
3162 if (PK11_CheckPKCS11Version(slot, 3, 2, PR_TRUE1) >= 0) {
3163 pk11_EnterKeyMonitor(sharedSecret);
3164 /* get the length the normal PKCS #11 way. This works no matter
3165 * what the KEM is and we don't have to try to guess the KEM length
3166 * from the key */
3167 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_EncapsulateKey(sharedSecret->session,
3168 &mech,
3169 pubKey->pkcs11ID,
3170 keyTemplate,
3171 templateCount,
3172 NULL((void*)0),
3173 &ciphertextLen,
3174 &sharedSecret->objectID);
3175 pk11_ExitKeyMonitor(sharedSecret);
3176 if ((crv != CKR_OK0x00000000UL) && (crv != CKR_BUFFER_TOO_SMALL0x00000150UL) &&
3177 (crv != CKR_KEY_SIZE_RANGE0x00000062UL)) {
3178 goto loser;
3179 }
3180 ciphertext = SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), NULL((void*)0), ciphertextLen);
3181 if (ciphertext == NULL((void*)0)) {
3182 crv = CKR_HOST_MEMORY0x00000002UL;
3183 goto loser;
3184 }
3185 pk11_EnterKeyMonitor(sharedSecret);
3186 /* Now do the encapsulate */
3187 /* NOTE: the PKCS #11 order of the parameters is different from
3188 * the vendor interface */
3189 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_EncapsulateKey(sharedSecret->session,
3190 &mech,
3191 pubKey->pkcs11ID,
3192 keyTemplate,
3193 templateCount,
3194 ciphertext->data,
3195 &ciphertextLen,
3196 &sharedSecret->objectID);
3197 pk11_ExitKeyMonitor(sharedSecret);
3198 if (crv != CKR_OK0x00000000UL) {
3199 goto loser;
3200 }
3201 ciphertext->len = ciphertextLen;
3202 } else {
3203 /* use the old NSS private interface */
3204 CK_INTERFACE_PTR KEMInterface = NULL((void*)0);
3205 CK_UTF8CHAR_PTR KEMInterfaceName =
3206 (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3207 CK_VERSION KEMInterfaceVersion = { 1, 0 };
3208 CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL((void*)0);
3209 CK_NSS_KEM_PARAMETER_SET_TYPE kemParameterSet;
3210
3211 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetInterface(KEMInterfaceName,
3212 &KEMInterfaceVersion,
3213 &KEMInterface, 0);
3214 if (crv != CKR_OK0x00000000UL) {
3215 goto loser;
3216 }
3217 KEMInterfaceFunctions = (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3218
3219 /* the old API expected the parameter set as a parameter, the
3220 * pkcs11 v3.2 gets it from the key */
3221 kemParameterSet = PK11_ReadULongAttribute(slot,
3222 pubKey->pkcs11ID,
3223 CKA_NSS_PARAMETER_SET((0x80000000UL | 0x4E534350) + 40));
3224 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3225 kemParameterSet = PK11_ReadULongAttribute(slot,
3226 pubKey->pkcs11ID,
3227 CKA_PARAMETER_SET0x0000061dUL);
3228 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3229 crv = CKR_PUBLIC_KEY_INVALID0x000001B9UL;
3230 goto loser;
3231 }
3232 }
3233 /* The old interface only ever supported KYBER768 and MLKEM768
3234 * SOME versions of RHEL has MLKEM1024 support, if we want to
3235 * make sure this works with those versions of softoken (without their
3236 * NSS) we should check the kemParamSet and set the mech to
3237 * CKM_NSS_ML_KEM if the key isn't KYBER and the cipher test to
3238 * MLKEM104_CIPHERTEXT_BYTES if the kemParmset is MLKEM1024 */
3239 mech.mechanism = CKM_NSS_KYBER((0x80000000UL | 0x4E534350) + 46);
3240 mech.pParameter = (CK_VOID_PTR)&kemParameterSet;
3241 mech.ulParameterLen = sizeof(kemParameterSet);
3242 ciphertextLen = KYBER768_CIPHERTEXT_BYTES1088U;
3243
3244 ciphertext = SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), NULL((void*)0), ciphertextLen);
3245 if (ciphertext == NULL((void*)0)) {
3246 crv = CKR_HOST_MEMORY0x00000002UL;
3247 goto loser;
3248 }
3249
3250 pk11_EnterKeyMonitor(sharedSecret);
3251 crv = KEMInterfaceFunctions->C_Encapsulate(sharedSecret->session,
3252 &mech,
3253 pubKey->pkcs11ID,
3254 keyTemplate,
3255 templateCount,
3256 &sharedSecret->objectID,
3257 ciphertext->data,
3258 &ciphertextLen);
3259 pk11_ExitKeyMonitor(sharedSecret);
3260 if (crv != CKR_OK0x00000000UL) {
3261 goto loser;
3262 }
3263
3264 PORT_Assert(ciphertextLen == ciphertext->len)((ciphertextLen == ciphertext->len) ? ((void)0) : PR_Assert
("ciphertextLen == ciphertext->len", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3264))
;
3265 }
3266
3267 *outKey = sharedSecret;
3268 *outCiphertext = ciphertext;
3269
3270 return SECSuccess;
3271
3272loser:
3273 PK11_FreeSymKey(sharedSecret);
3274 SECITEM_FreeItemSECITEM_FreeItem_Util(ciphertext, PR_TRUE1);
3275 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
3276 return SECFailure;
3277}
3278
3279SECStatus
3280PK11_Decapsulate(SECKEYPrivateKey *privKey, const SECItem *ciphertext,
3281 CK_MECHANISM_TYPE target, PK11AttrFlags attrFlags,
3282 CK_FLAGS opFlags, PK11SymKey **outKey)
3283{
3284 PORT_Assert(privKey)((privKey) ? ((void)0) : PR_Assert("privKey", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3284))
;
3285 PORT_Assert(ciphertext)((ciphertext) ? ((void)0) : PR_Assert("ciphertext", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3285))
;
3286 PORT_Assert(outKey)((outKey) ? ((void)0) : PR_Assert("outKey", "/root/firefox-clang/security/nss/lib/pk11wrap/pk11skey.c"
, 3286))
;
3287
3288 PK11SlotInfo *slot = privKey->pkcs11Slot;
3289
3290 PK11SymKey *sharedSecret;
3291
3292 CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS16];
3293 unsigned int templateCount;
3294
3295 CK_ATTRIBUTE *attrs;
3296 CK_BBOOL cktrue = CK_TRUE1;
3297 CK_BBOOL ckfalse = CK_FALSE0;
3298 CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY0x00000004UL;
3299 CK_KEY_TYPE keyType = CKK_GENERIC_SECRET0x00000010UL;
3300 CK_MECHANISM_TYPE kemType = pk11_mapKemKeyType(privKey->keyType);
3301 CK_MECHANISM mech = { kemType, NULL((void*)0), 0 };
3302
3303 CK_RV crv;
3304
3305 *outKey = NULL((void*)0);
3306
3307 if (kemType == CKM_INVALID_MECHANISM0xffffffffUL) {
3308 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_UNSUPPORTED_KEYALG);
3309 return SECFailure;
3310 }
3311 if (slot == NULL((void*)0)) {
3312 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
3313 return SECFailure;
3314 }
3315
3316 sharedSecret = pk11_CreateSymKey(slot, target, PR_TRUE1, PR_TRUE1, NULL((void*)0));
3317 if (sharedSecret == NULL((void*)0)) {
3318 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
3319 return SECFailure;
3320 }
3321 sharedSecret->origin = PK11_OriginUnwrap;
3322
3323 attrs = keyTemplate;
3324 PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass))(attrs)->type = (0x00000000UL); (attrs)->pValue = (&
keyClass); (attrs)->ulValueLen = (sizeof(keyClass));
;
3325 attrs++;
3326
3327 PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType))(attrs)->type = (0x00000100UL); (attrs)->pValue = (&
keyType); (attrs)->ulValueLen = (sizeof(keyType));
;
3328 attrs++;
3329
3330 attrs += pk11_AttrFlagsToAttributes(attrFlags, attrs, &cktrue, &ckfalse);
3331 attrs += pk11_OpFlagsToAttributes(opFlags, attrs, &cktrue);
3332
3333 templateCount = attrs - keyTemplate;
3334 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",
3334))
;
3335
3336 if (PK11_CheckPKCS11Version(slot, 3, 2, PR_TRUE1) >= 0) {
3337 pk11_EnterKeyMonitor(sharedSecret);
3338 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_DecapsulateKey(sharedSecret->session,
3339 &mech,
3340 privKey->pkcs11ID,
3341 keyTemplate,
3342 templateCount,
3343 ciphertext->data,
3344 ciphertext->len,
3345 &sharedSecret->objectID);
3346 pk11_ExitKeyMonitor(sharedSecret);
3347 if (crv != CKR_OK0x00000000UL) {
3348 goto loser;
3349 }
3350 } else {
3351 CK_INTERFACE_PTR KEMInterface = NULL((void*)0);
3352 CK_UTF8CHAR_PTR KEMInterfaceName =
3353 (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface";
3354 CK_VERSION KEMInterfaceVersion = { 1, 0 };
3355 CK_NSS_KEM_FUNCTIONS *KEMInterfaceFunctions = NULL((void*)0);
3356
3357 crv = PK11_GETTAB(slot)((CK_FUNCTION_LIST_3_2_PTR)((slot)->functionList))->C_GetInterface(KEMInterfaceName,
3358 &KEMInterfaceVersion,
3359 &KEMInterface, 0);
3360 if (crv != CKR_OK0x00000000UL) {
3361 PORT_SetErrorPORT_SetError_Util(PK11_MapError(crv));
3362 goto loser;
3363 }
3364 KEMInterfaceFunctions =
3365 (CK_NSS_KEM_FUNCTIONS *)(KEMInterface->pFunctionList);
3366
3367 /* the old API expected the parameter set as a parameter, the
3368 * pkcs11 v3.2 gets it from the key */
3369 CK_ULONG kemParameterSet = PK11_ReadULongAttribute(slot,
3370 privKey->pkcs11ID,
3371 CKA_NSS_PARAMETER_SET((0x80000000UL | 0x4E534350) + 40));
3372 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3373 kemParameterSet = PK11_ReadULongAttribute(slot,
3374 privKey->pkcs11ID,
3375 CKA_PARAMETER_SET0x0000061dUL);
3376 if (kemParameterSet == CK_UNAVAILABLE_INFORMATION(~0UL)) {
3377 crv = CKR_KEY_HANDLE_INVALID0x00000060UL;
Value stored to 'crv' is never read
3378 goto loser;
3379 }
3380 }
3381 /* The old interface only ever supported KYBER768 and MLKEM768
3382 * SOME versions of RHEL has MLKEM1024 support, if we want to
3383 * make sure this works with those versions of softoken (without their
3384 * NSS) we should check the kemParamSet and set the mech to
3385 * CKM_NSS_ML_KEM if the key isn't KYBER and the cipher test to
3386 * MLKEM104_CIPHERTEXT_BYTES if the kemParmset is MLKEM1024 */
3387 mech.mechanism = CKM_NSS_KYBER((0x80000000UL | 0x4E534350) + 46);
3388 mech.pParameter = (CK_VOID_PTR)&kemParameterSet;
3389 mech.ulParameterLen = sizeof(kemParameterSet);
3390
3391 pk11_EnterKeyMonitor(sharedSecret);
3392 crv = KEMInterfaceFunctions->C_Decapsulate(sharedSecret->session,
3393 &mech,
3394 privKey->pkcs11ID,
3395 ciphertext->data,
3396 ciphertext->len,
3397 keyTemplate,
3398 templateCount,
3399 &sharedSecret->objectID);
3400 pk11_ExitKeyMonitor(sharedSecret);
3401 if (crv != CKR_OK0x00000000UL) {
3402 goto loser;
3403 }
3404 }
3405
3406 *outKey = sharedSecret;
3407 return SECSuccess;
3408
3409loser:
3410 PK11_FreeSymKey(sharedSecret);
3411 return SECFailure;
3412}