Coverage Report

Created: 2025-07-01 06:26

/src/nss/lib/softoken/pkcs11.c
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
/*
5
 * This file implements PKCS 11 on top of our existing security modules
6
 *
7
 * For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
8
 *   This implementation has two slots:
9
 *      slot 1 is our generic crypto support. It does not require login.
10
 *   It supports Public Key ops, and all they bulk ciphers and hashes.
11
 *   It can also support Private Key ops for imported Private keys. It does
12
 *   not have any token storage.
13
 *      slot 2 is our private key support. It requires a login before use. It
14
 *   can store Private Keys and Certs as token objects. Currently only private
15
 *   keys and their associated Certificates are saved on the token.
16
 *
17
 *   In this implementation, session objects are only visible to the session
18
 *   that created or generated them.
19
 */
20
#include "seccomon.h"
21
#include "secitem.h"
22
/* we need to use the deprecated mechanisms values for backward compatibility */
23
#include "pkcs11.h"
24
#include "pkcs11i.h"
25
#include "softoken.h"
26
#include "lowkeyi.h"
27
#include "blapi.h"
28
#include "secder.h"
29
#include "secport.h"
30
#include "secrng.h"
31
#include "prtypes.h"
32
#include "nspr.h"
33
#include "softkver.h"
34
#include "secoid.h"
35
#include "sftkdb.h"
36
#include "utilpars.h"
37
#include "ec.h"
38
#include "secasn1.h"
39
#include "secerr.h"
40
#include "lgglue.h"
41
#include "kem.h"
42
43
PRBool parentForkedAfterC_Initialize;
44
45
#ifndef NO_FORK_CHECK
46
47
PRBool sftkForkCheckDisabled;
48
49
#if defined(CHECK_FORK_PTHREAD) || defined(CHECK_FORK_MIXED)
50
PRBool forked = PR_FALSE;
51
#endif
52
53
#if defined(CHECK_FORK_GETPID) || defined(CHECK_FORK_MIXED)
54
#include <unistd.h>
55
pid_t myPid;
56
#endif
57
58
#ifdef CHECK_FORK_MIXED
59
#include <sys/systeminfo.h>
60
PRBool usePthread_atfork;
61
#endif
62
63
#endif
64
65
#ifdef XP_UNIX
66
0
#define LIB_PARAM_DEFAULT_FILE_LOCATION "/etc/nss/params.config"
67
#endif
68
69
0
#define LIB_PARAM_DEFAULT " configdir='' certPrefix='' keyPrefix='' secmod='' flags=noCertDB,noModDB "
70
/*
71
 * ******************** Static data *******************************
72
 */
73
74
/* The next three strings must be exactly 32 characters long */
75
static char *manufacturerID = "Mozilla Foundation              ";
76
static char manufacturerID_space[33];
77
static char *libraryDescription = "NSS Internal Crypto Services    ";
78
static char libraryDescription_space[33];
79
80
/*
81
 * In FIPS mode, we disallow login attempts for 1 second after a login
82
 * failure so that there are at most 60 login attempts per minute.
83
 */
84
static PRIntervalTime loginWaitTime;
85
86
#define __PASTE(x, y) x##y
87
88
/*
89
 * we renamed all our internal functions, get the correct
90
 * definitions for them...
91
 */
92
#undef CK_PKCS11_FUNCTION_INFO
93
#undef CK_NEED_ARG_LIST
94
95
#define CK_PKCS11_3_0 1
96
#define CK_EXTERN extern
97
#define CK_PKCS11_FUNCTION_INFO(func) \
98
    CK_RV __PASTE(NS, func)
99
#define CK_NEED_ARG_LIST 1
100
101
#include "pkcs11f.h"
102
103
#ifndef NSS_FIPS_DISABLE
104
/* ------------- forward declare all the FIPS functions ------------- */
105
#undef CK_NEED_ARG_LIST
106
#undef CK_PKCS11_FUNCTION_INFO
107
108
#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(F, name)
109
#define CK_NEED_ARG_LIST 1
110
111
#include "pkcs11f.h"
112
#endif
113
114
/* build the crypto module table */
115
static CK_FUNCTION_LIST_3_0 sftk_funcList = {
116
    { 3, 0 },
117
118
#undef CK_PKCS11_FUNCTION_INFO
119
#undef CK_NEED_ARG_LIST
120
121
#define CK_PKCS11_FUNCTION_INFO(func) \
122
    __PASTE(NS, func)                 \
123
    ,
124
#include "pkcs11f.h"
125
126
};
127
128
/* need a special version of get info for version 2 which returns the version
129
 * 2.4 version number */
130
CK_RV NSC_GetInfoV2(CK_INFO_PTR pInfo);
131
CK_RV NSC_GetMechanismInfoV2(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
132
                             CK_MECHANISM_INFO_PTR pInfo);
133
134
/* build the crypto module table */
135
static CK_FUNCTION_LIST sftk_funcList_v2 = {
136
    { 2, 40 },
137
138
#undef CK_PKCS11_3_0
139
#define CK_PKCS_11_2_0_ONLY 1
140
#undef CK_PKCS11_FUNCTION_INFO
141
#undef CK_NEED_ARG_LIST
142
#define C_GetInfo C_GetInfoV2
143
#define C_GetMechanismInfo C_GetMechanismInfoV2
144
145
#define CK_PKCS11_FUNCTION_INFO(func) \
146
    __PASTE(NS, func)                 \
147
    ,
148
#include "pkcs11f.h"
149
150
};
151
152
#undef C_GetInfo
153
#undef C_GetMechanismInfo
154
#undef CK_PKCS_11_2_0_ONLY
155
#undef CK_PKCS11_FUNCTION_INFO
156
#undef CK_NEED_ARG_LIST
157
158
#undef __PASTE
159
160
CK_NSS_MODULE_FUNCTIONS sftk_module_funcList = {
161
    { 1, 0 },
162
    NSC_ModuleDBFunc
163
};
164
165
static CK_RV
166
nsc_NSSGetFIPSStatus(CK_SESSION_HANDLE hSession,
167
                     CK_OBJECT_HANDLE hObject,
168
                     CK_ULONG ulOperationType,
169
                     CK_ULONG *pulFIPSStatus);
170
CK_NSS_FIPS_FUNCTIONS sftk_fips_funcList = {
171
    { 1, 0 },
172
    nsc_NSSGetFIPSStatus
173
};
174
175
CK_NSS_KEM_FUNCTIONS sftk_kem_funcList = {
176
    { 1, 0 },
177
    NSC_Encapsulate,
178
    NSC_Decapsulate
179
};
180
181
/*
182
 * Array is orderd by default first
183
 */
184
static CK_INTERFACE nss_interfaces[] = {
185
    { (CK_UTF8CHAR_PTR) "PKCS 11", &sftk_funcList, NSS_INTERFACE_FLAGS },
186
    { (CK_UTF8CHAR_PTR) "PKCS 11", &sftk_funcList_v2, NSS_INTERFACE_FLAGS },
187
    { (CK_UTF8CHAR_PTR) "Vendor NSS Module Interface", &sftk_module_funcList, NSS_INTERFACE_FLAGS },
188
    { (CK_UTF8CHAR_PTR) "Vendor NSS FIPS Interface", &sftk_fips_funcList, NSS_INTERFACE_FLAGS },
189
    { (CK_UTF8CHAR_PTR) "Vendor NSS KEM Interface", &sftk_kem_funcList, NSS_INTERFACE_FLAGS }
190
};
191
/* must match the count of interfaces in nss_interfaces above */
192
955
#define NSS_INTERFACE_COUNT 5
193
194
/* List of DES Weak Keys */
195
typedef unsigned char desKey[8];
196
static const desKey sftk_desWeakTable[] = {
197
#ifdef noParity
198
    /* weak */
199
    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
200
    { 0x1e, 0x1e, 0x1e, 0x1e, 0x0e, 0x0e, 0x0e, 0x0e },
201
    { 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0xf0, 0xf0 },
202
    { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe },
203
    /* semi-weak */
204
    { 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe },
205
    { 0xfe, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0xfe },
206
207
    { 0x1e, 0xe0, 0x1e, 0xe0, 0x0e, 0xf0, 0x0e, 0xf0 },
208
    { 0xe0, 0x1e, 0xe0, 0x1e, 0xf0, 0x0e, 0xf0, 0x0e },
209
210
    { 0x00, 0xe0, 0x00, 0xe0, 0x00, 0x0f, 0x00, 0x0f },
211
    { 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00 },
212
213
    { 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe },
214
    { 0xfe, 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e },
215
216
    { 0x00, 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e },
217
    { 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e, 0x00 },
218
219
    { 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0, 0xfe },
220
    { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0 },
221
#else
222
    /* weak */
223
    { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
224
    { 0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e },
225
    { 0xe0, 0xe0, 0xe0, 0xe0, 0xf1, 0xf1, 0xf1, 0xf1 },
226
    { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe },
227
228
    /* semi-weak */
229
    { 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe },
230
    { 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01 },
231
232
    { 0x1f, 0xe0, 0x1f, 0xe0, 0x0e, 0xf1, 0x0e, 0xf1 },
233
    { 0xe0, 0x1f, 0xe0, 0x1f, 0xf1, 0x0e, 0xf1, 0x0e },
234
235
    { 0x01, 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1 },
236
    { 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1, 0x01 },
237
238
    { 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe },
239
    { 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e },
240
241
    { 0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e },
242
    { 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01 },
243
244
    { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe },
245
    { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1 }
246
#endif
247
};
248
249
static const int sftk_desWeakTableSize = sizeof(sftk_desWeakTable) /
250
                                         sizeof(sftk_desWeakTable[0]);
251
252
/* DES KEY Parity conversion table. Takes each byte/2 as an index, returns
253
 * that byte with the proper parity bit set */
254
static const unsigned char parityTable[256] = {
255
    /* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */
256
    /* E */ 0x01, 0x02, 0x04, 0x07, 0x08, 0x0b, 0x0d, 0x0e,
257
    /* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */
258
    /* O */ 0x10, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c, 0x1f,
259
    /* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */
260
    /* O */ 0x20, 0x23, 0x25, 0x26, 0x29, 0x2a, 0x2c, 0x2f,
261
    /* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */
262
    /* E */ 0x31, 0x32, 0x34, 0x37, 0x38, 0x3b, 0x3d, 0x3e,
263
    /* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */
264
    /* O */ 0x40, 0x43, 0x45, 0x46, 0x49, 0x4a, 0x4c, 0x4f,
265
    /* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */
266
    /* E */ 0x51, 0x52, 0x54, 0x57, 0x58, 0x5b, 0x5d, 0x5e,
267
    /* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */
268
    /* E */ 0x61, 0x62, 0x64, 0x67, 0x68, 0x6b, 0x6d, 0x6e,
269
    /* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */
270
    /* O */ 0x70, 0x73, 0x75, 0x76, 0x79, 0x7a, 0x7c, 0x7f,
271
    /* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */
272
    /* O */ 0x80, 0x83, 0x85, 0x86, 0x89, 0x8a, 0x8c, 0x8f,
273
    /* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */
274
    /* E */ 0x91, 0x92, 0x94, 0x97, 0x98, 0x9b, 0x9d, 0x9e,
275
    /* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */
276
    /* E */ 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xab, 0xad, 0xae,
277
    /* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */
278
    /* O */ 0xb0, 0xb3, 0xb5, 0xb6, 0xb9, 0xba, 0xbc, 0xbf,
279
    /* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */
280
    /* E */ 0xc1, 0xc2, 0xc4, 0xc7, 0xc8, 0xcb, 0xcd, 0xce,
281
    /* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */
282
    /* O */ 0xd0, 0xd3, 0xd5, 0xd6, 0xd9, 0xda, 0xdc, 0xdf,
283
    /* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */
284
    /* O */ 0xe0, 0xe3, 0xe5, 0xe6, 0xe9, 0xea, 0xec, 0xef,
285
    /* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */
286
    /* E */ 0xf1, 0xf2, 0xf4, 0xf7, 0xf8, 0xfb, 0xfd, 0xfe
287
};
288
289
/* Mechanisms */
290
struct mechanismList {
291
    CK_MECHANISM_TYPE type;
292
    CK_MECHANISM_INFO info;
293
    PRBool privkey;
294
};
295
296
/*
297
 * the following table includes a complete list of mechanism defined by
298
 * PKCS #11 version 2.01. Those Mechanisms not supported by this PKCS #11
299
 * module are ifdef'ed out.
300
 */
301
#define CKF_EN_DE CKF_ENCRYPT | CKF_DECRYPT
302
#define CKF_WR_UN CKF_WRAP | CKF_UNWRAP
303
#define CKF_SN_VR CKF_SIGN | CKF_VERIFY
304
#define CKF_SN_RE CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER
305
#define CKF_EN_DE_MSG CKF_ENCRYPT | CKF_DECRYPT | CKF_MESSAGE_ENCRYPT | CKF_MESSAGE_DECRYPT
306
307
#define CKF_EN_DE_WR_UN CKF_EN_DE | CKF_WR_UN
308
#define CKF_SN_VR_RE CKF_SN_VR | CKF_SN_RE
309
#define CKF_DUZ_IT_ALL CKF_EN_DE_WR_UN | CKF_SN_VR_RE
310
311
#define CKF_EC_PNU CKF_EC_F_P | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS
312
313
#define CKF_EC_BPNU CKF_EC_F_2M | CKF_EC_PNU
314
#define CKF_EC_POC CKF_EC_F_P | CKF_EC_OID | CKF_EC_COMPRESS
315
316
#define CK_MAX 0xffffffff
317
318
static const struct mechanismList mechanisms[] = {
319
320
    /*
321
     * PKCS #11 Mechanism List.
322
     *
323
     * The first argument is the PKCS #11 Mechanism we support.
324
     * The second argument is Mechanism info structure. It includes:
325
     *    The minimum key size,
326
     *       in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs.
327
     *       in bytes for RC5, AES, Camellia, and CAST*
328
     *       ignored for DES*, IDEA and FORTEZZA based
329
     *    The maximum key size,
330
     *       in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs.
331
     *       in bytes for RC5, AES, Camellia, and CAST*
332
     *       ignored for DES*, IDEA and FORTEZZA based
333
     *     Flags
334
     *       What operations are supported by this mechanism.
335
     *  The third argument is a bool which tells if this mechanism is
336
     *    supported in the database token.
337
     *
338
     */
339
340
    /* ------------------------- RSA Operations ---------------------------*/
341
    { CKM_RSA_PKCS_KEY_PAIR_GEN, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
342
    { CKM_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE },
343
    { CKM_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
344
    { CKM_RSA_PKCS_OAEP, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_EN_DE_WR_UN }, PR_TRUE },
345
#ifdef SFTK_RSA9796_SUPPORTED
346
    { CKM_RSA_9796, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE },
347
#endif
348
    { CKM_RSA_X_509, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE },
349
    /* -------------- RSA Multipart Signing Operations -------------------- */
350
    { CKM_MD2_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
351
    { CKM_MD5_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
352
    { CKM_SHA1_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
353
    { CKM_SHA224_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
354
    { CKM_SHA256_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
355
    { CKM_SHA384_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
356
    { CKM_SHA512_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
357
    { CKM_SHA1_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
358
    { CKM_SHA224_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
359
    { CKM_SHA256_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
360
    { CKM_SHA384_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
361
    { CKM_SHA512_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE },
362
    /* ------------------------- DSA Operations --------------------------- */
363
    { CKM_DSA_KEY_PAIR_GEN, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
364
    { CKM_DSA, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
365
    { CKM_DSA_PARAMETER_GEN, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_GENERATE }, PR_TRUE },
366
    { CKM_DSA_SHA1, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
367
    { CKM_DSA_SHA224, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
368
    { CKM_DSA_SHA256, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
369
    { CKM_DSA_SHA384, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
370
    { CKM_DSA_SHA512, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE },
371
    /* -------------------- Diffie Hellman Operations --------------------- */
372
    /* no diffie hellman yet */
373
    { CKM_DH_PKCS_KEY_PAIR_GEN, { DH_MIN_P_BITS, DH_MAX_P_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
374
    { CKM_DH_PKCS_DERIVE, { DH_MIN_P_BITS, DH_MAX_P_BITS, CKF_DERIVE }, PR_TRUE },
375
    /* -------------------- Elliptic Curve Operations --------------------- */
376
    { CKM_EC_KEY_PAIR_GEN, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_GENERATE_KEY_PAIR | CKF_EC_BPNU }, PR_TRUE },
377
    { CKM_NSS_ECDHE_NO_PAIRWISE_CHECK_KEY_PAIR_GEN, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_GENERATE_KEY_PAIR | CKF_EC_BPNU }, PR_TRUE },
378
    { CKM_ECDH1_DERIVE, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_DERIVE | CKF_EC_BPNU }, PR_TRUE },
379
    { CKM_ECDSA, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
380
    { CKM_ECDSA_SHA1, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
381
    { CKM_ECDSA_SHA224, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
382
    { CKM_ECDSA_SHA256, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
383
    { CKM_ECDSA_SHA384, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
384
    { CKM_ECDSA_SHA512, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE },
385
    { CKM_EC_EDWARDS_KEY_PAIR_GEN, { ECD_MIN_KEY_BITS, ECD_MAX_KEY_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
386
    { CKM_EC_MONTGOMERY_KEY_PAIR_GEN, { ECD_MIN_KEY_BITS, ECD_MAX_KEY_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
387
    { CKM_EDDSA, { ECD_MIN_KEY_BITS, ECD_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_POC }, PR_TRUE },
388
    /* ------------------------- RC2 Operations --------------------------- */
389
    { CKM_RC2_KEY_GEN, { 1, 128, CKF_GENERATE }, PR_TRUE },
390
    { CKM_RC2_ECB, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE },
391
    { CKM_RC2_CBC, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE },
392
    { CKM_RC2_MAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
393
    { CKM_RC2_MAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
394
    { CKM_RC2_CBC_PAD, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE },
395
    /* ------------------------- RC4 Operations --------------------------- */
396
    { CKM_RC4_KEY_GEN, { 1, 256, CKF_GENERATE }, PR_FALSE },
397
    { CKM_RC4, { 1, 256, CKF_EN_DE_WR_UN }, PR_FALSE },
398
    /* ------------------------- DES Operations --------------------------- */
399
    { CKM_DES_KEY_GEN, { 8, 8, CKF_GENERATE }, PR_TRUE },
400
    { CKM_DES_ECB, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
401
    { CKM_DES_CBC, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
402
    { CKM_DES_MAC, { 8, 8, CKF_SN_VR }, PR_TRUE },
403
    { CKM_DES_MAC_GENERAL, { 8, 8, CKF_SN_VR }, PR_TRUE },
404
    { CKM_DES_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
405
    { CKM_DES2_KEY_GEN, { 24, 24, CKF_GENERATE }, PR_TRUE },
406
    { CKM_DES3_KEY_GEN, { 24, 24, CKF_GENERATE }, PR_TRUE },
407
    { CKM_DES3_ECB, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE },
408
    { CKM_DES3_CBC, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE },
409
    { CKM_DES3_MAC, { 24, 24, CKF_SN_VR }, PR_TRUE },
410
    { CKM_DES3_MAC_GENERAL, { 24, 24, CKF_SN_VR }, PR_TRUE },
411
    { CKM_DES3_CBC_PAD, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE },
412
    /* ------------------------- CDMF Operations --------------------------- */
413
    { CKM_CDMF_KEY_GEN, { 8, 8, CKF_GENERATE }, PR_TRUE },
414
    { CKM_CDMF_ECB, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
415
    { CKM_CDMF_CBC, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
416
    { CKM_CDMF_MAC, { 8, 8, CKF_SN_VR }, PR_TRUE },
417
    { CKM_CDMF_MAC_GENERAL, { 8, 8, CKF_SN_VR }, PR_TRUE },
418
    { CKM_CDMF_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
419
    /* ------------------------- AES Operations --------------------------- */
420
    { CKM_AES_KEY_GEN, { 16, 32, CKF_GENERATE }, PR_TRUE },
421
    { CKM_AES_ECB, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
422
    { CKM_AES_CBC, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
423
    { CKM_AES_MAC, { 16, 32, CKF_SN_VR }, PR_TRUE },
424
    { CKM_AES_MAC_GENERAL, { 16, 32, CKF_SN_VR }, PR_TRUE },
425
    { CKM_AES_CMAC, { 16, 32, CKF_SN_VR }, PR_TRUE },
426
    { CKM_AES_CMAC_GENERAL, { 16, 32, CKF_SN_VR }, PR_TRUE },
427
    { CKM_AES_CBC_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
428
    { CKM_AES_CTS, { 16, 32, CKF_EN_DE }, PR_TRUE },
429
    { CKM_AES_CTR, { 16, 32, CKF_EN_DE }, PR_TRUE },
430
    { CKM_AES_GCM, { 16, 32, CKF_EN_DE_MSG }, PR_TRUE },
431
    { CKM_AES_XCBC_MAC_96, { 12, 12, CKF_SN_VR }, PR_TRUE },
432
    { CKM_AES_XCBC_MAC, { 16, 16, CKF_SN_VR }, PR_TRUE },
433
    /* ------------------------- Camellia Operations --------------------- */
434
    { CKM_CAMELLIA_KEY_GEN, { 16, 32, CKF_GENERATE }, PR_TRUE },
435
    { CKM_CAMELLIA_ECB, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
436
    { CKM_CAMELLIA_CBC, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
437
    { CKM_CAMELLIA_MAC, { 16, 32, CKF_SN_VR }, PR_TRUE },
438
    { CKM_CAMELLIA_MAC_GENERAL, { 16, 32, CKF_SN_VR }, PR_TRUE },
439
    { CKM_CAMELLIA_CBC_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
440
/* ------------------------- SEED Operations --------------------------- */
441
#ifndef NSS_DISABLE_DEPRECATED_SEED
442
    { CKM_SEED_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
443
    { CKM_SEED_ECB, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
444
    { CKM_SEED_CBC, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
445
    { CKM_SEED_MAC, { 16, 16, CKF_SN_VR }, PR_TRUE },
446
    { CKM_SEED_MAC_GENERAL, { 16, 16, CKF_SN_VR }, PR_TRUE },
447
    { CKM_SEED_CBC_PAD, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
448
#endif
449
/* ------------------------- ChaCha20 Operations ---------------------- */
450
#ifndef NSS_DISABLE_CHACHAPOLY
451
    { CKM_NSS_CHACHA20_KEY_GEN, { 32, 32, CKF_GENERATE }, PR_TRUE },
452
    { CKM_NSS_CHACHA20_POLY1305, { 32, 32, CKF_EN_DE }, PR_TRUE },
453
    { CKM_NSS_CHACHA20_CTR, { 32, 32, CKF_EN_DE }, PR_TRUE },
454
    { CKM_CHACHA20_KEY_GEN, { 32, 32, CKF_GENERATE }, PR_TRUE },
455
    { CKM_CHACHA20, { 32, 32, CKF_EN_DE }, PR_TRUE },
456
    { CKM_CHACHA20_POLY1305, { 32, 32, CKF_EN_DE_MSG }, PR_TRUE },
457
#endif /* NSS_DISABLE_CHACHAPOLY */
458
    /* ------------------------- Hashing Operations ----------------------- */
459
    { CKM_MD2, { 0, 0, CKF_DIGEST }, PR_FALSE },
460
    { CKM_MD2_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
461
    { CKM_MD2_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
462
    { CKM_MD5, { 0, 0, CKF_DIGEST }, PR_FALSE },
463
    { CKM_MD5_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
464
    { CKM_MD5_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
465
    { CKM_SHA_1, { 0, 0, CKF_DIGEST }, PR_FALSE },
466
    { CKM_SHA_1_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
467
    { CKM_SHA_1_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
468
    { CKM_SHA224, { 0, 0, CKF_DIGEST }, PR_FALSE },
469
    { CKM_SHA224_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
470
    { CKM_SHA224_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
471
    { CKM_SHA256, { 0, 0, CKF_DIGEST }, PR_FALSE },
472
    { CKM_SHA256_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
473
    { CKM_SHA256_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
474
    { CKM_SHA384, { 0, 0, CKF_DIGEST }, PR_FALSE },
475
    { CKM_SHA384_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
476
    { CKM_SHA384_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
477
    { CKM_SHA512, { 0, 0, CKF_DIGEST }, PR_FALSE },
478
    { CKM_SHA512_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
479
    { CKM_SHA512_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
480
    { CKM_SHA3_224, { 0, 0, CKF_DIGEST }, PR_FALSE },
481
    { CKM_SHA3_224_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
482
    { CKM_SHA3_224_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
483
    { CKM_SHA3_256, { 0, 0, CKF_DIGEST }, PR_FALSE },
484
    { CKM_SHA3_256_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
485
    { CKM_SHA3_256_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
486
    { CKM_SHA3_384, { 0, 0, CKF_DIGEST }, PR_FALSE },
487
    { CKM_SHA3_384_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
488
    { CKM_SHA3_384_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
489
    { CKM_SHA3_512, { 0, 0, CKF_DIGEST }, PR_FALSE },
490
    { CKM_SHA3_512_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE },
491
    { CKM_SHA3_512_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE },
492
    { CKM_TLS_PRF_GENERAL, { 0, 512, CKF_SN_VR }, PR_FALSE },
493
    { CKM_TLS_MAC, { 0, 512, CKF_SN_VR }, PR_FALSE },
494
    { CKM_NSS_TLS_PRF_GENERAL_SHA256,
495
      { 0, 512, CKF_SN_VR },
496
      PR_FALSE },
497
    /* ------------------------- HKDF Operations -------------------------- */
498
    { CKM_HKDF_DERIVE, { 1, 255 * 64, CKF_DERIVE }, PR_TRUE },
499
    { CKM_HKDF_DATA, { 1, 255 * 64, CKF_DERIVE }, PR_TRUE },
500
    { CKM_HKDF_KEY_GEN, { 20, 64, CKF_GENERATE }, PR_TRUE },
501
    { CKM_NSS_HKDF_SHA1, { 1, 128, CKF_DERIVE }, PR_TRUE },
502
    { CKM_NSS_HKDF_SHA256, { 1, 128, CKF_DERIVE }, PR_TRUE },
503
    { CKM_NSS_HKDF_SHA384, { 1, 128, CKF_DERIVE }, PR_TRUE },
504
    { CKM_NSS_HKDF_SHA512, { 1, 128, CKF_DERIVE }, PR_TRUE },
505
/* ------------------------- CAST Operations --------------------------- */
506
#ifdef NSS_SOFTOKEN_DOES_CAST
507
    /* Cast operations are not supported ( yet? ) */
508
    { CKM_CAST_KEY_GEN, { 1, 8, CKF_GENERATE }, PR_TRUE },
509
    { CKM_CAST_ECB, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
510
    { CKM_CAST_CBC, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
511
    { CKM_CAST_MAC, { 1, 8, CKF_SN_VR }, PR_TRUE },
512
    { CKM_CAST_MAC_GENERAL, { 1, 8, CKF_SN_VR }, PR_TRUE },
513
    { CKM_CAST_CBC_PAD, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE },
514
    { CKM_CAST3_KEY_GEN, { 1, 16, CKF_GENERATE }, PR_TRUE },
515
    { CKM_CAST3_ECB, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
516
    { CKM_CAST3_CBC, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
517
    { CKM_CAST3_MAC, { 1, 16, CKF_SN_VR }, PR_TRUE },
518
    { CKM_CAST3_MAC_GENERAL, { 1, 16, CKF_SN_VR }, PR_TRUE },
519
    { CKM_CAST3_CBC_PAD, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
520
    { CKM_CAST5_KEY_GEN, { 1, 16, CKF_GENERATE }, PR_TRUE },
521
    { CKM_CAST5_ECB, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
522
    { CKM_CAST5_CBC, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
523
    { CKM_CAST5_MAC, { 1, 16, CKF_SN_VR }, PR_TRUE },
524
    { CKM_CAST5_MAC_GENERAL, { 1, 16, CKF_SN_VR }, PR_TRUE },
525
    { CKM_CAST5_CBC_PAD, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
526
#endif
527
#if NSS_SOFTOKEN_DOES_RC5
528
    /* ------------------------- RC5 Operations --------------------------- */
529
    { CKM_RC5_KEY_GEN, { 1, 32, CKF_GENERATE }, PR_TRUE },
530
    { CKM_RC5_ECB, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
531
    { CKM_RC5_CBC, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
532
    { CKM_RC5_MAC, { 1, 32, CKF_SN_VR }, PR_TRUE },
533
    { CKM_RC5_MAC_GENERAL, { 1, 32, CKF_SN_VR }, PR_TRUE },
534
    { CKM_RC5_CBC_PAD, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
535
#endif
536
#ifdef NSS_SOFTOKEN_DOES_IDEA
537
    /* ------------------------- IDEA Operations -------------------------- */
538
    { CKM_IDEA_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
539
    { CKM_IDEA_ECB, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
540
    { CKM_IDEA_CBC, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
541
    { CKM_IDEA_MAC, { 16, 16, CKF_SN_VR }, PR_TRUE },
542
    { CKM_IDEA_MAC_GENERAL, { 16, 16, CKF_SN_VR }, PR_TRUE },
543
    { CKM_IDEA_CBC_PAD, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE },
544
#endif
545
    /* --------------------- Secret Key Operations ------------------------ */
546
    { CKM_GENERIC_SECRET_KEY_GEN, { 1, 32, CKF_GENERATE }, PR_TRUE },
547
    { CKM_CONCATENATE_BASE_AND_KEY, { 1, 32, CKF_DERIVE }, PR_FALSE },
548
    { CKM_CONCATENATE_BASE_AND_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
549
    { CKM_CONCATENATE_DATA_AND_BASE, { 1, 32, CKF_DERIVE }, PR_FALSE },
550
    { CKM_XOR_BASE_AND_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
551
    { CKM_EXTRACT_KEY_FROM_KEY, { 1, 32, CKF_DERIVE }, PR_FALSE },
552
    { CKM_DES3_ECB_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
553
    { CKM_DES3_CBC_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
554
    { CKM_AES_ECB_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
555
    { CKM_AES_CBC_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
556
    { CKM_CAMELLIA_ECB_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
557
    { CKM_CAMELLIA_CBC_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
558
#ifndef NSS_DISABLE_DEPRECATED_SEED
559
    { CKM_SEED_ECB_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
560
    { CKM_SEED_CBC_ENCRYPT_DATA, { 1, 32, CKF_DERIVE }, PR_FALSE },
561
#endif
562
    /* ---------------------- SSL Key Derivations ------------------------- */
563
    { CKM_SSL3_PRE_MASTER_KEY_GEN, { 48, 48, CKF_GENERATE }, PR_FALSE },
564
    { CKM_SSL3_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
565
    { CKM_SSL3_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE },
566
    { CKM_SSL3_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
567
    { CKM_SSL3_MD5_MAC, { 0, 16, CKF_DERIVE }, PR_FALSE },
568
    { CKM_SSL3_SHA1_MAC, { 0, 20, CKF_DERIVE }, PR_FALSE },
569
    { CKM_MD5_KEY_DERIVATION, { 0, 16, CKF_DERIVE }, PR_FALSE },
570
    { CKM_MD2_KEY_DERIVATION, { 0, 16, CKF_DERIVE }, PR_FALSE },
571
    { CKM_SHA1_KEY_DERIVATION, { 0, 20, CKF_DERIVE }, PR_FALSE },
572
    { CKM_SHA224_KEY_DERIVATION, { 0, 28, CKF_DERIVE }, PR_FALSE },
573
    { CKM_SHA256_KEY_DERIVATION, { 0, 32, CKF_DERIVE }, PR_FALSE },
574
    { CKM_SHA384_KEY_DERIVATION, { 0, 48, CKF_DERIVE }, PR_FALSE },
575
    { CKM_SHA512_KEY_DERIVATION, { 0, 64, CKF_DERIVE }, PR_FALSE },
576
    { CKM_TLS_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
577
    { CKM_TLS12_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
578
    { CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256,
579
      { 48, 48, CKF_DERIVE },
580
      PR_FALSE },
581
    { CKM_TLS_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE },
582
    { CKM_TLS12_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE },
583
    { CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256,
584
      { 8, 128, CKF_DERIVE },
585
      PR_FALSE },
586
    { CKM_TLS_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
587
    { CKM_TLS12_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE },
588
    { CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256,
589
      { 48, 48, CKF_DERIVE },
590
      PR_FALSE },
591
    { CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE,
592
      { 48, 128, CKF_DERIVE },
593
      PR_FALSE },
594
    { CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH,
595
      { 48, 128, CKF_DERIVE },
596
      PR_FALSE },
597
    /* ---------------------- PBE Key Derivations  ------------------------ */
598
    { CKM_PBE_MD2_DES_CBC, { 8, 8, CKF_DERIVE }, PR_TRUE },
599
    { CKM_PBE_MD5_DES_CBC, { 8, 8, CKF_DERIVE }, PR_TRUE },
600
    /* ------------------ NSS PBE Key Derivations  ------------------- */
601
    { CKM_NSS_PBE_SHA1_DES_CBC, { 8, 8, CKF_GENERATE }, PR_TRUE },
602
    { CKM_NSS_PBE_SHA1_FAULTY_3DES_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE },
603
    { CKM_PBE_SHA1_DES3_EDE_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE },
604
    { CKM_PBE_SHA1_DES2_EDE_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE },
605
    { CKM_PBE_SHA1_RC2_40_CBC, { 40, 40, CKF_GENERATE }, PR_TRUE },
606
    { CKM_PBE_SHA1_RC2_128_CBC, { 128, 128, CKF_GENERATE }, PR_TRUE },
607
    { CKM_PBE_SHA1_RC4_40, { 40, 40, CKF_GENERATE }, PR_TRUE },
608
    { CKM_PBE_SHA1_RC4_128, { 128, 128, CKF_GENERATE }, PR_TRUE },
609
    { CKM_PBA_SHA1_WITH_SHA1_HMAC, { 20, 20, CKF_GENERATE }, PR_TRUE },
610
    { CKM_PKCS5_PBKD2, { 1, 256, CKF_GENERATE }, PR_TRUE },
611
    { CKM_NSS_PBE_SHA1_HMAC_KEY_GEN, { 20, 20, CKF_GENERATE }, PR_TRUE },
612
    { CKM_NSS_PBE_MD5_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
613
    { CKM_NSS_PBE_MD2_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
614
    { CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN, { 28, 28, CKF_GENERATE }, PR_TRUE },
615
    { CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN, { 32, 32, CKF_GENERATE }, PR_TRUE },
616
    { CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN, { 48, 48, CKF_GENERATE }, PR_TRUE },
617
    { CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN, { 64, 64, CKF_GENERATE }, PR_TRUE },
618
    /* ------------------ NIST 800-108 Key Derivations  ------------------- */
619
    { CKM_SP800_108_COUNTER_KDF, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
620
    { CKM_SP800_108_FEEDBACK_KDF, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
621
    { CKM_SP800_108_DOUBLE_PIPELINE_KDF, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
622
    { CKM_NSS_SP800_108_COUNTER_KDF_DERIVE_DATA, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
623
    { CKM_NSS_SP800_108_FEEDBACK_KDF_DERIVE_DATA, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
624
    { CKM_NSS_SP800_108_DOUBLE_PIPELINE_KDF_DERIVE_DATA, { 0, CK_MAX, CKF_DERIVE }, PR_TRUE },
625
    /* ------------------ AES Key Wrap (also encrypt)  ------------------- */
626
    { CKM_NSS_AES_KEY_WRAP, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
627
    { CKM_NSS_AES_KEY_WRAP_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
628
    { CKM_AES_KEY_WRAP, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
629
    { CKM_AES_KEY_WRAP_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
630
    { CKM_AES_KEY_WRAP_KWP, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
631
    /* --------------------------- J-PAKE -------------------------------- */
632
    { CKM_NSS_JPAKE_ROUND1_SHA1, { 0, 0, CKF_GENERATE }, PR_TRUE },
633
    { CKM_NSS_JPAKE_ROUND1_SHA256, { 0, 0, CKF_GENERATE }, PR_TRUE },
634
    { CKM_NSS_JPAKE_ROUND1_SHA384, { 0, 0, CKF_GENERATE }, PR_TRUE },
635
    { CKM_NSS_JPAKE_ROUND1_SHA512, { 0, 0, CKF_GENERATE }, PR_TRUE },
636
    { CKM_NSS_JPAKE_ROUND2_SHA1, { 0, 0, CKF_DERIVE }, PR_TRUE },
637
    { CKM_NSS_JPAKE_ROUND2_SHA256, { 0, 0, CKF_DERIVE }, PR_TRUE },
638
    { CKM_NSS_JPAKE_ROUND2_SHA384, { 0, 0, CKF_DERIVE }, PR_TRUE },
639
    { CKM_NSS_JPAKE_ROUND2_SHA512, { 0, 0, CKF_DERIVE }, PR_TRUE },
640
    { CKM_NSS_JPAKE_FINAL_SHA1, { 0, 0, CKF_DERIVE }, PR_TRUE },
641
    { CKM_NSS_JPAKE_FINAL_SHA256, { 0, 0, CKF_DERIVE }, PR_TRUE },
642
    { CKM_NSS_JPAKE_FINAL_SHA384, { 0, 0, CKF_DERIVE }, PR_TRUE },
643
    { CKM_NSS_JPAKE_FINAL_SHA512, { 0, 0, CKF_DERIVE }, PR_TRUE },
644
    /* -------------------- Constant Time TLS MACs ----------------------- */
645
    { CKM_NSS_HMAC_CONSTANT_TIME, { 0, 0, CKF_DIGEST }, PR_TRUE },
646
    { CKM_NSS_SSL3_MAC_CONSTANT_TIME, { 0, 0, CKF_DIGEST }, PR_TRUE },
647
    /* -------------------- IPSEC ----------------------- */
648
    { CKM_IKE2_PRF_PLUS_DERIVE, { 8, 255 * 64, CKF_DERIVE }, PR_TRUE },
649
    { CKM_IKE_PRF_DERIVE, { 8, 64, CKF_DERIVE }, PR_TRUE },
650
    { CKM_IKE1_PRF_DERIVE, { 8, 64, CKF_DERIVE }, PR_TRUE },
651
    { CKM_IKE1_EXTENDED_DERIVE, { 8, 255 * 64, CKF_DERIVE }, PR_TRUE },
652
    { CKM_NSS_IKE_PRF_PLUS_DERIVE, { 8, 255 * 64, CKF_DERIVE }, PR_TRUE },
653
    { CKM_NSS_IKE_PRF_DERIVE, { 8, 64, CKF_DERIVE }, PR_TRUE },
654
    { CKM_NSS_IKE1_PRF_DERIVE, { 8, 64, CKF_DERIVE }, PR_TRUE },
655
    { CKM_NSS_IKE1_APP_B_PRF_DERIVE, { 8, 255 * 64, CKF_DERIVE }, PR_TRUE },
656
    /* -------------------- Kyber Operations ----------------------- */
657
    { CKM_NSS_KYBER_KEY_PAIR_GEN, { 0, 0, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
658
    { CKM_NSS_KYBER, { 0, 0, 0 }, PR_TRUE },
659
    { CKM_NSS_ML_KEM_KEY_PAIR_GEN, { 0, 0, CKF_GENERATE_KEY_PAIR }, PR_TRUE },
660
    { CKM_NSS_ML_KEM, { 0, 0, 0 }, PR_TRUE },
661
};
662
static const CK_ULONG mechanismCount = sizeof(mechanisms) / sizeof(mechanisms[0]);
663
664
/* sigh global so fipstokn can read it */
665
PRBool nsc_init = PR_FALSE;
666
667
#if defined(CHECK_FORK_PTHREAD) || defined(CHECK_FORK_MIXED)
668
669
#include <pthread.h>
670
671
static void
672
ForkedChild(void)
673
{
674
    if (nsc_init || nsf_init) {
675
        forked = PR_TRUE;
676
    }
677
}
678
679
#endif
680
681
#define SFTKFreeWrap(ctxtype, mmm) \
682
    void SFTKFree_##mmm(void *vp)  \
683
123k
    {                              \
684
123k
        ctxtype *p = vp;           \
685
123k
        mmm(p);                    \
686
123k
    }
SFTKFree_nsslowkey_DestroyPublicKey
Line
Count
Source
683
70.5k
    {                              \
684
70.5k
        ctxtype *p = vp;           \
685
70.5k
        mmm(p);                    \
686
70.5k
    }
SFTKFree_nsslowkey_DestroyPrivateKey
Line
Count
Source
683
52.8k
    {                              \
684
52.8k
        ctxtype *p = vp;           \
685
52.8k
        mmm(p);                    \
686
52.8k
    }
687
688
SFTKFreeWrap(NSSLOWKEYPublicKey, nsslowkey_DestroyPublicKey);
689
SFTKFreeWrap(NSSLOWKEYPrivateKey, nsslowkey_DestroyPrivateKey);
690
691
static char *
692
sftk_setStringName(const char *inString, char *buffer, int buffer_length, PRBool nullTerminate)
693
24
{
694
24
    int full_length, string_length;
695
696
24
    full_length = nullTerminate ? buffer_length - 1 : buffer_length;
697
24
    string_length = PORT_Strlen(inString);
698
    /*
699
     *  shorten the string, respecting utf8 encoding
700
     *  to do so, we work backward from the end
701
     *  bytes looking from the end are either:
702
     *    - ascii [0x00,0x7f]
703
     *    - the [2-n]th byte of a multibyte sequence
704
     *        [0x3F,0xBF], i.e, most significant 2 bits are '10'
705
     *    - the first byte of a multibyte sequence [0xC0,0xFD],
706
     *        i.e, most significant 2 bits are '11'
707
     *
708
     *    When the string is too long, we lop off any trailing '10' bytes,
709
     *  if any. When these are all eliminated we lop off
710
     *  one additional byte. Thus if we lopped any '10'
711
     *  we'll be lopping a '11' byte (the first byte of the multibyte sequence),
712
     *  otherwise we're lopping off an ascii character.
713
     *
714
     *    To test for '10' bytes, we first AND it with
715
     *  11000000 (0xc0) so that we get 10000000 (0x80) if and only if
716
     *  the byte starts with 10. We test for equality.
717
     */
718
24
    while (string_length > full_length) {
719
        /* need to shorten */
720
0
        while (string_length > 0 &&
721
0
               ((inString[string_length - 1] & (char)0xc0) == (char)0x80)) {
722
            /* lop off '10' byte */
723
0
            string_length--;
724
0
        }
725
        /*
726
         * test string_length in case bad data is received
727
         * and string consisted of all '10' bytes,
728
         * avoiding any infinite loop
729
         */
730
0
        if (string_length) {
731
            /* remove either '11' byte or an asci byte */
732
0
            string_length--;
733
0
        }
734
0
    }
735
24
    PORT_Memset(buffer, ' ', full_length);
736
24
    if (nullTerminate) {
737
24
        buffer[full_length] = 0;
738
24
    }
739
24
    PORT_Memcpy(buffer, inString, string_length);
740
24
    return buffer;
741
24
}
742
/*
743
 * Configuration utils
744
 */
745
static CK_RV
746
sftk_configure(const char *man, const char *libdes)
747
4
{
748
749
    /* make sure the internationalization was done correctly... */
750
4
    if (man) {
751
0
        manufacturerID = sftk_setStringName(man, manufacturerID_space,
752
0
                                            sizeof(manufacturerID_space), PR_TRUE);
753
0
    }
754
4
    if (libdes) {
755
0
        libraryDescription = sftk_setStringName(libdes,
756
0
                                                libraryDescription_space, sizeof(libraryDescription_space),
757
0
                                                PR_TRUE);
758
0
    }
759
760
4
    return CKR_OK;
761
4
}
762
763
/*
764
 * ******************** Password Utilities *******************************
765
 */
766
767
/*
768
 * see if the key DB password is enabled
769
 */
770
static PRBool
771
sftk_hasNullPassword(SFTKSlot *slot, SFTKDBHandle *keydb)
772
0
{
773
0
    PRBool pwenabled;
774
775
0
    pwenabled = PR_FALSE;
776
0
    if (sftkdb_HasPasswordSet(keydb) == SECSuccess) {
777
0
        PRBool tokenRemoved = PR_FALSE;
778
0
        SECStatus rv = sftkdb_CheckPasswordNull(keydb, &tokenRemoved);
779
0
        if (tokenRemoved) {
780
0
            sftk_CloseAllSessions(slot, PR_FALSE);
781
0
        }
782
0
        return (rv == SECSuccess);
783
0
    }
784
785
0
    return pwenabled;
786
0
}
787
788
/*
789
 * ******************** Object Creation Utilities ***************************
790
 */
791
792
/* Make sure a given attribute exists. If it doesn't, initialize it to
793
 * value and len
794
 */
795
CK_RV
796
sftk_defaultAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type,
797
                      const void *value, unsigned int len)
798
11.4M
{
799
11.4M
    if (!sftk_hasAttribute(object, type)) {
800
8.44M
        return sftk_AddAttributeType(object, type, value, len);
801
8.44M
    }
802
3.01M
    return CKR_OK;
803
11.4M
}
804
805
/*
806
 * check the consistancy and initialize a Data Object
807
 */
808
static CK_RV
809
sftk_handleDataObject(SFTKSession *session, SFTKObject *object)
810
38.9k
{
811
38.9k
    CK_RV crv;
812
813
    /* first reject private and token data objects */
814
38.9k
    if (sftk_isTrue(object, CKA_PRIVATE) || sftk_isTrue(object, CKA_TOKEN)) {
815
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
816
0
    }
817
818
    /* now just verify the required date fields */
819
38.9k
    crv = sftk_defaultAttribute(object, CKA_APPLICATION, NULL, 0);
820
38.9k
    if (crv != CKR_OK)
821
0
        return crv;
822
38.9k
    crv = sftk_defaultAttribute(object, CKA_VALUE, NULL, 0);
823
38.9k
    if (crv != CKR_OK)
824
0
        return crv;
825
826
38.9k
    return CKR_OK;
827
38.9k
}
828
829
/*
830
 * check the consistancy and initialize a Certificate Object
831
 */
832
static CK_RV
833
sftk_handleCertObject(SFTKSession *session, SFTKObject *object)
834
0
{
835
0
    CK_CERTIFICATE_TYPE type;
836
0
    SFTKAttribute *attribute;
837
0
    CK_RV crv;
838
839
    /* certificates must have a type */
840
0
    if (!sftk_hasAttribute(object, CKA_CERTIFICATE_TYPE)) {
841
0
        return CKR_TEMPLATE_INCOMPLETE;
842
0
    }
843
844
    /* we can't store any certs private */
845
0
    if (sftk_isTrue(object, CKA_PRIVATE)) {
846
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
847
0
    }
848
849
    /* We only support X.509 Certs for now */
850
0
    attribute = sftk_FindAttribute(object, CKA_CERTIFICATE_TYPE);
851
0
    if (attribute == NULL)
852
0
        return CKR_TEMPLATE_INCOMPLETE;
853
0
    type = *(CK_CERTIFICATE_TYPE *)attribute->attrib.pValue;
854
0
    sftk_FreeAttribute(attribute);
855
856
0
    if (type != CKC_X_509) {
857
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
858
0
    }
859
860
    /* X.509 Certificate */
861
862
    /* make sure we have a cert */
863
0
    if (!sftk_hasAttribute(object, CKA_VALUE)) {
864
0
        return CKR_TEMPLATE_INCOMPLETE;
865
0
    }
866
867
    /* in PKCS #11, Subject is a required field */
868
0
    if (!sftk_hasAttribute(object, CKA_SUBJECT)) {
869
0
        return CKR_TEMPLATE_INCOMPLETE;
870
0
    }
871
872
    /* in PKCS #11, Issuer is a required field */
873
0
    if (!sftk_hasAttribute(object, CKA_ISSUER)) {
874
0
        return CKR_TEMPLATE_INCOMPLETE;
875
0
    }
876
877
    /* in PKCS #11, Serial is a required field */
878
0
    if (!sftk_hasAttribute(object, CKA_SERIAL_NUMBER)) {
879
0
        return CKR_TEMPLATE_INCOMPLETE;
880
0
    }
881
882
    /* add it to the object */
883
0
    object->objectInfo = NULL;
884
0
    object->infoFree = (SFTKFree)NULL;
885
886
    /* now just verify the required date fields */
887
0
    crv = sftk_defaultAttribute(object, CKA_ID, NULL, 0);
888
0
    if (crv != CKR_OK) {
889
0
        return crv;
890
0
    }
891
892
0
    if (sftk_isTrue(object, CKA_TOKEN)) {
893
0
        SFTKSlot *slot = session->slot;
894
0
        SFTKDBHandle *certHandle = sftk_getCertDB(slot);
895
896
0
        if (certHandle == NULL) {
897
0
            return CKR_TOKEN_WRITE_PROTECTED;
898
0
        }
899
900
0
        crv = sftkdb_write(certHandle, object, &object->handle);
901
0
        sftk_freeDB(certHandle);
902
0
        return crv;
903
0
    }
904
905
0
    return CKR_OK;
906
0
}
907
908
/*
909
 * check the consistancy and initialize a Trust Object
910
 */
911
static CK_RV
912
sftk_handleTrustObject(SFTKSession *session, SFTKObject *object)
913
0
{
914
    /* we can't store any certs private */
915
0
    if (sftk_isTrue(object, CKA_PRIVATE)) {
916
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
917
0
    }
918
919
    /* certificates must have a type */
920
0
    if (!sftk_hasAttribute(object, CKA_ISSUER)) {
921
0
        return CKR_TEMPLATE_INCOMPLETE;
922
0
    }
923
0
    if (!sftk_hasAttribute(object, CKA_SERIAL_NUMBER)) {
924
0
        return CKR_TEMPLATE_INCOMPLETE;
925
0
    }
926
0
    if (!sftk_hasAttribute(object, CKA_CERT_SHA1_HASH)) {
927
0
        return CKR_TEMPLATE_INCOMPLETE;
928
0
    }
929
0
    if (!sftk_hasAttribute(object, CKA_CERT_MD5_HASH)) {
930
0
        return CKR_TEMPLATE_INCOMPLETE;
931
0
    }
932
933
0
    if (sftk_isTrue(object, CKA_TOKEN)) {
934
0
        SFTKSlot *slot = session->slot;
935
0
        SFTKDBHandle *certHandle = sftk_getCertDB(slot);
936
0
        CK_RV crv;
937
938
0
        if (certHandle == NULL) {
939
0
            return CKR_TOKEN_WRITE_PROTECTED;
940
0
        }
941
942
0
        crv = sftkdb_write(certHandle, object, &object->handle);
943
0
        sftk_freeDB(certHandle);
944
0
        return crv;
945
0
    }
946
947
0
    return CKR_OK;
948
0
}
949
950
/*
951
 * check the consistancy and initialize a Trust Object
952
 */
953
static CK_RV
954
sftk_handleSMimeObject(SFTKSession *session, SFTKObject *object)
955
0
{
956
957
    /* we can't store any certs private */
958
0
    if (sftk_isTrue(object, CKA_PRIVATE)) {
959
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
960
0
    }
961
962
    /* certificates must have a type */
963
0
    if (!sftk_hasAttribute(object, CKA_SUBJECT)) {
964
0
        return CKR_TEMPLATE_INCOMPLETE;
965
0
    }
966
0
    if (!sftk_hasAttribute(object, CKA_NSS_EMAIL)) {
967
0
        return CKR_TEMPLATE_INCOMPLETE;
968
0
    }
969
970
0
    if (sftk_isTrue(object, CKA_TOKEN)) {
971
0
        SFTKSlot *slot = session->slot;
972
0
        SFTKDBHandle *certHandle;
973
0
        CK_RV crv;
974
975
0
        PORT_Assert(slot);
976
0
        if (slot == NULL) {
977
0
            return CKR_SESSION_HANDLE_INVALID;
978
0
        }
979
980
0
        certHandle = sftk_getCertDB(slot);
981
0
        if (certHandle == NULL) {
982
0
            return CKR_TOKEN_WRITE_PROTECTED;
983
0
        }
984
985
0
        crv = sftkdb_write(certHandle, object, &object->handle);
986
0
        sftk_freeDB(certHandle);
987
0
        return crv;
988
0
    }
989
990
0
    return CKR_OK;
991
0
}
992
993
/*
994
 * check the consistancy and initialize a Trust Object
995
 */
996
static CK_RV
997
sftk_handleCrlObject(SFTKSession *session, SFTKObject *object)
998
0
{
999
1000
    /* we can't store any certs private */
1001
0
    if (sftk_isTrue(object, CKA_PRIVATE)) {
1002
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
1003
0
    }
1004
1005
    /* certificates must have a type */
1006
0
    if (!sftk_hasAttribute(object, CKA_SUBJECT)) {
1007
0
        return CKR_TEMPLATE_INCOMPLETE;
1008
0
    }
1009
0
    if (!sftk_hasAttribute(object, CKA_VALUE)) {
1010
0
        return CKR_TEMPLATE_INCOMPLETE;
1011
0
    }
1012
1013
0
    if (sftk_isTrue(object, CKA_TOKEN)) {
1014
0
        SFTKSlot *slot = session->slot;
1015
0
        SFTKDBHandle *certHandle = sftk_getCertDB(slot);
1016
0
        CK_RV crv;
1017
1018
0
        if (certHandle == NULL) {
1019
0
            return CKR_TOKEN_WRITE_PROTECTED;
1020
0
        }
1021
1022
0
        crv = sftkdb_write(certHandle, object, &object->handle);
1023
0
        sftk_freeDB(certHandle);
1024
0
        return crv;
1025
0
    }
1026
1027
0
    return CKR_OK;
1028
0
}
1029
1030
/*
1031
 * check the consistancy and initialize a Public Key Object
1032
 */
1033
static CK_RV
1034
sftk_handlePublicKeyObject(SFTKSession *session, SFTKObject *object,
1035
                           CK_KEY_TYPE key_type)
1036
71.0k
{
1037
71.0k
    CK_BBOOL encrypt = CK_TRUE;
1038
71.0k
    CK_BBOOL recover = CK_TRUE;
1039
71.0k
    CK_BBOOL wrap = CK_TRUE;
1040
71.0k
    CK_BBOOL derive = CK_FALSE;
1041
71.0k
    CK_BBOOL verify = CK_TRUE;
1042
71.0k
    CK_RV crv;
1043
1044
71.0k
    switch (key_type) {
1045
16.8k
        case CKK_RSA:
1046
16.8k
            crv = sftk_ConstrainAttribute(object, CKA_MODULUS,
1047
16.8k
                                          RSA_MIN_MODULUS_BITS, 0, 0);
1048
16.8k
            if (crv != CKR_OK) {
1049
0
                return crv;
1050
0
            }
1051
16.8k
            crv = sftk_ConstrainAttribute(object, CKA_PUBLIC_EXPONENT, 2, 0, 0);
1052
16.8k
            if (crv != CKR_OK) {
1053
11
                return crv;
1054
11
            }
1055
16.8k
            break;
1056
16.8k
        case CKK_DSA:
1057
824
            crv = sftk_ConstrainAttribute(object, CKA_SUBPRIME,
1058
824
                                          DSA_MIN_Q_BITS, DSA_MAX_Q_BITS, 0);
1059
824
            if (crv != CKR_OK) {
1060
0
                return crv;
1061
0
            }
1062
824
            crv = sftk_ConstrainAttribute(object, CKA_PRIME,
1063
824
                                          DSA_MIN_P_BITS, DSA_MAX_P_BITS, 64);
1064
824
            if (crv != CKR_OK) {
1065
2
                return crv;
1066
2
            }
1067
822
            crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DSA_MAX_P_BITS, 0);
1068
822
            if (crv != CKR_OK) {
1069
0
                return crv;
1070
0
            }
1071
822
            crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DSA_MAX_P_BITS, 0);
1072
822
            if (crv != CKR_OK) {
1073
0
                return crv;
1074
0
            }
1075
822
            encrypt = CK_FALSE;
1076
822
            recover = CK_FALSE;
1077
822
            wrap = CK_FALSE;
1078
822
            break;
1079
5.10k
        case CKK_DH:
1080
5.10k
            crv = sftk_ConstrainAttribute(object, CKA_PRIME,
1081
5.10k
                                          DH_MIN_P_BITS, DH_MAX_P_BITS, 0);
1082
5.10k
            if (crv != CKR_OK) {
1083
0
                return crv;
1084
0
            }
1085
5.10k
            crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DH_MAX_P_BITS, 0);
1086
5.10k
            if (crv != CKR_OK) {
1087
0
                return crv;
1088
0
            }
1089
5.10k
            crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DH_MAX_P_BITS, 0);
1090
5.10k
            if (crv != CKR_OK) {
1091
320
                return crv;
1092
320
            }
1093
4.78k
            verify = CK_FALSE;
1094
4.78k
            derive = CK_TRUE;
1095
4.78k
            encrypt = CK_FALSE;
1096
4.78k
            recover = CK_FALSE;
1097
4.78k
            wrap = CK_FALSE;
1098
4.78k
            break;
1099
0
        case CKK_EC_MONTGOMERY:
1100
0
        case CKK_EC_EDWARDS:
1101
48.0k
        case CKK_EC:
1102
48.0k
            if (!sftk_hasAttribute(object, CKA_EC_PARAMS)) {
1103
0
                return CKR_TEMPLATE_INCOMPLETE;
1104
0
            }
1105
48.0k
            if (!sftk_hasAttribute(object, CKA_EC_POINT)) {
1106
0
                return CKR_TEMPLATE_INCOMPLETE;
1107
0
            }
1108
            /* for ECDSA and EDDSA. Change if the structure of any of them is modified. */
1109
48.0k
            derive = (key_type == CKK_EC_EDWARDS) ? CK_FALSE : CK_TRUE;    /* CK_TRUE for ECDH */
1110
48.0k
            verify = (key_type == CKK_EC_MONTGOMERY) ? CK_FALSE : CK_TRUE; /* for ECDSA and EDDSA */
1111
48.0k
            encrypt = CK_FALSE;
1112
48.0k
            recover = CK_FALSE;
1113
48.0k
            wrap = CK_FALSE;
1114
48.0k
            break;
1115
0
        case CKK_NSS_KYBER:
1116
187
        case CKK_NSS_ML_KEM:
1117
187
            if (!sftk_hasAttribute(object, CKA_NSS_PARAMETER_SET)) {
1118
0
                return CKR_TEMPLATE_INCOMPLETE;
1119
0
            }
1120
187
            derive = CK_FALSE;
1121
187
            verify = CK_FALSE;
1122
187
            encrypt = CK_FALSE;
1123
187
            recover = CK_FALSE;
1124
187
            wrap = CK_FALSE;
1125
187
            break;
1126
0
        default:
1127
0
            return CKR_ATTRIBUTE_VALUE_INVALID;
1128
71.0k
    }
1129
1130
    /* make sure the required fields exist */
1131
70.6k
    crv = sftk_defaultAttribute(object, CKA_SUBJECT, NULL, 0);
1132
70.6k
    if (crv != CKR_OK)
1133
0
        return crv;
1134
70.6k
    crv = sftk_defaultAttribute(object, CKA_ENCRYPT, &encrypt, sizeof(CK_BBOOL));
1135
70.6k
    if (crv != CKR_OK)
1136
0
        return crv;
1137
70.6k
    crv = sftk_defaultAttribute(object, CKA_VERIFY, &verify, sizeof(CK_BBOOL));
1138
70.6k
    if (crv != CKR_OK)
1139
0
        return crv;
1140
70.6k
    crv = sftk_defaultAttribute(object, CKA_VERIFY_RECOVER,
1141
70.6k
                                &recover, sizeof(CK_BBOOL));
1142
70.6k
    if (crv != CKR_OK)
1143
0
        return crv;
1144
70.6k
    crv = sftk_defaultAttribute(object, CKA_WRAP, &wrap, sizeof(CK_BBOOL));
1145
70.6k
    if (crv != CKR_OK)
1146
0
        return crv;
1147
70.6k
    crv = sftk_defaultAttribute(object, CKA_DERIVE, &derive, sizeof(CK_BBOOL));
1148
70.6k
    if (crv != CKR_OK)
1149
0
        return crv;
1150
1151
70.6k
    object->objectInfo = sftk_GetPubKey(object, key_type, &crv);
1152
70.6k
    if (object->objectInfo == NULL) {
1153
153
        return crv;
1154
153
    }
1155
70.5k
    object->infoFree = SFTKFree_nsslowkey_DestroyPublicKey;
1156
1157
    /* Check that an imported EC key is valid */
1158
70.5k
    if (key_type == CKK_EC || key_type == CKK_EC_EDWARDS || key_type == CKK_EC_MONTGOMERY) {
1159
47.9k
        NSSLOWKEYPublicKey *pubKey = (NSSLOWKEYPublicKey *)object->objectInfo;
1160
47.9k
        SECStatus rv = EC_ValidatePublicKey(&pubKey->u.ec.ecParams,
1161
47.9k
                                            &pubKey->u.ec.publicValue);
1162
1163
47.9k
        if (rv != SECSuccess) {
1164
20
            return CKR_TEMPLATE_INCONSISTENT;
1165
20
        }
1166
47.9k
    }
1167
1168
70.5k
    if (sftk_isTrue(object, CKA_TOKEN)) {
1169
0
        SFTKSlot *slot = session->slot;
1170
0
        SFTKDBHandle *certHandle = sftk_getCertDB(slot);
1171
1172
0
        if (certHandle == NULL) {
1173
0
            return CKR_TOKEN_WRITE_PROTECTED;
1174
0
        }
1175
1176
0
        crv = sftkdb_write(certHandle, object, &object->handle);
1177
0
        sftk_freeDB(certHandle);
1178
0
        return crv;
1179
0
    }
1180
1181
70.5k
    return CKR_OK;
1182
70.5k
}
1183
1184
static NSSLOWKEYPrivateKey *
1185
sftk_mkPrivKey(SFTKObject *object, CK_KEY_TYPE key, CK_RV *rvp);
1186
1187
static SECStatus
1188
sftk_verifyRSAPrivateKey(SFTKObject *object, PRBool fillIfNeeded);
1189
1190
/*
1191
 * check the consistancy and initialize a Private Key Object
1192
 */
1193
static CK_RV
1194
sftk_handlePrivateKeyObject(SFTKSession *session, SFTKObject *object, CK_KEY_TYPE key_type)
1195
52.8k
{
1196
52.8k
    CK_BBOOL cktrue = CK_TRUE;
1197
52.8k
    CK_BBOOL encrypt = CK_TRUE;
1198
52.8k
    CK_BBOOL sign = CK_FALSE;
1199
52.8k
    CK_BBOOL recover = CK_TRUE;
1200
52.8k
    CK_BBOOL wrap = CK_TRUE;
1201
52.8k
    CK_BBOOL derive = CK_TRUE;
1202
52.8k
    CK_BBOOL ckfalse = CK_FALSE;
1203
52.8k
    PRBool createObjectInfo = PR_TRUE;
1204
52.8k
    PRBool fillPrivateKey = PR_FALSE;
1205
52.8k
    int missing_rsa_mod_component = 0;
1206
52.8k
    int missing_rsa_exp_component = 0;
1207
52.8k
    int missing_rsa_crt_component = 0;
1208
1209
52.8k
    SECItem mod;
1210
52.8k
    CK_RV crv;
1211
52.8k
    SECStatus rv;
1212
1213
52.8k
    switch (key_type) {
1214
12
        case CKK_RSA:
1215
12
            if (!sftk_hasAttribute(object, CKA_MODULUS)) {
1216
0
                missing_rsa_mod_component++;
1217
0
            }
1218
12
            if (!sftk_hasAttribute(object, CKA_PUBLIC_EXPONENT)) {
1219
0
                missing_rsa_exp_component++;
1220
0
            }
1221
12
            if (!sftk_hasAttribute(object, CKA_PRIVATE_EXPONENT)) {
1222
0
                missing_rsa_exp_component++;
1223
0
            }
1224
12
            if (!sftk_hasAttribute(object, CKA_PRIME_1)) {
1225
0
                missing_rsa_mod_component++;
1226
0
            }
1227
12
            if (!sftk_hasAttribute(object, CKA_PRIME_2)) {
1228
0
                missing_rsa_mod_component++;
1229
0
            }
1230
12
            if (!sftk_hasAttribute(object, CKA_EXPONENT_1)) {
1231
0
                missing_rsa_crt_component++;
1232
0
            }
1233
12
            if (!sftk_hasAttribute(object, CKA_EXPONENT_2)) {
1234
0
                missing_rsa_crt_component++;
1235
0
            }
1236
12
            if (!sftk_hasAttribute(object, CKA_COEFFICIENT)) {
1237
0
                missing_rsa_crt_component++;
1238
0
            }
1239
12
            if (missing_rsa_mod_component || missing_rsa_exp_component ||
1240
12
                missing_rsa_crt_component) {
1241
                /* we are missing a component, see if we have enough to rebuild
1242
                 * the rest */
1243
0
                int have_exp = 2 - missing_rsa_exp_component;
1244
0
                int have_component = 5 -
1245
0
                                     (missing_rsa_exp_component + missing_rsa_mod_component);
1246
1247
0
                if ((have_exp == 0) || (have_component < 3)) {
1248
                    /* nope, not enough to reconstruct the private key */
1249
0
                    return CKR_TEMPLATE_INCOMPLETE;
1250
0
                }
1251
0
                fillPrivateKey = PR_TRUE;
1252
0
            }
1253
            /*verify the parameters for consistency*/
1254
12
            rv = sftk_verifyRSAPrivateKey(object, fillPrivateKey);
1255
12
            if (rv != SECSuccess) {
1256
0
                return CKR_TEMPLATE_INCOMPLETE;
1257
0
            }
1258
1259
            /* make sure Netscape DB attribute is set correctly */
1260
12
            crv = sftk_Attribute2SSecItem(NULL, &mod, object, CKA_MODULUS);
1261
12
            if (crv != CKR_OK)
1262
0
                return crv;
1263
12
            crv = sftk_forceAttribute(object, CKA_NSS_DB,
1264
12
                                      sftk_item_expand(&mod));
1265
12
            if (mod.data)
1266
12
                SECITEM_ZfreeItem(&mod, PR_FALSE);
1267
12
            if (crv != CKR_OK)
1268
0
                return crv;
1269
1270
12
            sign = CK_TRUE;
1271
12
            derive = CK_FALSE;
1272
12
            break;
1273
0
        case CKK_DSA:
1274
0
            if (!sftk_hasAttribute(object, CKA_SUBPRIME)) {
1275
0
                return CKR_TEMPLATE_INCOMPLETE;
1276
0
            }
1277
0
            sign = CK_TRUE;
1278
0
            derive = CK_FALSE;
1279
        /* fall through */
1280
5.10k
        case CKK_DH:
1281
5.10k
            if (!sftk_hasAttribute(object, CKA_PRIME)) {
1282
0
                return CKR_TEMPLATE_INCOMPLETE;
1283
0
            }
1284
5.10k
            if (!sftk_hasAttribute(object, CKA_BASE)) {
1285
0
                return CKR_TEMPLATE_INCOMPLETE;
1286
0
            }
1287
5.10k
            if (!sftk_hasAttribute(object, CKA_VALUE)) {
1288
0
                return CKR_TEMPLATE_INCOMPLETE;
1289
0
            }
1290
            /* allow subprime to be set after the fact */
1291
5.10k
            crv = sftk_defaultAttribute(object, CKA_SUBPRIME, NULL, 0);
1292
5.10k
            if (crv != CKR_OK) {
1293
0
                return crv;
1294
0
            }
1295
5.10k
            encrypt = CK_FALSE;
1296
5.10k
            recover = CK_FALSE;
1297
5.10k
            wrap = CK_FALSE;
1298
5.10k
            break;
1299
47.7k
        case CKK_EC:
1300
47.7k
        case CKK_EC_EDWARDS:
1301
47.7k
        case CKK_EC_MONTGOMERY:
1302
47.7k
            if (!sftk_hasAttribute(object, CKA_EC_PARAMS)) {
1303
0
                return CKR_TEMPLATE_INCOMPLETE;
1304
0
            }
1305
47.7k
            if (!sftk_hasAttribute(object, CKA_VALUE)) {
1306
0
                return CKR_TEMPLATE_INCOMPLETE;
1307
0
            }
1308
            /* for ECDSA and EDDSA. Change if the structure of any of them is modified. */
1309
47.7k
            derive = (key_type == CKK_EC_EDWARDS) ? CK_FALSE : CK_TRUE;  /* CK_TRUE for ECDH */
1310
47.7k
            sign = (key_type == CKK_EC_MONTGOMERY) ? CK_FALSE : CK_TRUE; /* for ECDSA and EDDSA */
1311
47.7k
            encrypt = CK_FALSE;
1312
47.7k
            recover = CK_FALSE;
1313
47.7k
            wrap = CK_FALSE;
1314
47.7k
            break;
1315
0
        case CKK_NSS_JPAKE_ROUND1:
1316
0
            if (!sftk_hasAttribute(object, CKA_PRIME) ||
1317
0
                !sftk_hasAttribute(object, CKA_SUBPRIME) ||
1318
0
                !sftk_hasAttribute(object, CKA_BASE)) {
1319
0
                return CKR_TEMPLATE_INCOMPLETE;
1320
0
            }
1321
        /* fall through */
1322
0
        case CKK_NSS_JPAKE_ROUND2:
1323
            /* CKA_NSS_JPAKE_SIGNERID and CKA_NSS_JPAKE_PEERID are checked in
1324
               the J-PAKE code. */
1325
0
            encrypt = sign = recover = wrap = CK_FALSE;
1326
0
            derive = CK_TRUE;
1327
0
            createObjectInfo = PR_FALSE;
1328
0
            break;
1329
0
        case CKK_NSS_KYBER:
1330
0
        case CKK_NSS_ML_KEM:
1331
0
            if (!sftk_hasAttribute(object, CKA_KEY_TYPE)) {
1332
0
                return CKR_TEMPLATE_INCOMPLETE;
1333
0
            }
1334
0
            if (!sftk_hasAttribute(object, CKA_VALUE)) {
1335
0
                return CKR_TEMPLATE_INCOMPLETE;
1336
0
            }
1337
0
            encrypt = sign = recover = wrap = CK_FALSE;
1338
0
            break;
1339
0
        default:
1340
0
            return CKR_ATTRIBUTE_VALUE_INVALID;
1341
52.8k
    }
1342
52.8k
    crv = sftk_defaultAttribute(object, CKA_SUBJECT, NULL, 0);
1343
52.8k
    if (crv != CKR_OK)
1344
0
        return crv;
1345
52.8k
    crv = sftk_defaultAttribute(object, CKA_SENSITIVE, &cktrue, sizeof(CK_BBOOL));
1346
52.8k
    if (crv != CKR_OK)
1347
0
        return crv;
1348
52.8k
    crv = sftk_defaultAttribute(object, CKA_EXTRACTABLE, &cktrue, sizeof(CK_BBOOL));
1349
52.8k
    if (crv != CKR_OK)
1350
0
        return crv;
1351
52.8k
    crv = sftk_defaultAttribute(object, CKA_DECRYPT, &encrypt, sizeof(CK_BBOOL));
1352
52.8k
    if (crv != CKR_OK)
1353
0
        return crv;
1354
52.8k
    crv = sftk_defaultAttribute(object, CKA_SIGN, &sign, sizeof(CK_BBOOL));
1355
52.8k
    if (crv != CKR_OK)
1356
0
        return crv;
1357
52.8k
    crv = sftk_defaultAttribute(object, CKA_SIGN_RECOVER, &recover,
1358
52.8k
                                sizeof(CK_BBOOL));
1359
52.8k
    if (crv != CKR_OK)
1360
0
        return crv;
1361
52.8k
    crv = sftk_defaultAttribute(object, CKA_UNWRAP, &wrap, sizeof(CK_BBOOL));
1362
52.8k
    if (crv != CKR_OK)
1363
0
        return crv;
1364
52.8k
    crv = sftk_defaultAttribute(object, CKA_DERIVE, &derive, sizeof(CK_BBOOL));
1365
52.8k
    if (crv != CKR_OK)
1366
0
        return crv;
1367
    /* the next two bits get modified only in the key gen and token cases */
1368
52.8k
    crv = sftk_forceAttribute(object, CKA_ALWAYS_SENSITIVE,
1369
52.8k
                              &ckfalse, sizeof(CK_BBOOL));
1370
52.8k
    if (crv != CKR_OK)
1371
0
        return crv;
1372
52.8k
    crv = sftk_forceAttribute(object, CKA_NEVER_EXTRACTABLE,
1373
52.8k
                              &ckfalse, sizeof(CK_BBOOL));
1374
52.8k
    if (crv != CKR_OK)
1375
0
        return crv;
1376
1377
    /* should we check the non-token RSA private keys? */
1378
1379
52.8k
    if (sftk_isTrue(object, CKA_TOKEN)) {
1380
0
        SFTKSlot *slot = session->slot;
1381
0
        SFTKDBHandle *keyHandle = sftk_getKeyDB(slot);
1382
1383
0
        if (keyHandle == NULL) {
1384
0
            return CKR_TOKEN_WRITE_PROTECTED;
1385
0
        }
1386
1387
0
        crv = sftkdb_write(keyHandle, object, &object->handle);
1388
0
        sftk_freeDB(keyHandle);
1389
0
        return crv;
1390
52.8k
    } else if (createObjectInfo) {
1391
52.8k
        object->objectInfo = sftk_mkPrivKey(object, key_type, &crv);
1392
52.8k
        if (object->objectInfo == NULL)
1393
0
            return crv;
1394
52.8k
        object->infoFree = SFTKFree_nsslowkey_DestroyPrivateKey;
1395
52.8k
    }
1396
52.8k
    return CKR_OK;
1397
52.8k
}
1398
1399
/* forward declare the DES formating function for handleSecretKey */
1400
void sftk_FormatDESKey(unsigned char *key, int length);
1401
1402
/* Validate secret key data, and set defaults */
1403
static CK_RV
1404
validateSecretKey(SFTKSession *session, SFTKObject *object,
1405
                  CK_KEY_TYPE key_type, PRBool isFIPS)
1406
566k
{
1407
566k
    CK_RV crv;
1408
566k
    CK_BBOOL cktrue = CK_TRUE;
1409
566k
    CK_BBOOL ckfalse = CK_FALSE;
1410
566k
    SFTKAttribute *attribute = NULL;
1411
566k
    unsigned long requiredLen;
1412
1413
566k
    crv = sftk_defaultAttribute(object, CKA_SENSITIVE,
1414
566k
                                isFIPS ? &cktrue : &ckfalse, sizeof(CK_BBOOL));
1415
566k
    if (crv != CKR_OK)
1416
0
        return crv;
1417
566k
    crv = sftk_defaultAttribute(object, CKA_EXTRACTABLE,
1418
566k
                                &cktrue, sizeof(CK_BBOOL));
1419
566k
    if (crv != CKR_OK)
1420
0
        return crv;
1421
566k
    crv = sftk_defaultAttribute(object, CKA_ENCRYPT, &cktrue, sizeof(CK_BBOOL));
1422
566k
    if (crv != CKR_OK)
1423
0
        return crv;
1424
566k
    crv = sftk_defaultAttribute(object, CKA_DECRYPT, &cktrue, sizeof(CK_BBOOL));
1425
566k
    if (crv != CKR_OK)
1426
0
        return crv;
1427
566k
    crv = sftk_defaultAttribute(object, CKA_SIGN, &ckfalse, sizeof(CK_BBOOL));
1428
566k
    if (crv != CKR_OK)
1429
0
        return crv;
1430
566k
    crv = sftk_defaultAttribute(object, CKA_VERIFY, &ckfalse, sizeof(CK_BBOOL));
1431
566k
    if (crv != CKR_OK)
1432
0
        return crv;
1433
566k
    crv = sftk_defaultAttribute(object, CKA_WRAP, &cktrue, sizeof(CK_BBOOL));
1434
566k
    if (crv != CKR_OK)
1435
0
        return crv;
1436
566k
    crv = sftk_defaultAttribute(object, CKA_UNWRAP, &cktrue, sizeof(CK_BBOOL));
1437
566k
    if (crv != CKR_OK)
1438
0
        return crv;
1439
1440
566k
    if (!sftk_hasAttribute(object, CKA_VALUE)) {
1441
0
        return CKR_TEMPLATE_INCOMPLETE;
1442
0
    }
1443
    /* the next two bits get modified only in the key gen and token cases */
1444
566k
    crv = sftk_forceAttribute(object, CKA_ALWAYS_SENSITIVE,
1445
566k
                              &ckfalse, sizeof(CK_BBOOL));
1446
566k
    if (crv != CKR_OK)
1447
0
        return crv;
1448
566k
    crv = sftk_forceAttribute(object, CKA_NEVER_EXTRACTABLE,
1449
566k
                              &ckfalse, sizeof(CK_BBOOL));
1450
566k
    if (crv != CKR_OK)
1451
0
        return crv;
1452
1453
    /* some types of keys have a value length */
1454
566k
    crv = CKR_OK;
1455
566k
    switch (key_type) {
1456
        /* force CKA_VALUE_LEN to be set */
1457
353k
        case CKK_GENERIC_SECRET:
1458
353k
        case CKK_RC2:
1459
356k
        case CKK_RC4:
1460
#if NSS_SOFTOKEN_DOES_RC5
1461
        case CKK_RC5:
1462
#endif
1463
#ifdef NSS_SOFTOKEN_DOES_CAST
1464
        case CKK_CAST:
1465
        case CKK_CAST3:
1466
        case CKK_CAST5:
1467
#endif
1468
#if NSS_SOFTOKEN_DOES_IDEA
1469
        case CKK_IDEA:
1470
#endif
1471
356k
            attribute = sftk_FindAttribute(object, CKA_VALUE);
1472
            /* shouldn't happen */
1473
356k
            if (attribute == NULL)
1474
0
                return CKR_TEMPLATE_INCOMPLETE;
1475
356k
            crv = sftk_forceAttribute(object, CKA_VALUE_LEN,
1476
356k
                                      &attribute->attrib.ulValueLen, sizeof(CK_ULONG));
1477
356k
            sftk_FreeAttribute(attribute);
1478
356k
            break;
1479
        /* force the value to have the correct parity */
1480
5.50k
        case CKK_DES:
1481
5.50k
        case CKK_DES2:
1482
32.1k
        case CKK_DES3:
1483
32.1k
        case CKK_CDMF:
1484
32.1k
            attribute = sftk_FindAttribute(object, CKA_VALUE);
1485
            /* shouldn't happen */
1486
32.1k
            if (attribute == NULL)
1487
0
                return CKR_TEMPLATE_INCOMPLETE;
1488
32.1k
            requiredLen = sftk_MapKeySize(key_type);
1489
32.1k
            if (attribute->attrib.ulValueLen != requiredLen) {
1490
0
                sftk_FreeAttribute(attribute);
1491
0
                return CKR_KEY_SIZE_RANGE;
1492
0
            }
1493
32.1k
            sftk_FormatDESKey((unsigned char *)attribute->attrib.pValue,
1494
32.1k
                              attribute->attrib.ulValueLen);
1495
32.1k
            sftk_FreeAttribute(attribute);
1496
32.1k
            break;
1497
118k
        case CKK_AES:
1498
118k
            attribute = sftk_FindAttribute(object, CKA_VALUE);
1499
            /* shouldn't happen */
1500
118k
            if (attribute == NULL)
1501
0
                return CKR_TEMPLATE_INCOMPLETE;
1502
118k
            if (attribute->attrib.ulValueLen != 16 &&
1503
118k
                attribute->attrib.ulValueLen != 24 &&
1504
118k
                attribute->attrib.ulValueLen != 32) {
1505
0
                sftk_FreeAttribute(attribute);
1506
0
                return CKR_KEY_SIZE_RANGE;
1507
0
            }
1508
118k
            crv = sftk_forceAttribute(object, CKA_VALUE_LEN,
1509
118k
                                      &attribute->attrib.ulValueLen, sizeof(CK_ULONG));
1510
118k
            sftk_FreeAttribute(attribute);
1511
118k
            break;
1512
58.9k
        default:
1513
58.9k
            break;
1514
566k
    }
1515
1516
566k
    return crv;
1517
566k
}
1518
1519
/*
1520
 * check the consistancy and initialize a Secret Key Object
1521
 */
1522
static CK_RV
1523
sftk_handleSecretKeyObject(SFTKSession *session, SFTKObject *object,
1524
                           CK_KEY_TYPE key_type, PRBool isFIPS)
1525
566k
{
1526
566k
    CK_RV crv;
1527
1528
    /* First validate and set defaults */
1529
566k
    crv = validateSecretKey(session, object, key_type, isFIPS);
1530
566k
    if (crv != CKR_OK)
1531
0
        goto loser;
1532
1533
    /* If the object is a TOKEN object, store in the database */
1534
566k
    if (sftk_isTrue(object, CKA_TOKEN)) {
1535
0
        SFTKSlot *slot = session->slot;
1536
0
        SFTKDBHandle *keyHandle = sftk_getKeyDB(slot);
1537
1538
0
        if (keyHandle == NULL) {
1539
0
            return CKR_TOKEN_WRITE_PROTECTED;
1540
0
        }
1541
1542
0
        crv = sftkdb_write(keyHandle, object, &object->handle);
1543
0
        sftk_freeDB(keyHandle);
1544
0
        return crv;
1545
0
    }
1546
1547
566k
loser:
1548
1549
566k
    return crv;
1550
566k
}
1551
1552
/*
1553
 * check the consistancy and initialize a Key Object
1554
 */
1555
static CK_RV
1556
sftk_handleKeyObject(SFTKSession *session, SFTKObject *object)
1557
690k
{
1558
690k
    SFTKAttribute *attribute;
1559
690k
    CK_KEY_TYPE key_type;
1560
690k
    CK_BBOOL ckfalse = CK_FALSE;
1561
690k
    CK_RV crv;
1562
1563
    /* verify the required fields */
1564
690k
    if (!sftk_hasAttribute(object, CKA_KEY_TYPE)) {
1565
0
        return CKR_TEMPLATE_INCOMPLETE;
1566
0
    }
1567
1568
    /* now verify the common fields */
1569
690k
    crv = sftk_defaultAttribute(object, CKA_ID, NULL, 0);
1570
690k
    if (crv != CKR_OK)
1571
0
        return crv;
1572
690k
    crv = sftk_defaultAttribute(object, CKA_START_DATE, NULL, 0);
1573
690k
    if (crv != CKR_OK)
1574
0
        return crv;
1575
690k
    crv = sftk_defaultAttribute(object, CKA_END_DATE, NULL, 0);
1576
690k
    if (crv != CKR_OK)
1577
0
        return crv;
1578
    /* CKA_DERIVE is common to all keys, but it's default value is
1579
     * key dependent */
1580
690k
    crv = sftk_defaultAttribute(object, CKA_LOCAL, &ckfalse, sizeof(CK_BBOOL));
1581
690k
    if (crv != CKR_OK)
1582
0
        return crv;
1583
1584
    /* get the key type */
1585
690k
    attribute = sftk_FindAttribute(object, CKA_KEY_TYPE);
1586
690k
    if (!attribute) {
1587
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
1588
0
    }
1589
690k
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1590
690k
    sftk_FreeAttribute(attribute);
1591
1592
690k
    switch (object->objclass) {
1593
71.0k
        case CKO_PUBLIC_KEY:
1594
71.0k
            return sftk_handlePublicKeyObject(session, object, key_type);
1595
52.8k
        case CKO_PRIVATE_KEY:
1596
52.8k
            return sftk_handlePrivateKeyObject(session, object, key_type);
1597
566k
        case CKO_SECRET_KEY:
1598
            /* make sure the required fields exist */
1599
566k
            return sftk_handleSecretKeyObject(session, object, key_type,
1600
566k
                                              (PRBool)(sftk_isFIPS(session->slot->slotID)));
1601
0
        default:
1602
0
            break;
1603
690k
    }
1604
0
    return CKR_ATTRIBUTE_VALUE_INVALID;
1605
690k
}
1606
1607
/*
1608
 * check the consistancy and Verify a DSA Parameter Object
1609
 */
1610
static CK_RV
1611
sftk_handleDSAParameterObject(SFTKSession *session, SFTKObject *object)
1612
0
{
1613
0
    SFTKAttribute *primeAttr = NULL;
1614
0
    SFTKAttribute *subPrimeAttr = NULL;
1615
0
    SFTKAttribute *baseAttr = NULL;
1616
0
    SFTKAttribute *seedAttr = NULL;
1617
0
    SFTKAttribute *hAttr = NULL;
1618
0
    SFTKAttribute *attribute;
1619
0
    CK_RV crv = CKR_TEMPLATE_INCOMPLETE;
1620
0
    PQGParams params;
1621
0
    PQGVerify vfy, *verify = NULL;
1622
0
    SECStatus result, rv;
1623
    /* This bool keeps track of whether or not we need verify parameters.
1624
     * If a P, Q and G or supplied, we dont' need verify parameters, as we
1625
     * have PQ and G.
1626
     *   - If G is not supplied, the presumption is that we want to
1627
     * verify P and Q only.
1628
     *   - If counter is supplied, it is presumed we want to verify PQ because
1629
     * the counter is only used in verification.
1630
     *   - If H is supplied, is is presumed we want to verify G because H is
1631
     * only used to verify G.
1632
     *   - Any verification step must have the SEED (counter or H could be
1633
     * missing depending on exactly what we want to verify). If SEED is supplied,
1634
     * the code just goes ahead and runs verify (other errors are parameter
1635
     * errors are detected by the PQG_VerifyParams function). If SEED is not
1636
     * supplied, but we determined that we are trying to verify (because needVfy
1637
     * is set, go ahead and return CKR_TEMPLATE_INCOMPLETE.
1638
     */
1639
0
    PRBool needVfy = PR_FALSE;
1640
1641
0
    primeAttr = sftk_FindAttribute(object, CKA_PRIME);
1642
0
    if (primeAttr == NULL)
1643
0
        goto loser;
1644
0
    params.prime.data = primeAttr->attrib.pValue;
1645
0
    params.prime.len = primeAttr->attrib.ulValueLen;
1646
1647
0
    subPrimeAttr = sftk_FindAttribute(object, CKA_SUBPRIME);
1648
0
    if (subPrimeAttr == NULL)
1649
0
        goto loser;
1650
0
    params.subPrime.data = subPrimeAttr->attrib.pValue;
1651
0
    params.subPrime.len = subPrimeAttr->attrib.ulValueLen;
1652
1653
0
    baseAttr = sftk_FindAttribute(object, CKA_BASE);
1654
0
    if (baseAttr != NULL) {
1655
0
        params.base.data = baseAttr->attrib.pValue;
1656
0
        params.base.len = baseAttr->attrib.ulValueLen;
1657
0
    } else {
1658
0
        params.base.data = NULL;
1659
0
        params.base.len = 0;
1660
0
        needVfy = PR_TRUE; /* presumably only including PQ so we can verify
1661
                            * them. */
1662
0
    }
1663
1664
0
    attribute = sftk_FindAttribute(object, CKA_NSS_PQG_COUNTER);
1665
0
    if (attribute != NULL) {
1666
0
        vfy.counter = *(CK_ULONG *)attribute->attrib.pValue;
1667
0
        sftk_FreeAttribute(attribute);
1668
0
        needVfy = PR_TRUE; /* included a count so we can verify PQ */
1669
0
    } else {
1670
0
        vfy.counter = -1;
1671
0
    }
1672
1673
0
    hAttr = sftk_FindAttribute(object, CKA_NSS_PQG_H);
1674
0
    if (hAttr != NULL) {
1675
0
        vfy.h.data = hAttr->attrib.pValue;
1676
0
        vfy.h.len = hAttr->attrib.ulValueLen;
1677
0
        needVfy = PR_TRUE; /* included H so we can verify G */
1678
0
    } else {
1679
0
        vfy.h.data = NULL;
1680
0
        vfy.h.len = 0;
1681
0
    }
1682
0
    seedAttr = sftk_FindAttribute(object, CKA_NSS_PQG_SEED);
1683
0
    if (seedAttr != NULL) {
1684
0
        vfy.seed.data = seedAttr->attrib.pValue;
1685
0
        vfy.seed.len = seedAttr->attrib.ulValueLen;
1686
1687
0
        verify = &vfy;
1688
0
    } else if (needVfy) {
1689
0
        goto loser; /* Verify always needs seed, if we need verify and not seed
1690
                     * then fail */
1691
0
    }
1692
1693
0
    crv = CKR_FUNCTION_FAILED;
1694
0
    rv = PQG_VerifyParams(&params, verify, &result);
1695
0
    if (rv == SECSuccess) {
1696
0
        crv = (result == SECSuccess) ? CKR_OK : CKR_ATTRIBUTE_VALUE_INVALID;
1697
0
    }
1698
1699
0
loser:
1700
0
    if (hAttr)
1701
0
        sftk_FreeAttribute(hAttr);
1702
0
    if (seedAttr)
1703
0
        sftk_FreeAttribute(seedAttr);
1704
0
    if (baseAttr)
1705
0
        sftk_FreeAttribute(baseAttr);
1706
0
    if (subPrimeAttr)
1707
0
        sftk_FreeAttribute(subPrimeAttr);
1708
0
    if (primeAttr)
1709
0
        sftk_FreeAttribute(primeAttr);
1710
1711
0
    return crv;
1712
0
}
1713
1714
/*
1715
 * check the consistancy and initialize a Key Parameter Object
1716
 */
1717
static CK_RV
1718
sftk_handleKeyParameterObject(SFTKSession *session, SFTKObject *object)
1719
0
{
1720
0
    SFTKAttribute *attribute;
1721
0
    CK_KEY_TYPE key_type;
1722
0
    CK_BBOOL ckfalse = CK_FALSE;
1723
0
    CK_RV crv;
1724
1725
    /* verify the required fields */
1726
0
    if (!sftk_hasAttribute(object, CKA_KEY_TYPE)) {
1727
0
        return CKR_TEMPLATE_INCOMPLETE;
1728
0
    }
1729
1730
    /* now verify the common fields */
1731
0
    crv = sftk_defaultAttribute(object, CKA_LOCAL, &ckfalse, sizeof(CK_BBOOL));
1732
0
    if (crv != CKR_OK)
1733
0
        return crv;
1734
1735
    /* get the key type */
1736
0
    attribute = sftk_FindAttribute(object, CKA_KEY_TYPE);
1737
0
    if (!attribute) {
1738
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
1739
0
    }
1740
0
    key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
1741
0
    sftk_FreeAttribute(attribute);
1742
1743
0
    switch (key_type) {
1744
0
        case CKK_DSA:
1745
0
            return sftk_handleDSAParameterObject(session, object);
1746
1747
0
        default:
1748
0
            break;
1749
0
    }
1750
0
    return CKR_KEY_TYPE_INCONSISTENT;
1751
0
}
1752
1753
/*
1754
 * Handle Object does all the object consistancy checks, automatic attribute
1755
 * generation, attribute defaulting, etc. If handleObject succeeds, the object
1756
 * will be assigned an object handle, and the object installed in the session
1757
 * or stored in the DB.
1758
 */
1759
CK_RV
1760
sftk_handleObject(SFTKObject *object, SFTKSession *session)
1761
729k
{
1762
729k
    SFTKSlot *slot = session->slot;
1763
729k
    SFTKAttribute *attribute;
1764
729k
    CK_BBOOL ckfalse = CK_FALSE;
1765
729k
    CK_BBOOL cktrue = CK_TRUE;
1766
729k
    PRBool isLoggedIn, needLogin;
1767
729k
    CK_RV crv;
1768
1769
    /* make sure all the base object types are defined. If not set the
1770
     * defaults */
1771
729k
    crv = sftk_defaultAttribute(object, CKA_TOKEN, &ckfalse, sizeof(CK_BBOOL));
1772
729k
    if (crv != CKR_OK)
1773
0
        return crv;
1774
729k
    crv = sftk_defaultAttribute(object, CKA_PRIVATE, &ckfalse, sizeof(CK_BBOOL));
1775
729k
    if (crv != CKR_OK)
1776
0
        return crv;
1777
729k
    crv = sftk_defaultAttribute(object, CKA_LABEL, NULL, 0);
1778
729k
    if (crv != CKR_OK)
1779
0
        return crv;
1780
729k
    crv = sftk_defaultAttribute(object, CKA_MODIFIABLE, &cktrue, sizeof(CK_BBOOL));
1781
729k
    if (crv != CKR_OK)
1782
0
        return crv;
1783
1784
729k
    PZ_Lock(slot->slotLock);
1785
729k
    isLoggedIn = slot->isLoggedIn;
1786
729k
    needLogin = slot->needLogin;
1787
729k
    PZ_Unlock(slot->slotLock);
1788
1789
    /* don't create a private object if we aren't logged in */
1790
729k
    if (!isLoggedIn && needLogin && sftk_isTrue(object, CKA_PRIVATE)) {
1791
0
        return CKR_USER_NOT_LOGGED_IN;
1792
0
    }
1793
1794
729k
    if (((session->info.flags & CKF_RW_SESSION) == 0) &&
1795
729k
        (sftk_isTrue(object, CKA_TOKEN))) {
1796
0
        return CKR_SESSION_READ_ONLY;
1797
0
    }
1798
1799
    /* Assign a unique SESSION object handle to every new object,
1800
     * whether it is a session object or a token object.
1801
     * At this point, all new objects are structured as session objects.
1802
     * Objects with the CKA_TOKEN attribute true will be turned into
1803
     * token objects and will have a token object handle assigned to
1804
     * them by a call to sftk_mkHandle in the handler for each object
1805
     * class, invoked below.
1806
     *
1807
     * It may be helpful to note/remember that
1808
     * sftk_narrowToXxxObject uses sftk_isToken,
1809
     * sftk_isToken examines the sign bit of the object's handle, but
1810
     * sftk_isTrue(...,CKA_TOKEN) examines the CKA_TOKEN attribute.
1811
     */
1812
729k
    object->handle = sftk_getNextHandle(slot);
1813
1814
    /* get the object class */
1815
729k
    attribute = sftk_FindAttribute(object, CKA_CLASS);
1816
729k
    if (attribute == NULL) {
1817
0
        return CKR_TEMPLATE_INCOMPLETE;
1818
0
    }
1819
729k
    object->objclass = *(CK_OBJECT_CLASS *)attribute->attrib.pValue;
1820
729k
    sftk_FreeAttribute(attribute);
1821
1822
    /* Now handle the specific object class.
1823
     * At this point, all objects are session objects, and the session
1824
     * number must be passed to the object class handlers.
1825
     */
1826
729k
    switch (object->objclass) {
1827
38.9k
        case CKO_DATA:
1828
38.9k
            crv = sftk_handleDataObject(session, object);
1829
38.9k
            break;
1830
0
        case CKO_CERTIFICATE:
1831
0
            crv = sftk_handleCertObject(session, object);
1832
0
            break;
1833
0
        case CKO_NSS_TRUST:
1834
0
            crv = sftk_handleTrustObject(session, object);
1835
0
            break;
1836
0
        case CKO_NSS_CRL:
1837
0
            crv = sftk_handleCrlObject(session, object);
1838
0
            break;
1839
0
        case CKO_NSS_SMIME:
1840
0
            crv = sftk_handleSMimeObject(session, object);
1841
0
            break;
1842
52.8k
        case CKO_PRIVATE_KEY:
1843
123k
        case CKO_PUBLIC_KEY:
1844
690k
        case CKO_SECRET_KEY:
1845
690k
            crv = sftk_handleKeyObject(session, object);
1846
690k
            break;
1847
0
        case CKO_DOMAIN_PARAMETERS:
1848
0
            crv = sftk_handleKeyParameterObject(session, object);
1849
0
            break;
1850
0
        default:
1851
0
            crv = CKR_ATTRIBUTE_VALUE_INVALID;
1852
0
            break;
1853
729k
    }
1854
1855
    /* can't fail from here on out unless the pk_handlXXX functions have
1856
     * failed the request */
1857
729k
    if (crv != CKR_OK) {
1858
506
        return crv;
1859
506
    }
1860
1861
    /* Now link the object into the slot and session structures.
1862
     * If the object has a true CKA_TOKEN attribute, the above object
1863
     * class handlers will have set the sign bit in the object handle,
1864
     * causing the following test to be true.
1865
     */
1866
728k
    if (sftk_isToken(object->handle)) {
1867
0
        sftk_convertSessionToToken(object);
1868
728k
    } else {
1869
728k
        object->slot = slot;
1870
728k
        sftk_AddObject(session, object);
1871
728k
    }
1872
1873
728k
    return CKR_OK;
1874
729k
}
1875
1876
/*
1877
 * ******************** Public Key Utilities ***************************
1878
 */
1879
/* Generate a low public key structure from an object */
1880
NSSLOWKEYPublicKey *
1881
sftk_GetPubKey(SFTKObject *object, CK_KEY_TYPE key_type,
1882
               CK_RV *crvp)
1883
88.4k
{
1884
88.4k
    NSSLOWKEYPublicKey *pubKey;
1885
88.4k
    PLArenaPool *arena;
1886
88.4k
    CK_RV crv;
1887
1888
88.4k
    if (object->objclass != CKO_PUBLIC_KEY) {
1889
0
        *crvp = CKR_KEY_TYPE_INCONSISTENT;
1890
0
        return NULL;
1891
0
    }
1892
1893
88.4k
    if (sftk_isToken(object->handle)) {
1894
        /* ferret out the token object handle */
1895
0
    }
1896
1897
    /* If we already have a key, use it */
1898
88.4k
    if (object->objectInfo) {
1899
17.7k
        *crvp = CKR_OK;
1900
17.7k
        return (NSSLOWKEYPublicKey *)object->objectInfo;
1901
17.7k
    }
1902
1903
    /* allocate the structure */
1904
70.6k
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1905
70.6k
    if (arena == NULL) {
1906
0
        *crvp = CKR_HOST_MEMORY;
1907
0
        return NULL;
1908
0
    }
1909
1910
70.6k
    pubKey = (NSSLOWKEYPublicKey *)
1911
70.6k
        PORT_ArenaAlloc(arena, sizeof(NSSLOWKEYPublicKey));
1912
70.6k
    if (pubKey == NULL) {
1913
0
        PORT_FreeArena(arena, PR_FALSE);
1914
0
        *crvp = CKR_HOST_MEMORY;
1915
0
        return NULL;
1916
0
    }
1917
1918
    /* fill in the structure */
1919
70.6k
    pubKey->arena = arena;
1920
70.6k
    switch (key_type) {
1921
16.8k
        case CKK_RSA:
1922
16.8k
            pubKey->keyType = NSSLOWKEYRSAKey;
1923
16.8k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.rsa.modulus,
1924
16.8k
                                          object, CKA_MODULUS);
1925
16.8k
            if (crv != CKR_OK)
1926
0
                break;
1927
16.8k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.rsa.publicExponent,
1928
16.8k
                                          object, CKA_PUBLIC_EXPONENT);
1929
16.8k
            break;
1930
822
        case CKK_DSA:
1931
822
            pubKey->keyType = NSSLOWKEYDSAKey;
1932
822
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.prime,
1933
822
                                          object, CKA_PRIME);
1934
822
            if (crv != CKR_OK)
1935
0
                break;
1936
822
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.subPrime,
1937
822
                                          object, CKA_SUBPRIME);
1938
822
            if (crv != CKR_OK)
1939
0
                break;
1940
822
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.base,
1941
822
                                          object, CKA_BASE);
1942
822
            if (crv != CKR_OK)
1943
0
                break;
1944
822
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.publicValue,
1945
822
                                          object, CKA_VALUE);
1946
822
            break;
1947
4.78k
        case CKK_DH:
1948
4.78k
            pubKey->keyType = NSSLOWKEYDHKey;
1949
4.78k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.prime,
1950
4.78k
                                          object, CKA_PRIME);
1951
4.78k
            if (crv != CKR_OK)
1952
0
                break;
1953
4.78k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.base,
1954
4.78k
                                          object, CKA_BASE);
1955
4.78k
            if (crv != CKR_OK)
1956
0
                break;
1957
4.78k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.publicValue,
1958
4.78k
                                          object, CKA_VALUE);
1959
4.78k
            break;
1960
0
        case CKK_EC_EDWARDS:
1961
0
        case CKK_EC_MONTGOMERY:
1962
48.0k
        case CKK_EC:
1963
48.0k
            pubKey->keyType = NSSLOWKEYECKey;
1964
48.0k
            crv = sftk_Attribute2SSecItem(arena,
1965
48.0k
                                          &pubKey->u.ec.ecParams.DEREncoding,
1966
48.0k
                                          object, CKA_EC_PARAMS);
1967
48.0k
            if (crv != CKR_OK)
1968
0
                break;
1969
1970
            /* Fill out the rest of the ecParams structure
1971
             * based on the encoded params
1972
             */
1973
48.0k
            if (EC_FillParams(arena, &pubKey->u.ec.ecParams.DEREncoding,
1974
48.0k
                              &pubKey->u.ec.ecParams) != SECSuccess) {
1975
104
                crv = CKR_DOMAIN_PARAMS_INVALID;
1976
104
                break;
1977
104
            }
1978
1979
47.9k
            crv = sftk_Attribute2SSecItem(arena, &pubKey->u.ec.publicValue,
1980
47.9k
                                          object, CKA_EC_POINT);
1981
47.9k
            if (crv == CKR_OK) {
1982
47.9k
                unsigned int keyLen = EC_GetPointSize(&pubKey->u.ec.ecParams);
1983
1984
                /* special note: We can't just use the first byte to distinguish
1985
                 * between EC_POINT_FORM_UNCOMPRESSED and SEC_ASN1_OCTET_STRING.
1986
                 * Both are 0x04. */
1987
1988
                /* Handle the non-DER encoded case.
1989
                 * Some curves are always pressumed to be non-DER.
1990
                 */
1991
47.9k
                if (pubKey->u.ec.ecParams.type != ec_params_named ||
1992
47.9k
                    (pubKey->u.ec.publicValue.len == keyLen &&
1993
46.0k
                     pubKey->u.ec.publicValue.data[0] == EC_POINT_FORM_UNCOMPRESSED)) {
1994
1.96k
                    break; /* key was not DER encoded, no need to unwrap */
1995
1.96k
                }
1996
1997
                /* handle the encoded case */
1998
46.0k
                if ((pubKey->u.ec.publicValue.data[0] == SEC_ASN1_OCTET_STRING) &&
1999
46.0k
                    pubKey->u.ec.publicValue.len > keyLen) {
2000
46.0k
                    SECItem publicValue;
2001
46.0k
                    SECStatus rv;
2002
2003
46.0k
                    rv = SEC_QuickDERDecodeItem(arena, &publicValue,
2004
46.0k
                                                SEC_ASN1_GET(SEC_OctetStringTemplate),
2005
46.0k
                                                &pubKey->u.ec.publicValue);
2006
                    /* nope, didn't decode correctly */
2007
46.0k
                    if ((rv != SECSuccess) || (publicValue.len != keyLen)) {
2008
7
                        crv = CKR_ATTRIBUTE_VALUE_INVALID;
2009
7
                        break;
2010
7
                    }
2011
                    /* we don't handle compressed points except in the case of ECCurve25519 */
2012
45.9k
                    if (publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
2013
34
                        crv = CKR_ATTRIBUTE_VALUE_INVALID;
2014
34
                        break;
2015
34
                    }
2016
                    /* replace our previous with the decoded key */
2017
45.9k
                    pubKey->u.ec.publicValue = publicValue;
2018
45.9k
                    break;
2019
45.9k
                }
2020
8
                crv = CKR_ATTRIBUTE_VALUE_INVALID;
2021
8
            }
2022
8
            break;
2023
8
        case CKK_NSS_KYBER:
2024
187
        case CKK_NSS_ML_KEM:
2025
187
            crv = CKR_OK;
2026
187
            break;
2027
0
        default:
2028
0
            crv = CKR_KEY_TYPE_INCONSISTENT;
2029
0
            break;
2030
70.6k
    }
2031
70.6k
    *crvp = crv;
2032
70.6k
    if (crv != CKR_OK) {
2033
153
        PORT_FreeArena(arena, PR_TRUE);
2034
153
        return NULL;
2035
153
    }
2036
2037
70.5k
    object->objectInfo = pubKey;
2038
70.5k
    object->infoFree = SFTKFree_nsslowkey_DestroyPublicKey;
2039
70.5k
    return pubKey;
2040
70.6k
}
2041
2042
/* make a private key from a verified object */
2043
static NSSLOWKEYPrivateKey *
2044
sftk_mkPrivKey(SFTKObject *object, CK_KEY_TYPE key_type, CK_RV *crvp)
2045
52.8k
{
2046
52.8k
    NSSLOWKEYPrivateKey *privKey;
2047
52.8k
    SFTKItemTemplate itemTemplate[SFTK_MAX_ITEM_TEMPLATE];
2048
52.8k
    int itemTemplateCount = 0;
2049
52.8k
    PLArenaPool *arena;
2050
52.8k
    CK_RV crv = CKR_OK;
2051
52.8k
    SECStatus rv;
2052
2053
52.8k
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2054
52.8k
    if (arena == NULL) {
2055
0
        *crvp = CKR_HOST_MEMORY;
2056
0
        return NULL;
2057
0
    }
2058
2059
52.8k
    privKey = (NSSLOWKEYPrivateKey *)
2060
52.8k
        PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPrivateKey));
2061
52.8k
    if (privKey == NULL) {
2062
0
        PORT_FreeArena(arena, PR_FALSE);
2063
0
        *crvp = CKR_HOST_MEMORY;
2064
0
        return NULL;
2065
0
    }
2066
2067
    /* in future this would be a switch on key_type */
2068
52.8k
    privKey->arena = arena;
2069
52.8k
    switch (key_type) {
2070
12
        case CKK_RSA:
2071
12
            privKey->keyType = NSSLOWKEYRSAKey;
2072
2073
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2074
12
                                   &privKey->u.rsa.modulus, CKA_MODULUS);
2075
12
            itemTemplateCount++;
2076
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2077
12
                                   &privKey->u.rsa.publicExponent, CKA_PUBLIC_EXPONENT);
2078
12
            itemTemplateCount++;
2079
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2080
12
                                   &privKey->u.rsa.privateExponent, CKA_PRIVATE_EXPONENT);
2081
12
            itemTemplateCount++;
2082
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2083
12
                                   &privKey->u.rsa.prime1, CKA_PRIME_1);
2084
12
            itemTemplateCount++;
2085
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2086
12
                                   &privKey->u.rsa.prime2, CKA_PRIME_2);
2087
12
            itemTemplateCount++;
2088
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2089
12
                                   &privKey->u.rsa.exponent1, CKA_EXPONENT_1);
2090
12
            itemTemplateCount++;
2091
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2092
12
                                   &privKey->u.rsa.exponent2, CKA_EXPONENT_2);
2093
12
            itemTemplateCount++;
2094
12
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2095
12
                                   &privKey->u.rsa.coefficient, CKA_COEFFICIENT);
2096
12
            itemTemplateCount++;
2097
12
            rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version,
2098
12
                                 NSSLOWKEY_PRIVATE_KEY_INFO_VERSION);
2099
12
            if (rv != SECSuccess)
2100
0
                crv = CKR_HOST_MEMORY;
2101
12
            break;
2102
2103
0
        case CKK_DSA:
2104
0
            privKey->keyType = NSSLOWKEYDSAKey;
2105
0
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2106
0
                                   &privKey->u.dsa.params.prime, CKA_PRIME);
2107
0
            itemTemplateCount++;
2108
0
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2109
0
                                   &privKey->u.dsa.params.subPrime, CKA_SUBPRIME);
2110
0
            itemTemplateCount++;
2111
0
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2112
0
                                   &privKey->u.dsa.params.base, CKA_BASE);
2113
0
            itemTemplateCount++;
2114
0
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2115
0
                                   &privKey->u.dsa.privateValue, CKA_VALUE);
2116
0
            itemTemplateCount++;
2117
            /* privKey was zero'd so public value is already set to NULL, 0
2118
             * if we don't set it explicitly */
2119
0
            break;
2120
2121
5.10k
        case CKK_DH:
2122
5.10k
            privKey->keyType = NSSLOWKEYDHKey;
2123
5.10k
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2124
5.10k
                                   &privKey->u.dh.prime, CKA_PRIME);
2125
5.10k
            itemTemplateCount++;
2126
5.10k
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2127
5.10k
                                   &privKey->u.dh.base, CKA_BASE);
2128
5.10k
            itemTemplateCount++;
2129
5.10k
            SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
2130
5.10k
                                   &privKey->u.dh.privateValue, CKA_VALUE);
2131
5.10k
            itemTemplateCount++;
2132
            /* privKey was zero'd so public value is already set to NULL, 0
2133
             * if we don't set it explicitly */
2134
5.10k
            break;
2135
0
        case CKK_EC_EDWARDS:
2136
0
        case CKK_EC_MONTGOMERY:
2137
47.7k
        case CKK_EC:
2138
47.7k
            privKey->keyType = NSSLOWKEYECKey;
2139
47.7k
            crv = sftk_Attribute2SSecItem(arena,
2140
47.7k
                                          &privKey->u.ec.ecParams.DEREncoding,
2141
47.7k
                                          object, CKA_EC_PARAMS);
2142
47.7k
            if (crv != CKR_OK)
2143
0
                break;
2144
2145
            /* Fill out the rest of the ecParams structure
2146
             * based on the encoded params
2147
             */
2148
47.7k
            if (EC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding,
2149
47.7k
                              &privKey->u.ec.ecParams) != SECSuccess) {
2150
0
                crv = CKR_DOMAIN_PARAMS_INVALID;
2151
0
                break;
2152
0
            }
2153
47.7k
            crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.privateValue,
2154
47.7k
                                          object, CKA_VALUE);
2155
47.7k
            if (crv != CKR_OK)
2156
0
                break;
2157
2158
47.7k
            if (sftk_hasAttribute(object, CKA_NSS_DB)) {
2159
47.7k
                crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.publicValue,
2160
47.7k
                                              object, CKA_NSS_DB);
2161
47.7k
                if (crv != CKR_OK) {
2162
0
                    break;
2163
0
                }
2164
                /* privKey was zero'd so public value is already set to NULL, 0
2165
                 * if we don't set it explicitly */
2166
47.7k
            } else if (key_type == CKK_EC) {
2167
                /* as no public key was provided during the import, we need to derive it here.
2168
                 See: PK11_ImportAndReturnPrivateKey*/
2169
0
                (void)SECITEM_AllocItem(arena, &privKey->u.ec.publicValue, EC_GetPointSize(&privKey->u.ec.ecParams));
2170
0
                rv = EC_DerivePublicKey(&privKey->u.ec.privateValue, &privKey->u.ec.ecParams, &privKey->u.ec.publicValue);
2171
0
                if (rv != SECSuccess) {
2172
0
                    break;
2173
0
                }
2174
0
                sftk_forceAttribute(object, CKA_NSS_DB, privKey->u.ec.publicValue.data, privKey->u.ec.publicValue.len);
2175
0
            }
2176
2177
47.7k
            rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version,
2178
47.7k
                                 NSSLOWKEY_EC_PRIVATE_KEY_VERSION);
2179
47.7k
            if (rv != SECSuccess) {
2180
0
                crv = CKR_HOST_MEMORY;
2181
/* The following ifdef is needed for Linux arm distros and
2182
 * Android as gcc 4.6 has a bug when targeting arm (but not
2183
 * thumb). The bug has been fixed in gcc 4.7.
2184
 * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56561
2185
 */
2186
#if defined(__arm__) && !defined(__thumb__) && defined(__GNUC__)
2187
                *crvp = CKR_HOST_MEMORY;
2188
                break;
2189
#endif
2190
0
            }
2191
47.7k
            break;
2192
2193
0
        case CKK_NSS_KYBER:
2194
0
        case CKK_NSS_ML_KEM:
2195
0
            break;
2196
2197
0
        default:
2198
0
            crv = CKR_KEY_TYPE_INCONSISTENT;
2199
0
            break;
2200
52.8k
    }
2201
52.8k
    if (crv == CKR_OK && itemTemplateCount != 0) {
2202
5.11k
        PORT_Assert(itemTemplateCount > 0);
2203
5.11k
        PORT_Assert(itemTemplateCount <= SFTK_MAX_ITEM_TEMPLATE);
2204
5.11k
        crv = sftk_MultipleAttribute2SecItem(arena, object, itemTemplate,
2205
5.11k
                                             itemTemplateCount);
2206
5.11k
    }
2207
52.8k
    *crvp = crv;
2208
52.8k
    if (crv != CKR_OK) {
2209
0
        PORT_FreeArena(arena, PR_TRUE);
2210
0
        return NULL;
2211
0
    }
2212
52.8k
    return privKey;
2213
52.8k
}
2214
2215
/*
2216
 * If a partial RSA private key is present, fill in the rest if necessary,
2217
 * and then verify the parameters are well-formed
2218
 */
2219
static SECStatus
2220
sftk_verifyRSAPrivateKey(SFTKObject *object, PRBool fillIfNeeded)
2221
12
{
2222
12
    RSAPrivateKey tmpKey = { 0 };
2223
12
    SFTKAttribute *modulus = NULL;
2224
12
    SFTKAttribute *prime1 = NULL;
2225
12
    SFTKAttribute *prime2 = NULL;
2226
12
    SFTKAttribute *privateExponent = NULL;
2227
12
    SFTKAttribute *publicExponent = NULL;
2228
12
    SFTKAttribute *exponent1 = NULL;
2229
12
    SFTKAttribute *exponent2 = NULL;
2230
12
    SFTKAttribute *coefficient = NULL;
2231
12
    SECStatus rv;
2232
12
    CK_RV crv;
2233
2234
    /* first fill in the components that we have. Populate only uses
2235
     * the non-crt components, so only fill those in  */
2236
12
    tmpKey.arena = NULL;
2237
12
    modulus = sftk_FindAttribute(object, CKA_MODULUS);
2238
12
    if (modulus) {
2239
12
        tmpKey.modulus.data = modulus->attrib.pValue;
2240
12
        tmpKey.modulus.len = modulus->attrib.ulValueLen;
2241
12
    }
2242
12
    prime1 = sftk_FindAttribute(object, CKA_PRIME_1);
2243
12
    if (prime1) {
2244
12
        tmpKey.prime1.data = prime1->attrib.pValue;
2245
12
        tmpKey.prime1.len = prime1->attrib.ulValueLen;
2246
12
    }
2247
12
    prime2 = sftk_FindAttribute(object, CKA_PRIME_2);
2248
12
    if (prime2) {
2249
12
        tmpKey.prime2.data = prime2->attrib.pValue;
2250
12
        tmpKey.prime2.len = prime2->attrib.ulValueLen;
2251
12
    }
2252
12
    privateExponent = sftk_FindAttribute(object, CKA_PRIVATE_EXPONENT);
2253
12
    if (privateExponent) {
2254
12
        tmpKey.privateExponent.data = privateExponent->attrib.pValue;
2255
12
        tmpKey.privateExponent.len = privateExponent->attrib.ulValueLen;
2256
12
    }
2257
12
    publicExponent = sftk_FindAttribute(object, CKA_PUBLIC_EXPONENT);
2258
12
    if (publicExponent) {
2259
12
        tmpKey.publicExponent.data = publicExponent->attrib.pValue;
2260
12
        tmpKey.publicExponent.len = publicExponent->attrib.ulValueLen;
2261
12
    }
2262
12
    exponent1 = sftk_FindAttribute(object, CKA_EXPONENT_1);
2263
12
    if (exponent1) {
2264
12
        tmpKey.exponent1.data = exponent1->attrib.pValue;
2265
12
        tmpKey.exponent1.len = exponent1->attrib.ulValueLen;
2266
12
    }
2267
12
    exponent2 = sftk_FindAttribute(object, CKA_EXPONENT_2);
2268
12
    if (exponent2) {
2269
12
        tmpKey.exponent2.data = exponent2->attrib.pValue;
2270
12
        tmpKey.exponent2.len = exponent2->attrib.ulValueLen;
2271
12
    }
2272
12
    coefficient = sftk_FindAttribute(object, CKA_COEFFICIENT);
2273
12
    if (coefficient) {
2274
12
        tmpKey.coefficient.data = coefficient->attrib.pValue;
2275
12
        tmpKey.coefficient.len = coefficient->attrib.ulValueLen;
2276
12
    }
2277
2278
12
    if (fillIfNeeded) {
2279
        /*
2280
         * populate requires one exponent plus 2 other components to work.
2281
         * we expected our caller to check that first. If that didn't happen,
2282
         * populate will simply return an error here.
2283
         */
2284
0
        rv = RSA_PopulatePrivateKey(&tmpKey);
2285
0
        if (rv != SECSuccess) {
2286
0
            goto loser;
2287
0
        }
2288
0
    }
2289
12
    rv = RSA_PrivateKeyCheck(&tmpKey);
2290
12
    if (rv != SECSuccess) {
2291
0
        goto loser;
2292
0
    }
2293
    /* now that we have a fully populated key, set all our attribute values */
2294
12
    rv = SECFailure;
2295
12
    if (!modulus || modulus->attrib.pValue != tmpKey.modulus.data) {
2296
0
        crv = sftk_forceAttribute(object, CKA_MODULUS,
2297
0
                                  sftk_item_expand(&tmpKey.modulus));
2298
0
        if (crv != CKR_OK)
2299
0
            goto loser;
2300
0
    }
2301
12
    if (!publicExponent ||
2302
12
        publicExponent->attrib.pValue != tmpKey.publicExponent.data) {
2303
0
        crv = sftk_forceAttribute(object, CKA_PUBLIC_EXPONENT,
2304
0
                                  sftk_item_expand(&tmpKey.publicExponent));
2305
0
        if (crv != CKR_OK)
2306
0
            goto loser;
2307
0
    }
2308
12
    if (!privateExponent ||
2309
12
        privateExponent->attrib.pValue != tmpKey.privateExponent.data) {
2310
0
        crv = sftk_forceAttribute(object, CKA_PRIVATE_EXPONENT,
2311
0
                                  sftk_item_expand(&tmpKey.privateExponent));
2312
0
        if (crv != CKR_OK)
2313
0
            goto loser;
2314
0
    }
2315
12
    if (!prime1 || prime1->attrib.pValue != tmpKey.prime1.data) {
2316
0
        crv = sftk_forceAttribute(object, CKA_PRIME_1,
2317
0
                                  sftk_item_expand(&tmpKey.prime1));
2318
0
        if (crv != CKR_OK)
2319
0
            goto loser;
2320
0
    }
2321
12
    if (!prime2 || prime2->attrib.pValue != tmpKey.prime2.data) {
2322
0
        crv = sftk_forceAttribute(object, CKA_PRIME_2,
2323
0
                                  sftk_item_expand(&tmpKey.prime2));
2324
0
        if (crv != CKR_OK)
2325
0
            goto loser;
2326
0
    }
2327
12
    if (!exponent1 || exponent1->attrib.pValue != tmpKey.exponent1.data) {
2328
0
        crv = sftk_forceAttribute(object, CKA_EXPONENT_1,
2329
0
                                  sftk_item_expand(&tmpKey.exponent1));
2330
0
        if (crv != CKR_OK)
2331
0
            goto loser;
2332
0
    }
2333
12
    if (!exponent2 || exponent2->attrib.pValue != tmpKey.exponent2.data) {
2334
0
        crv = sftk_forceAttribute(object, CKA_EXPONENT_2,
2335
0
                                  sftk_item_expand(&tmpKey.exponent2));
2336
0
        if (crv != CKR_OK)
2337
0
            goto loser;
2338
0
    }
2339
12
    if (!coefficient || coefficient->attrib.pValue != tmpKey.coefficient.data) {
2340
0
        crv = sftk_forceAttribute(object, CKA_COEFFICIENT,
2341
0
                                  sftk_item_expand(&tmpKey.coefficient));
2342
0
        if (crv != CKR_OK)
2343
0
            goto loser;
2344
0
    }
2345
12
    rv = SECSuccess;
2346
2347
/* we're done (one way or the other), clean up all our stuff */
2348
12
loser:
2349
12
    if (tmpKey.arena) {
2350
0
        PORT_FreeArena(tmpKey.arena, PR_TRUE);
2351
0
    }
2352
12
    if (modulus) {
2353
12
        sftk_FreeAttribute(modulus);
2354
12
    }
2355
12
    if (prime1) {
2356
12
        sftk_FreeAttribute(prime1);
2357
12
    }
2358
12
    if (prime2) {
2359
12
        sftk_FreeAttribute(prime2);
2360
12
    }
2361
12
    if (privateExponent) {
2362
12
        sftk_FreeAttribute(privateExponent);
2363
12
    }
2364
12
    if (publicExponent) {
2365
12
        sftk_FreeAttribute(publicExponent);
2366
12
    }
2367
12
    if (exponent1) {
2368
12
        sftk_FreeAttribute(exponent1);
2369
12
    }
2370
12
    if (exponent2) {
2371
12
        sftk_FreeAttribute(exponent2);
2372
12
    }
2373
12
    if (coefficient) {
2374
12
        sftk_FreeAttribute(coefficient);
2375
12
    }
2376
12
    return rv;
2377
12
}
2378
2379
/* Generate a low private key structure from an object */
2380
NSSLOWKEYPrivateKey *
2381
sftk_GetPrivKey(SFTKObject *object, CK_KEY_TYPE key_type, CK_RV *crvp)
2382
134k
{
2383
134k
    NSSLOWKEYPrivateKey *priv = NULL;
2384
2385
134k
    if (object->objclass != CKO_PRIVATE_KEY) {
2386
0
        *crvp = CKR_KEY_TYPE_INCONSISTENT;
2387
0
        return NULL;
2388
0
    }
2389
134k
    if (object->objectInfo) {
2390
134k
        *crvp = CKR_OK;
2391
134k
        return (NSSLOWKEYPrivateKey *)object->objectInfo;
2392
134k
    }
2393
2394
0
    priv = sftk_mkPrivKey(object, key_type, crvp);
2395
0
    object->objectInfo = priv;
2396
0
    object->infoFree = SFTKFree_nsslowkey_DestroyPrivateKey;
2397
0
    return priv;
2398
134k
}
2399
2400
/* populate a public key object from a lowpublic keys structure */
2401
CK_RV
2402
sftk_PutPubKey(SFTKObject *publicKey, SFTKObject *privateKey, CK_KEY_TYPE keyType, NSSLOWKEYPublicKey *pubKey)
2403
0
{
2404
0
    CK_OBJECT_CLASS classType = CKO_PUBLIC_KEY;
2405
0
    CK_BBOOL cktrue = CK_TRUE;
2406
0
    CK_RV crv = CKR_OK;
2407
0
    sftk_DeleteAttributeType(publicKey, CKA_CLASS);
2408
0
    sftk_DeleteAttributeType(publicKey, CKA_KEY_TYPE);
2409
0
    sftk_DeleteAttributeType(publicKey, CKA_VALUE);
2410
2411
0
    switch (keyType) {
2412
0
        case CKK_RSA:
2413
0
            sftk_DeleteAttributeType(publicKey, CKA_MODULUS);
2414
0
            sftk_DeleteAttributeType(publicKey, CKA_PUBLIC_EXPONENT);
2415
            /* format the keys */
2416
            /* fill in the RSA dependent paramenters in the public key */
2417
0
            crv = sftk_AddAttributeType(publicKey, CKA_MODULUS,
2418
0
                                        sftk_item_expand(&pubKey->u.rsa.modulus));
2419
0
            if (crv != CKR_OK) {
2420
0
                break;
2421
0
            }
2422
0
            crv = sftk_AddAttributeType(publicKey, CKA_PUBLIC_EXPONENT,
2423
0
                                        sftk_item_expand(&pubKey->u.rsa.publicExponent));
2424
0
            break;
2425
0
        case CKK_DSA:
2426
0
            sftk_DeleteAttributeType(publicKey, CKA_PRIME);
2427
0
            sftk_DeleteAttributeType(publicKey, CKA_SUBPRIME);
2428
0
            sftk_DeleteAttributeType(publicKey, CKA_BASE);
2429
0
            crv = sftk_AddAttributeType(publicKey, CKA_PRIME,
2430
0
                                        sftk_item_expand(&pubKey->u.dsa.params.prime));
2431
0
            if (crv != CKR_OK) {
2432
0
                break;
2433
0
            }
2434
0
            crv = sftk_AddAttributeType(publicKey, CKA_SUBPRIME,
2435
0
                                        sftk_item_expand(&pubKey->u.dsa.params.subPrime));
2436
0
            if (crv != CKR_OK) {
2437
0
                break;
2438
0
            }
2439
0
            crv = sftk_AddAttributeType(publicKey, CKA_BASE,
2440
0
                                        sftk_item_expand(&pubKey->u.dsa.params.base));
2441
0
            if (crv != CKR_OK) {
2442
0
                break;
2443
0
            }
2444
0
            crv = sftk_AddAttributeType(publicKey, CKA_VALUE,
2445
0
                                        sftk_item_expand(&pubKey->u.dsa.publicValue));
2446
0
            break;
2447
0
        case CKK_DH:
2448
0
            sftk_DeleteAttributeType(publicKey, CKA_PRIME);
2449
0
            sftk_DeleteAttributeType(publicKey, CKA_BASE);
2450
0
            crv = sftk_AddAttributeType(publicKey, CKA_PRIME,
2451
0
                                        sftk_item_expand(&pubKey->u.dh.prime));
2452
0
            if (crv != CKR_OK) {
2453
0
                break;
2454
0
            }
2455
0
            crv = sftk_AddAttributeType(publicKey, CKA_BASE,
2456
0
                                        sftk_item_expand(&pubKey->u.dh.base));
2457
0
            if (crv != CKR_OK) {
2458
0
                break;
2459
0
            }
2460
0
            crv = sftk_AddAttributeType(publicKey, CKA_VALUE,
2461
0
                                        sftk_item_expand(&pubKey->u.dh.publicValue));
2462
0
            break;
2463
0
        case CKK_EC:
2464
0
        case CKK_EC_MONTGOMERY:
2465
0
        case CKK_EC_EDWARDS:
2466
0
            sftk_DeleteAttributeType(publicKey, CKA_EC_PARAMS);
2467
0
            sftk_DeleteAttributeType(publicKey, CKA_EC_POINT);
2468
0
            crv = sftk_AddAttributeType(publicKey, CKA_EC_PARAMS,
2469
0
                                        sftk_item_expand(&pubKey->u.ec.ecParams.DEREncoding));
2470
0
            if (crv != CKR_OK) {
2471
0
                break;
2472
0
            }
2473
0
            crv = sftk_AddAttributeType(publicKey, CKA_EC_POINT,
2474
0
                                        sftk_item_expand(&pubKey->u.ec.publicValue));
2475
0
            break;
2476
0
        default:
2477
0
            return CKR_KEY_TYPE_INCONSISTENT;
2478
0
    }
2479
0
    if (crv != CKR_OK) {
2480
0
        return crv;
2481
0
    }
2482
0
    crv = sftk_AddAttributeType(publicKey, CKA_CLASS, &classType,
2483
0
                                sizeof(CK_OBJECT_CLASS));
2484
0
    if (crv != CKR_OK) {
2485
0
        return crv;
2486
0
    }
2487
0
    crv = sftk_AddAttributeType(publicKey, CKA_KEY_TYPE, &keyType,
2488
0
                                sizeof(CK_KEY_TYPE));
2489
0
    if (crv != CKR_OK) {
2490
0
        return crv;
2491
0
    }
2492
    /* now handle the operator attributes */
2493
0
    if (sftk_isTrue(privateKey, CKA_DECRYPT)) {
2494
0
        crv = sftk_forceAttribute(publicKey, CKA_ENCRYPT, &cktrue, sizeof(CK_BBOOL));
2495
0
        if (crv != CKR_OK) {
2496
0
            return crv;
2497
0
        }
2498
0
    }
2499
0
    if (sftk_isTrue(privateKey, CKA_SIGN)) {
2500
0
        crv = sftk_forceAttribute(publicKey, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
2501
0
        if (crv != CKR_OK) {
2502
0
            return crv;
2503
0
        }
2504
0
    }
2505
0
    if (sftk_isTrue(privateKey, CKA_SIGN_RECOVER)) {
2506
0
        crv = sftk_forceAttribute(publicKey, CKA_VERIFY_RECOVER, &cktrue, sizeof(CK_BBOOL));
2507
0
        if (crv != CKR_OK) {
2508
0
            return crv;
2509
0
        }
2510
0
    }
2511
0
    if (sftk_isTrue(privateKey, CKA_DERIVE)) {
2512
0
        crv = sftk_forceAttribute(publicKey, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));
2513
0
        if (crv != CKR_OK) {
2514
0
            return crv;
2515
0
        }
2516
0
    }
2517
0
    return crv;
2518
0
}
2519
2520
/*
2521
 **************************** Symetric Key utils ************************
2522
 */
2523
/*
2524
 * set the DES key with parity bits correctly
2525
 */
2526
void
2527
sftk_FormatDESKey(unsigned char *key, int length)
2528
32.1k
{
2529
32.1k
    int i;
2530
2531
    /* format the des key */
2532
715k
    for (i = 0; i < length; i++) {
2533
683k
        key[i] = parityTable[key[i] >> 1];
2534
683k
    }
2535
32.1k
}
2536
2537
/*
2538
 * check a des key (des2 or des3 subkey) for weak keys.
2539
 */
2540
PRBool
2541
sftk_CheckDESKey(unsigned char *key)
2542
0
{
2543
0
    int i;
2544
2545
    /* format the des key with parity  */
2546
0
    sftk_FormatDESKey(key, 8);
2547
2548
0
    for (i = 0; i < sftk_desWeakTableSize; i++) {
2549
0
        if (PORT_Memcmp(key, sftk_desWeakTable[i], 8) == 0) {
2550
0
            return PR_TRUE;
2551
0
        }
2552
0
    }
2553
0
    return PR_FALSE;
2554
0
}
2555
2556
/*
2557
 * check if a des or triple des key is weak.
2558
 */
2559
PRBool
2560
sftk_IsWeakKey(unsigned char *key, CK_KEY_TYPE key_type)
2561
5.06k
{
2562
2563
5.06k
    switch (key_type) {
2564
0
        case CKK_DES:
2565
0
            return sftk_CheckDESKey(key);
2566
0
        case CKM_DES2_KEY_GEN:
2567
0
            if (sftk_CheckDESKey(key))
2568
0
                return PR_TRUE;
2569
0
            return sftk_CheckDESKey(&key[8]);
2570
0
        case CKM_DES3_KEY_GEN:
2571
0
            if (sftk_CheckDESKey(key))
2572
0
                return PR_TRUE;
2573
0
            if (sftk_CheckDESKey(&key[8]))
2574
0
                return PR_TRUE;
2575
0
            return sftk_CheckDESKey(&key[16]);
2576
5.06k
        default:
2577
5.06k
            break;
2578
5.06k
    }
2579
5.06k
    return PR_FALSE;
2580
5.06k
}
2581
2582
/**********************************************************************
2583
 *
2584
 *     Start of PKCS 11 functions
2585
 *
2586
 **********************************************************************/
2587
2588
/* return the function list */
2589
CK_RV
2590
NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList)
2591
0
{
2592
0
    *pFunctionList = (CK_FUNCTION_LIST_PTR)&sftk_funcList_v2;
2593
0
    return CKR_OK;
2594
0
}
2595
2596
/* return the function list */
2597
CK_RV
2598
C_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList)
2599
0
{
2600
0
#ifdef NSS_FIPS_DISABLED
2601
0
    return NSC_GetFunctionList(pFunctionList);
2602
#else
2603
    if (NSS_GetSystemFIPSEnabled()) {
2604
        return FC_GetFunctionList(pFunctionList);
2605
    } else {
2606
        return NSC_GetFunctionList(pFunctionList);
2607
    }
2608
#endif
2609
0
}
2610
2611
CK_RV
2612
NSC_GetInterfaceList(CK_INTERFACE_PTR interfaces, CK_ULONG_PTR pulCount)
2613
0
{
2614
0
    CK_ULONG count = *pulCount;
2615
0
    *pulCount = NSS_INTERFACE_COUNT;
2616
0
    if (interfaces == NULL) {
2617
0
        return CKR_OK;
2618
0
    }
2619
0
    if (count < NSS_INTERFACE_COUNT) {
2620
0
        return CKR_BUFFER_TOO_SMALL;
2621
0
    }
2622
0
    PORT_Memcpy(interfaces, nss_interfaces, sizeof(nss_interfaces));
2623
0
    return CKR_OK;
2624
0
}
2625
2626
CK_RV
2627
C_GetInterfaceList(CK_INTERFACE_PTR interfaces, CK_ULONG_PTR pulCount)
2628
0
{
2629
0
#ifdef NSS_FIPS_DISABLED
2630
0
    return NSC_GetInterfaceList(interfaces, pulCount);
2631
#else
2632
    if (NSS_GetSystemFIPSEnabled()) {
2633
        return FC_GetInterfaceList(interfaces, pulCount);
2634
    } else {
2635
        return NSC_GetInterfaceList(interfaces, pulCount);
2636
    }
2637
#endif
2638
0
}
2639
2640
/*
2641
 * Get the requested interface, use the nss_interfaces array so we can
2642
 * easily add new interfaces as they occur.
2643
 */
2644
CK_RV
2645
NSC_GetInterface(CK_UTF8CHAR_PTR pInterfaceName, CK_VERSION_PTR pVersion,
2646
                 CK_INTERFACE_PTR_PTR ppInterface, CK_FLAGS flags)
2647
195
{
2648
195
    int i;
2649
955
    for (i = 0; i < NSS_INTERFACE_COUNT; i++) {
2650
955
        CK_INTERFACE_PTR interface = &nss_interfaces[i];
2651
955
        if (pInterfaceName && PORT_Strcmp((char *)pInterfaceName, (char *)interface->pInterfaceName) != 0) {
2652
760
            continue;
2653
760
        }
2654
195
        if (pVersion && PORT_Memcmp(pVersion, (CK_VERSION *)interface->pFunctionList, sizeof(CK_VERSION)) != 0) {
2655
0
            continue;
2656
0
        }
2657
195
        if (flags & ((interface->flags & flags) != flags)) {
2658
0
            continue;
2659
0
        }
2660
195
        *ppInterface = interface;
2661
195
        return CKR_OK;
2662
195
    }
2663
0
    return CKR_ARGUMENTS_BAD;
2664
195
}
2665
2666
CK_RV
2667
C_GetInterface(CK_UTF8CHAR_PTR pInterfaceName, CK_VERSION_PTR pVersion,
2668
               CK_INTERFACE_PTR_PTR ppInterface, CK_FLAGS flags)
2669
0
{
2670
0
#ifdef NSS_FIPS_DISABLED
2671
0
    return NSC_GetInterface(pInterfaceName, pVersion, ppInterface, flags);
2672
#else
2673
    if (NSS_GetSystemFIPSEnabled()) {
2674
        return FC_GetInterface(pInterfaceName, pVersion, ppInterface, flags);
2675
    } else {
2676
        return NSC_GetInterface(pInterfaceName, pVersion, ppInterface, flags);
2677
    }
2678
#endif
2679
0
}
2680
2681
static PLHashNumber
2682
sftk_HashNumber(const void *key)
2683
11.5M
{
2684
11.5M
    return (PLHashNumber)((char *)key - (char *)NULL);
2685
11.5M
}
2686
2687
/*
2688
 * eventually I'd like to expunge all occurances of XXX_SLOT_ID and
2689
 * just go with the info in the slot. This is one place, however,
2690
 * where it might be a little difficult.
2691
 */
2692
const char *
2693
sftk_getDefTokName(CK_SLOT_ID slotID)
2694
8
{
2695
8
    static char buf[33];
2696
2697
8
    switch (slotID) {
2698
4
        case NETSCAPE_SLOT_ID:
2699
4
            return "NSS Generic Crypto Services     ";
2700
4
        case PRIVATE_KEY_SLOT_ID:
2701
4
            return "NSS Certificate DB              ";
2702
0
        case FIPS_SLOT_ID:
2703
0
            return "NSS FIPS 140-2 Certificate DB   ";
2704
0
        default:
2705
0
            break;
2706
8
    }
2707
0
    snprintf(buf, sizeof(buf), "NSS Application Token %08x  ", (unsigned int)slotID);
2708
0
    return buf;
2709
8
}
2710
2711
const char *
2712
sftk_getDefSlotName(CK_SLOT_ID slotID)
2713
8
{
2714
8
    static char buf[65];
2715
2716
8
    switch (slotID) {
2717
4
        case NETSCAPE_SLOT_ID:
2718
4
            return "NSS Internal Cryptographic Services                             ";
2719
4
        case PRIVATE_KEY_SLOT_ID:
2720
4
            return "NSS User Private Key and Certificate Services                   ";
2721
0
        case FIPS_SLOT_ID:
2722
0
            return "NSS FIPS 140-2 User Private Key Services                        ";
2723
0
        default:
2724
0
            break;
2725
8
    }
2726
0
    snprintf(buf, sizeof(buf),
2727
0
             "NSS Application Slot %08x                                   ",
2728
0
             (unsigned int)slotID);
2729
0
    return buf;
2730
8
}
2731
2732
static CK_ULONG nscSlotCount[2] = { 0, 0 };
2733
static CK_SLOT_ID_PTR nscSlotList[2] = { NULL, NULL };
2734
static CK_ULONG nscSlotListSize[2] = { 0, 0 };
2735
static PLHashTable *nscSlotHashTable[2] = { NULL, NULL };
2736
2737
static unsigned int
2738
sftk_GetModuleIndex(CK_SLOT_ID slotID)
2739
11.5M
{
2740
11.5M
    if (sftk_isFIPS(slotID)) {
2741
0
        return NSC_FIPS_MODULE;
2742
0
    }
2743
11.5M
    return NSC_NON_FIPS_MODULE;
2744
11.5M
}
2745
2746
/* look up a slot structure from the ID (used to be a macro when we only
2747
 * had two slots) */
2748
/* if all is true, return the slot even if it has been 'unloaded' */
2749
/* if all is false, only return the slots which are present */
2750
SFTKSlot *
2751
sftk_SlotFromID(CK_SLOT_ID slotID, PRBool all)
2752
11.5M
{
2753
11.5M
    SFTKSlot *slot;
2754
11.5M
    unsigned int index = sftk_GetModuleIndex(slotID);
2755
2756
11.5M
    if (nscSlotHashTable[index] == NULL)
2757
0
        return NULL;
2758
11.5M
    slot = (SFTKSlot *)PL_HashTableLookupConst(nscSlotHashTable[index],
2759
11.5M
                                               (void *)(uintptr_t)slotID);
2760
    /* cleared slots shouldn't 'show up' */
2761
11.5M
    if (slot && !all && !slot->present)
2762
0
        slot = NULL;
2763
11.5M
    return slot;
2764
11.5M
}
2765
2766
CK_SLOT_ID
2767
sftk_SlotIDFromSessionHandle(CK_SESSION_HANDLE handle)
2768
9.84M
{
2769
9.84M
    CK_ULONG slotIDIndex = (handle >> 24) & 0x7f;
2770
9.84M
    CK_ULONG moduleIndex = (handle >> 31) & 1;
2771
2772
9.84M
    if (slotIDIndex >= nscSlotCount[moduleIndex]) {
2773
0
        return (CK_SLOT_ID)-1;
2774
0
    }
2775
9.84M
    return nscSlotList[moduleIndex][slotIDIndex];
2776
9.84M
}
2777
2778
SFTKSlot *
2779
sftk_SlotFromSessionHandle(CK_SESSION_HANDLE handle)
2780
9.84M
{
2781
9.84M
    return sftk_SlotFromID(sftk_SlotIDFromSessionHandle(handle), PR_FALSE);
2782
9.84M
}
2783
2784
static CK_RV
2785
sftk_RegisterSlot(SFTKSlot *slot, unsigned int moduleIndex)
2786
8
{
2787
8
    PLHashEntry *entry;
2788
8
    unsigned int index;
2789
2790
8
    index = sftk_GetModuleIndex(slot->slotID);
2791
2792
    /* make sure the slotID for this module is valid */
2793
8
    if (moduleIndex != index) {
2794
0
        return CKR_SLOT_ID_INVALID;
2795
0
    }
2796
2797
8
    if (nscSlotList[index] == NULL) {
2798
4
        nscSlotListSize[index] = NSC_SLOT_LIST_BLOCK_SIZE;
2799
4
        nscSlotList[index] = (CK_SLOT_ID *)
2800
4
            PORT_ZAlloc(nscSlotListSize[index] * sizeof(CK_SLOT_ID));
2801
4
        if (nscSlotList[index] == NULL) {
2802
0
            return CKR_HOST_MEMORY;
2803
0
        }
2804
4
    }
2805
8
    if (nscSlotCount[index] >= nscSlotListSize[index]) {
2806
0
        CK_SLOT_ID *oldNscSlotList = nscSlotList[index];
2807
0
        CK_ULONG oldNscSlotListSize = nscSlotListSize[index];
2808
0
        nscSlotListSize[index] += NSC_SLOT_LIST_BLOCK_SIZE;
2809
0
        nscSlotList[index] = (CK_SLOT_ID *)PORT_Realloc(oldNscSlotList,
2810
0
                                                        nscSlotListSize[index] * sizeof(CK_SLOT_ID));
2811
0
        if (nscSlotList[index] == NULL) {
2812
            /* evidently coverity doesn't know realloc does not
2813
             * free var if it fails ! */
2814
            /* coverity [use_after_free : FALSE] */
2815
0
            nscSlotList[index] = oldNscSlotList;
2816
0
            nscSlotListSize[index] = oldNscSlotListSize;
2817
0
            return CKR_HOST_MEMORY;
2818
0
        }
2819
0
    }
2820
2821
8
    if (nscSlotHashTable[index] == NULL) {
2822
4
        nscSlotHashTable[index] = PL_NewHashTable(64, sftk_HashNumber,
2823
4
                                                  PL_CompareValues, PL_CompareValues, NULL, 0);
2824
4
        if (nscSlotHashTable[index] == NULL) {
2825
0
            return CKR_HOST_MEMORY;
2826
0
        }
2827
4
    }
2828
2829
8
    entry = PL_HashTableAdd(nscSlotHashTable[index], (void *)(uintptr_t)slot->slotID, slot);
2830
8
    if (entry == NULL) {
2831
0
        return CKR_HOST_MEMORY;
2832
0
    }
2833
8
    slot->index = (nscSlotCount[index] & 0x7f) | ((index << 7) & 0x80);
2834
8
    nscSlotList[index][nscSlotCount[index]++] = slot->slotID;
2835
2836
8
    return CKR_OK;
2837
8
}
2838
2839
/*
2840
 * ths function has all the common initialization that happens whenever we
2841
 * create a new slot or repurpose an old slot (only valid for slotID's 4
2842
 * and greater).
2843
 *
2844
 * things that are not reinitialized are:
2845
 *   slotID (can't change)
2846
 *   slotDescription (can't change once defined)
2847
 *   the locks and hash tables (difficult to change in running code, and
2848
 *     unnecessary. hash tables and list are cleared on shutdown, but they
2849
 *     are cleared in a 'friendly' way).
2850
 *   session and object ID counters -- so any old sessions and objects in the
2851
 *     application will get properly notified that the world has changed.
2852
 *
2853
 * things that are reinitialized:
2854
 *   database (otherwise what would the point be;).
2855
 *   state variables related to databases.
2856
 *   session count stat info.
2857
 *   tokenDescription.
2858
 *
2859
 * NOTE: slotID's 4 and greater show up as removable devices.
2860
 *
2861
 */
2862
CK_RV
2863
SFTK_SlotReInit(SFTKSlot *slot, char *configdir, char *updatedir,
2864
                char *updateID, sftk_token_parameters *params,
2865
                unsigned int moduleIndex)
2866
8
{
2867
8
    PRBool needLogin = !params->noKeyDB;
2868
8
    CK_RV crv;
2869
2870
8
    slot->hasTokens = PR_FALSE;
2871
8
    slot->sessionIDConflict = 0;
2872
8
    slot->sessionCount = 0;
2873
8
    slot->rwSessionCount = 0;
2874
8
    slot->needLogin = PR_FALSE;
2875
8
    slot->isLoggedIn = PR_FALSE;
2876
8
    slot->ssoLoggedIn = PR_FALSE;
2877
8
    slot->DB_loaded = PR_FALSE;
2878
8
    slot->certDB = NULL;
2879
8
    slot->keyDB = NULL;
2880
8
    slot->minimumPinLen = 0;
2881
8
    slot->readOnly = params->readOnly;
2882
8
    sftk_setStringName(params->tokdes ? params->tokdes : sftk_getDefTokName(slot->slotID), slot->tokDescription,
2883
8
                       sizeof(slot->tokDescription), PR_TRUE);
2884
8
    sftk_setStringName(params->updtokdes ? params->updtokdes : " ",
2885
8
                       slot->updateTokDescription,
2886
8
                       sizeof(slot->updateTokDescription), PR_TRUE);
2887
2888
8
    if ((!params->noCertDB) || (!params->noKeyDB)) {
2889
0
        SFTKDBHandle *certHandle = NULL;
2890
0
        SFTKDBHandle *keyHandle = NULL;
2891
0
        crv = sftk_DBInit(params->configdir ? params->configdir : configdir,
2892
0
                          params->certPrefix, params->keyPrefix,
2893
0
                          params->updatedir ? params->updatedir : updatedir,
2894
0
                          params->updCertPrefix, params->updKeyPrefix,
2895
0
                          params->updateID ? params->updateID : updateID,
2896
0
                          params->readOnly, params->noCertDB, params->noKeyDB,
2897
0
                          params->forceOpen,
2898
0
                          moduleIndex == NSC_FIPS_MODULE,
2899
0
                          &certHandle, &keyHandle);
2900
0
        if (crv != CKR_OK) {
2901
0
            goto loser;
2902
0
        }
2903
2904
0
        slot->certDB = certHandle;
2905
0
        slot->keyDB = keyHandle;
2906
0
    }
2907
8
    if (needLogin) {
2908
        /* if the data base is initialized with a null password,remember that */
2909
0
        slot->needLogin =
2910
0
            (PRBool)!sftk_hasNullPassword(slot, slot->keyDB);
2911
0
        if ((params->minPW >= 0) && (params->minPW <= SFTK_MAX_PIN)) {
2912
0
            slot->minimumPinLen = params->minPW;
2913
0
        }
2914
0
        if ((slot->minimumPinLen == 0) && (params->pwRequired)) {
2915
0
            slot->minimumPinLen = 1;
2916
0
        }
2917
        /* Make sure the pin len is set to the Minimum allowed value for fips
2918
         * when in FIPS mode. NOTE: we don't set it if the database has not
2919
         * been initialized yet so that we can init into level1 mode if needed
2920
         */
2921
0
        if ((sftkdb_HasPasswordSet(slot->keyDB) == SECSuccess) &&
2922
0
            (moduleIndex == NSC_FIPS_MODULE) &&
2923
0
            (slot->minimumPinLen < FIPS_MIN_PIN)) {
2924
0
            slot->minimumPinLen = FIPS_MIN_PIN;
2925
0
        }
2926
0
    }
2927
2928
8
    slot->present = PR_TRUE;
2929
8
    return CKR_OK;
2930
2931
0
loser:
2932
0
    SFTK_ShutdownSlot(slot);
2933
0
    return crv;
2934
8
}
2935
2936
/*
2937
 * initialize one of the slot structures. figure out which by the ID
2938
 */
2939
CK_RV
2940
SFTK_SlotInit(char *configdir, char *updatedir, char *updateID,
2941
              sftk_token_parameters *params, unsigned int moduleIndex)
2942
8
{
2943
8
    unsigned int i;
2944
8
    CK_SLOT_ID slotID = params->slotID;
2945
8
    SFTKSlot *slot;
2946
8
    CK_RV crv = CKR_HOST_MEMORY;
2947
2948
    /*
2949
     * first we initialize everything that is 'permanent' with this slot.
2950
     * that is everything we aren't going to shutdown if we close this slot
2951
     * and open it up again with different databases */
2952
2953
8
    slot = PORT_ZNew(SFTKSlot);
2954
2955
8
    if (slot == NULL) {
2956
0
        return CKR_HOST_MEMORY;
2957
0
    }
2958
2959
8
    slot->optimizeSpace = params->optimizeSpace;
2960
8
    if (slot->optimizeSpace) {
2961
8
        slot->sessObjHashSize = SPACE_SESSION_OBJECT_HASH_SIZE;
2962
8
        slot->sessHashSize = SPACE_SESSION_HASH_SIZE;
2963
8
        slot->numSessionLocks = 1;
2964
8
    } else {
2965
0
        slot->sessObjHashSize = TIME_SESSION_OBJECT_HASH_SIZE;
2966
0
        slot->sessHashSize = TIME_SESSION_HASH_SIZE;
2967
0
        slot->numSessionLocks = slot->sessHashSize / BUCKETS_PER_SESSION_LOCK;
2968
0
    }
2969
8
    slot->sessionLockMask = slot->numSessionLocks - 1;
2970
2971
8
    slot->slotLock = PZ_NewLock(nssILockSession);
2972
8
    if (slot->slotLock == NULL)
2973
0
        goto mem_loser;
2974
8
    slot->sessionLock = PORT_ZNewArray(PZLock *, slot->numSessionLocks);
2975
8
    if (slot->sessionLock == NULL)
2976
0
        goto mem_loser;
2977
16
    for (i = 0; i < slot->numSessionLocks; i++) {
2978
8
        slot->sessionLock[i] = PZ_NewLock(nssILockSession);
2979
8
        if (slot->sessionLock[i] == NULL)
2980
0
            goto mem_loser;
2981
8
    }
2982
8
    slot->objectLock = PZ_NewLock(nssILockObject);
2983
8
    if (slot->objectLock == NULL)
2984
0
        goto mem_loser;
2985
8
    slot->pwCheckLock = PR_NewLock();
2986
8
    if (slot->pwCheckLock == NULL)
2987
0
        goto mem_loser;
2988
8
    slot->head = PORT_ZNewArray(SFTKSession *, slot->sessHashSize);
2989
8
    if (slot->head == NULL)
2990
0
        goto mem_loser;
2991
8
    slot->sessObjHashTable = PORT_ZNewArray(SFTKObject *, slot->sessObjHashSize);
2992
8
    if (slot->sessObjHashTable == NULL)
2993
0
        goto mem_loser;
2994
8
    slot->tokObjHashTable = PL_NewHashTable(64, sftk_HashNumber, PL_CompareValues,
2995
8
                                            SECITEM_HashCompare, NULL, 0);
2996
8
    if (slot->tokObjHashTable == NULL)
2997
0
        goto mem_loser;
2998
2999
8
    slot->sessionIDCount = 0;
3000
8
    slot->sessionObjectHandleCount = NSC_MIN_SESSION_OBJECT_HANDLE;
3001
8
    slot->slotID = slotID;
3002
8
    sftk_setStringName(params->slotdes ? params->slotdes : sftk_getDefSlotName(slotID), slot->slotDescription,
3003
8
                       sizeof(slot->slotDescription), PR_TRUE);
3004
8
    crv = sftk_InitSession(&slot->moduleObjects, slot, slotID, NULL, NULL,
3005
8
                           CKF_SERIAL_SESSION);
3006
8
    if (crv != CKR_OK) {
3007
0
        goto loser;
3008
0
    }
3009
3010
    /* call the reinit code to set everything that changes between token
3011
     * init calls */
3012
8
    crv = SFTK_SlotReInit(slot, configdir, updatedir, updateID,
3013
8
                          params, moduleIndex);
3014
8
    if (crv != CKR_OK) {
3015
0
        goto loser;
3016
0
    }
3017
8
    if (sftk_isFIPS(slotID)) {
3018
0
        crv = sftk_CreateValidationObjects(slot);
3019
0
        if (crv != CKR_OK) {
3020
0
            goto loser;
3021
0
        }
3022
0
    }
3023
8
    crv = sftk_RegisterSlot(slot, moduleIndex);
3024
8
    if (crv != CKR_OK) {
3025
0
        goto loser;
3026
0
    }
3027
8
    return CKR_OK;
3028
3029
0
mem_loser:
3030
0
    crv = CKR_HOST_MEMORY;
3031
0
loser:
3032
0
    SFTK_DestroySlotData(slot);
3033
0
    return crv;
3034
0
}
3035
3036
CK_RV
3037
sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout)
3038
24
{
3039
24
    SFTKSession *session;
3040
24
    unsigned int i;
3041
24
    SFTKDBHandle *handle;
3042
3043
    /* first log out the card */
3044
    /* special case - if we are in a middle of upgrade, we want to close the
3045
     * sessions to fake a token removal to tell the upper level code we have
3046
     * switched from one database to another, but we don't want to
3047
     * explicity logout in case we can continue the upgrade with the
3048
     * existing password if possible.
3049
     */
3050
24
    if (logout) {
3051
24
        handle = sftk_getKeyDB(slot);
3052
24
        SKIP_AFTER_FORK(PZ_Lock(slot->slotLock));
3053
24
        slot->isLoggedIn = PR_FALSE;
3054
24
        if (slot->needLogin && handle) {
3055
0
            sftkdb_ClearPassword(handle);
3056
0
        }
3057
24
        SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock));
3058
24
        if (handle) {
3059
0
            sftk_freeDB(handle);
3060
0
        }
3061
24
    }
3062
3063
    /* now close all the current sessions */
3064
    /* NOTE: If you try to open new sessions before NSC_CloseAllSessions
3065
     * completes, some of those new sessions may or may not be closed by
3066
     * NSC_CloseAllSessions... but any session running when this code starts
3067
     * will guarrenteed be close, and no session will be partially closed */
3068
792
    for (i = 0; i < slot->sessHashSize; i++) {
3069
768
        PZLock *lock = SFTK_SESSION_LOCK(slot, i);
3070
777
        do {
3071
777
            SKIP_AFTER_FORK(PZ_Lock(lock));
3072
777
            session = slot->head[i];
3073
            /* hand deque */
3074
            /* this duplicates function of NSC_close session functions, but
3075
             * because we know that we are freeing all the sessions, we can
3076
             * do more efficient processing */
3077
777
            if (session) {
3078
9
                slot->head[i] = session->next;
3079
9
                if (session->next)
3080
0
                    session->next->prev = NULL;
3081
9
                session->next = session->prev = NULL;
3082
9
                SKIP_AFTER_FORK(PZ_Unlock(lock));
3083
9
                SKIP_AFTER_FORK(PZ_Lock(slot->slotLock));
3084
9
                --slot->sessionCount;
3085
9
                SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock));
3086
9
                if (session->info.flags & CKF_RW_SESSION) {
3087
0
                    (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount);
3088
0
                }
3089
768
            } else {
3090
768
                SKIP_AFTER_FORK(PZ_Unlock(lock));
3091
768
            }
3092
777
            if (session) {
3093
9
                sftk_DestroySession(session);
3094
9
            }
3095
777
        } while (session != NULL);
3096
768
    }
3097
24
    return CKR_OK;
3098
24
}
3099
3100
/*
3101
 * shut down the databases.
3102
 * we get the slot lock (which also protects slot->certDB and slot->keyDB)
3103
 * and clear the values so the new users will not find the databases.
3104
 * once things are clear, we can release our references to the databases.
3105
 * The databases will close when the last reference is released.
3106
 *
3107
 * We use reference counts so that we don't crash if someone shuts down
3108
 * a token that another thread is actively using.
3109
 */
3110
static void
3111
sftk_DBShutdown(SFTKSlot *slot)
3112
8
{
3113
8
    SFTKDBHandle *certHandle;
3114
8
    SFTKDBHandle *keyHandle;
3115
8
    SKIP_AFTER_FORK(PZ_Lock(slot->slotLock));
3116
8
    certHandle = slot->certDB;
3117
8
    slot->certDB = NULL;
3118
8
    keyHandle = slot->keyDB;
3119
8
    slot->keyDB = NULL;
3120
8
    SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock));
3121
8
    if (certHandle) {
3122
0
        sftk_freeDB(certHandle);
3123
0
    }
3124
8
    if (keyHandle) {
3125
0
        sftk_freeDB(keyHandle);
3126
0
    }
3127
8
}
3128
3129
CK_RV
3130
SFTK_ShutdownSlot(SFTKSlot *slot)
3131
8
{
3132
    /* make sure no new PK11 calls work except C_GetSlotInfo */
3133
8
    slot->present = PR_FALSE;
3134
3135
    /* close all outstanding sessions
3136
     * the sessHashSize variable guarentees we have all the session
3137
     * mechanism set up */
3138
8
    if (slot->head) {
3139
8
        sftk_CloseAllSessions(slot, PR_TRUE);
3140
8
    }
3141
3142
    /* clear all objects.. session objects are cleared as a result of
3143
     * closing all the sessions. We just need to clear the token object
3144
     * cache. slot->tokObjHashTable guarentees we have the token
3145
     * infrastructure set up. */
3146
8
    if (slot->tokObjHashTable) {
3147
8
        SFTK_ClearTokenKeyHashTable(slot);
3148
8
    }
3149
3150
    /* clear the slot description for the next guy */
3151
8
    PORT_Memset(slot->tokDescription, 0, sizeof(slot->tokDescription));
3152
3153
    /* now shut down the databases. */
3154
8
    sftk_DBShutdown(slot);
3155
8
    return CKR_OK;
3156
8
}
3157
3158
/*
3159
 * initialize one of the slot structures. figure out which by the ID
3160
 */
3161
CK_RV
3162
SFTK_DestroySlotData(SFTKSlot *slot)
3163
8
{
3164
8
    unsigned int i;
3165
3166
8
    SFTK_ShutdownSlot(slot);
3167
3168
8
    sftk_ClearSession(&slot->moduleObjects);
3169
3170
8
    if (slot->tokObjHashTable) {
3171
8
        PL_HashTableDestroy(slot->tokObjHashTable);
3172
8
        slot->tokObjHashTable = NULL;
3173
8
    }
3174
3175
8
    if (slot->sessObjHashTable) {
3176
8
        PORT_Free(slot->sessObjHashTable);
3177
8
        slot->sessObjHashTable = NULL;
3178
8
    }
3179
8
    slot->sessObjHashSize = 0;
3180
3181
8
    if (slot->head) {
3182
8
        PORT_Free(slot->head);
3183
8
        slot->head = NULL;
3184
8
    }
3185
8
    slot->sessHashSize = 0;
3186
3187
    /* OK everything has been disassembled, now we can finally get rid
3188
     * of the locks */
3189
8
    SKIP_AFTER_FORK(PZ_DestroyLock(slot->slotLock));
3190
8
    slot->slotLock = NULL;
3191
8
    if (slot->sessionLock) {
3192
16
        for (i = 0; i < slot->numSessionLocks; i++) {
3193
8
            if (slot->sessionLock[i]) {
3194
8
                SKIP_AFTER_FORK(PZ_DestroyLock(slot->sessionLock[i]));
3195
8
                slot->sessionLock[i] = NULL;
3196
8
            }
3197
8
        }
3198
8
        PORT_Free(slot->sessionLock);
3199
8
        slot->sessionLock = NULL;
3200
8
    }
3201
8
    if (slot->objectLock) {
3202
8
        SKIP_AFTER_FORK(PZ_DestroyLock(slot->objectLock));
3203
8
        slot->objectLock = NULL;
3204
8
    }
3205
8
    if (slot->pwCheckLock) {
3206
8
        SKIP_AFTER_FORK(PR_DestroyLock(slot->pwCheckLock));
3207
8
        slot->pwCheckLock = NULL;
3208
8
    }
3209
8
    PORT_Free(slot);
3210
8
    return CKR_OK;
3211
8
}
3212
3213
/*
3214
 * handle the SECMOD.db
3215
 */
3216
char **
3217
NSC_ModuleDBFunc(unsigned long function, char *parameters, void *args)
3218
8
{
3219
8
#ifdef NSS_DISABLE_DBM
3220
8
    return NSSUTIL_DoModuleDBFunction(function, parameters, args);
3221
#else
3222
    char *secmod = NULL;
3223
    char *appName = NULL;
3224
    char *filename = NULL;
3225
    NSSDBType dbType = NSS_DB_TYPE_NONE;
3226
    PRBool rw;
3227
    static char *success = "Success";
3228
    char **rvstr = NULL;
3229
3230
    rvstr = NSSUTIL_DoModuleDBFunction(function, parameters, args);
3231
    if (rvstr != NULL) {
3232
        return rvstr;
3233
    }
3234
3235
    if (PORT_GetError() != SEC_ERROR_LEGACY_DATABASE) {
3236
        return NULL;
3237
    }
3238
3239
    /* The legacy database uses the old dbm, which is only linked with the
3240
     * legacy DB handler, which is only callable from softoken */
3241
3242
    secmod = _NSSUTIL_GetSecmodName(parameters, &dbType, &appName,
3243
                                    &filename, &rw);
3244
3245
    switch (function) {
3246
        case SECMOD_MODULE_DB_FUNCTION_FIND:
3247
            if (secmod == NULL) {
3248
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
3249
                goto loser;
3250
            }
3251
            if (rw && (dbType != NSS_DB_TYPE_LEGACY) &&
3252
                (dbType != NSS_DB_TYPE_MULTIACCESS)) {
3253
                /* if we get here, we are trying to update the local database */
3254
                /* force data from the legacy DB */
3255
                char *oldSecmod = NULL;
3256
                char *oldAppName = NULL;
3257
                char *oldFilename = NULL;
3258
                PRBool oldrw;
3259
                char **strings = NULL;
3260
                int i;
3261
3262
                dbType = NSS_DB_TYPE_LEGACY;
3263
                oldSecmod = _NSSUTIL_GetSecmodName(parameters, &dbType, &oldAppName,
3264
                                                   &oldFilename, &oldrw);
3265
                strings = sftkdbCall_ReadSecmodDB(appName, oldFilename, oldSecmod,
3266
                                                  (char *)parameters, oldrw);
3267
                if (strings) {
3268
                    /* write out the strings */
3269
                    for (i = 0; strings[i]; i++) {
3270
                        NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD,
3271
                                                   parameters, strings[i]);
3272
                    }
3273
                    sftkdbCall_ReleaseSecmodDBData(oldAppName, oldFilename, oldSecmod,
3274
                                                   (char **)strings, oldrw);
3275
                } else {
3276
                    /* write out a dummy record */
3277
                    NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD,
3278
                                               parameters, " ");
3279
                }
3280
                if (oldSecmod) {
3281
                    PR_smprintf_free(oldSecmod);
3282
                }
3283
                if (oldAppName) {
3284
                    PORT_Free(oldAppName);
3285
                }
3286
                if (oldFilename) {
3287
                    PORT_Free(oldFilename);
3288
                }
3289
                rvstr = NSSUTIL_DoModuleDBFunction(function, parameters, args);
3290
                break;
3291
            }
3292
            rvstr = sftkdbCall_ReadSecmodDB(appName, filename, secmod,
3293
                                            (char *)parameters, rw);
3294
            break;
3295
        case SECMOD_MODULE_DB_FUNCTION_ADD:
3296
            if (secmod == NULL) {
3297
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
3298
                goto loser;
3299
            }
3300
            rvstr = (sftkdbCall_AddSecmodDB(appName, filename, secmod,
3301
                                            (char *)args, rw) == SECSuccess)
3302
                        ? &success
3303
                        : NULL;
3304
            break;
3305
        case SECMOD_MODULE_DB_FUNCTION_DEL:
3306
            if (secmod == NULL) {
3307
                PORT_SetError(SEC_ERROR_INVALID_ARGS);
3308
                goto loser;
3309
            }
3310
            rvstr = (sftkdbCall_DeleteSecmodDB(appName, filename, secmod,
3311
                                               (char *)args, rw) == SECSuccess)
3312
                        ? &success
3313
                        : NULL;
3314
            break;
3315
        case SECMOD_MODULE_DB_FUNCTION_RELEASE:
3316
            rvstr = (sftkdbCall_ReleaseSecmodDBData(appName, filename, secmod,
3317
                                                    (char **)args, rw) == SECSuccess)
3318
                        ? &success
3319
                        : NULL;
3320
            break;
3321
    }
3322
3323
loser:
3324
    if (secmod)
3325
        PR_smprintf_free(secmod);
3326
    if (appName)
3327
        PORT_Free(appName);
3328
    if (filename)
3329
        PORT_Free(filename);
3330
    return rvstr;
3331
#endif /* NSS_DISABLE_DBM */
3332
8
}
3333
3334
static void
3335
nscFreeAllSlots(unsigned int moduleIndex)
3336
4
{
3337
    /* free all the slots */
3338
4
    SFTKSlot *slot = NULL;
3339
4
    CK_SLOT_ID slotID;
3340
4
    int i;
3341
3342
4
    if (nscSlotList[moduleIndex]) {
3343
4
        CK_ULONG tmpSlotCount = nscSlotCount[moduleIndex];
3344
4
        CK_SLOT_ID_PTR tmpSlotList = nscSlotList[moduleIndex];
3345
4
        PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex];
3346
3347
        /* first close all the session */
3348
12
        for (i = 0; i < (int)tmpSlotCount; i++) {
3349
8
            slotID = tmpSlotList[i];
3350
8
            (void)NSC_CloseAllSessions(slotID);
3351
8
        }
3352
3353
        /* now clear out the statics */
3354
4
        nscSlotList[moduleIndex] = NULL;
3355
4
        nscSlotCount[moduleIndex] = 0;
3356
4
        nscSlotHashTable[moduleIndex] = NULL;
3357
4
        nscSlotListSize[moduleIndex] = 0;
3358
3359
12
        for (i = 0; i < (int)tmpSlotCount; i++) {
3360
8
            slotID = tmpSlotList[i];
3361
8
            slot = (SFTKSlot *)
3362
8
                PL_HashTableLookup(tmpSlotHashTable, (void *)(uintptr_t)slotID);
3363
8
            PORT_Assert(slot);
3364
8
            if (!slot)
3365
0
                continue;
3366
8
            SFTK_DestroySlotData(slot);
3367
8
            PL_HashTableRemove(tmpSlotHashTable, (void *)(uintptr_t)slotID);
3368
8
        }
3369
4
        PORT_Free(tmpSlotList);
3370
4
        PL_HashTableDestroy(tmpSlotHashTable);
3371
4
    }
3372
4
}
3373
3374
static void
3375
sftk_closePeer(PRBool isFIPS)
3376
0
{
3377
0
    CK_SLOT_ID slotID = isFIPS ? PRIVATE_KEY_SLOT_ID : FIPS_SLOT_ID;
3378
0
    SFTKSlot *slot;
3379
0
    unsigned int moduleIndex = isFIPS ? NSC_NON_FIPS_MODULE : NSC_FIPS_MODULE;
3380
0
    PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex];
3381
3382
0
    slot = (SFTKSlot *)PL_HashTableLookup(tmpSlotHashTable, (void *)(uintptr_t)slotID);
3383
0
    if (slot == NULL) {
3384
0
        return;
3385
0
    }
3386
0
    sftk_DBShutdown(slot);
3387
0
    return;
3388
0
}
3389
3390
extern void sftk_PBELockInit(void);
3391
extern void sftk_PBELockShutdown(void);
3392
3393
/* Parse the library parameters from the first occurance in the following src.:
3394
 * 1. C_INITIALIZED_ARGS - lib params are included in LibraryParameters field
3395
 * 2. NSS_LIB_PARAMS - env. var. containing the lib. params.
3396
 * 3. NSS_LIB_PARAMS_FILE - env. var. pointion to a file with lib. params.
3397
 * 4. /etc/nss/params.config - default lib. param. file location [Linux only]
3398
 * 5. LIB_PARAM_DEFAULT - string ensureing the pressence at all times
3399
 *    "configdir='' certPrefix='' keyPrefix='' secmod='' flags=noCertDB,noModDB"
3400
 */
3401
static CK_RV
3402
sftk_getParameters(CK_C_INITIALIZE_ARGS *init_args, PRBool isFIPS,
3403
                   sftk_parameters *paramStrings)
3404
4
{
3405
4
    CK_RV crv;
3406
4
    char *libParams;
3407
4
    const char *filename;
3408
4
    PRFileDesc *file_dc;
3409
4
    PRBool free_mem = PR_FALSE;
3410
3411
4
    if (!init_args || !init_args->LibraryParameters) {
3412
        /* Library parameters were not provided via C_Initialize_args*/
3413
3414
        /* Enviromental value has precedence to configuration filename */
3415
0
        libParams = PR_GetEnvSecure("NSS_LIB_PARAMS");
3416
3417
0
        if (!libParams) {
3418
            /* Load from config filename or use default */
3419
0
            filename = PR_GetEnvSecure("NSS_LIB_PARAMS_FILE");
3420
0
#ifdef XP_UNIX
3421
            /* Use default configuration file for Linux only */
3422
0
            if (!filename)
3423
0
                filename = LIB_PARAM_DEFAULT_FILE_LOCATION;
3424
0
#endif
3425
0
            if (filename) {
3426
0
                file_dc = PR_OpenFile(filename, PR_RDONLY, 444);
3427
0
                if (file_dc) {
3428
                    /* file opened */
3429
0
                    PRInt32 len = PR_Available(file_dc);
3430
0
                    libParams = PORT_NewArray(char, len + 1);
3431
0
                    if (libParams) {
3432
                        /* memory allocated */
3433
0
                        if (PR_Read(file_dc, libParams, len) == -1) {
3434
0
                            PORT_Free(libParams);
3435
0
                            libParams = NULL;
3436
0
                        } else {
3437
0
                            free_mem = PR_TRUE;
3438
0
                            libParams[len] = '\0';
3439
0
                        }
3440
0
                    }
3441
3442
0
                    PR_Close(file_dc);
3443
0
                }
3444
0
            }
3445
0
        }
3446
3447
0
        if (libParams == NULL)
3448
0
            libParams = LIB_PARAM_DEFAULT;
3449
3450
4
    } else {
3451
        /* Use parameters provided with C_Initialize_args */
3452
4
        libParams = (char *)init_args->LibraryParameters;
3453
4
    }
3454
3455
4
    crv = sftk_parseParameters(libParams, paramStrings, isFIPS);
3456
4
    if (crv != CKR_OK) {
3457
0
        crv = CKR_ARGUMENTS_BAD;
3458
0
        goto loser;
3459
0
    }
3460
3461
4
    crv = CKR_OK;
3462
4
loser:
3463
4
    if (free_mem)
3464
0
        PORT_Free(libParams);
3465
3466
4
    return crv;
3467
4
}
3468
3469
/* NSC_Initialize initializes the Cryptoki library. */
3470
CK_RV
3471
nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS)
3472
4
{
3473
4
    CK_RV crv = CKR_OK;
3474
4
    SECStatus rv;
3475
4
    CK_C_INITIALIZE_ARGS *init_args = (CK_C_INITIALIZE_ARGS *)pReserved;
3476
4
    PRBool destroy_freelist_on_error = PR_TRUE;
3477
4
    int i;
3478
4
    unsigned int moduleIndex = isFIPS ? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE;
3479
3480
4
    if (isFIPS) {
3481
0
        loginWaitTime = PR_SecondsToInterval(1);
3482
0
    }
3483
3484
4
    ENABLE_FORK_CHECK();
3485
3486
4
    sftk_PBELockInit();
3487
3488
4
    rv = SECOID_Init();
3489
4
    if (rv != SECSuccess) {
3490
0
        crv = CKR_DEVICE_ERROR;
3491
0
        return crv;
3492
0
    }
3493
3494
4
    rv = BL_Init(); /* initialize freebl engine */
3495
4
    if (rv != SECSuccess) {
3496
0
        crv = CKR_DEVICE_ERROR;
3497
0
        return crv;
3498
0
    }
3499
3500
4
    rv = RNG_RNGInit(); /* initialize random number generator */
3501
4
    if (rv != SECSuccess) {
3502
0
        crv = CKR_DEVICE_ERROR;
3503
0
        return crv;
3504
0
    }
3505
3506
    /* NOTE:
3507
     * we should be getting out mutexes from this list, not statically binding
3508
     * them from NSPR. This should happen before we allow the internal to split
3509
     * off from the rest on NSS.
3510
     */
3511
3512
    /* initialize the key and cert db's */
3513
4
    if (init_args && (!(init_args->flags & CKF_OS_LOCKING_OK))) {
3514
0
        if (init_args->CreateMutex && init_args->DestroyMutex &&
3515
0
            init_args->LockMutex && init_args->UnlockMutex) {
3516
            /* softoken always uses NSPR (ie. OS locking), and doesn't know how
3517
             * to use the lock functions provided by the application.
3518
             */
3519
0
            crv = CKR_CANT_LOCK;
3520
0
            return crv;
3521
0
        }
3522
0
        if (init_args->CreateMutex || init_args->DestroyMutex ||
3523
0
            init_args->LockMutex || init_args->UnlockMutex) {
3524
            /* only some of the lock functions were provided by the
3525
             * application. This is invalid per PKCS#11 spec.
3526
             */
3527
0
            crv = CKR_ARGUMENTS_BAD;
3528
0
            return crv;
3529
0
        }
3530
0
    }
3531
3532
4
    sftk_parameters paramStrings;
3533
3534
    /* load and parse the library parameters */
3535
4
    crv = sftk_getParameters(init_args, isFIPS, &paramStrings);
3536
4
    if (crv != CKR_OK) {
3537
0
        goto loser;
3538
0
    }
3539
3540
4
    crv = sftk_configure(paramStrings.man, paramStrings.libdes);
3541
4
    if (crv != CKR_OK) {
3542
0
        goto loser;
3543
0
    }
3544
3545
    /* if we have a peer already open, have him close his DB's so we
3546
     * don't clobber each other. */
3547
4
    if ((isFIPS && nsc_init) || (!isFIPS && nsf_init)) {
3548
0
        sftk_closePeer(isFIPS);
3549
0
        if (sftk_audit_enabled) {
3550
0
            if (isFIPS && nsc_init) {
3551
0
                sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE,
3552
0
                                     "enabled FIPS mode");
3553
0
            } else {
3554
0
                sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE,
3555
0
                                     "disabled FIPS mode");
3556
0
            }
3557
0
        }
3558
        /* if we have a peer open, we don't want to destroy the freelist
3559
         * from under the peer if we fail, the free list will be
3560
         * destroyed in that case when the C_Finalize is called for
3561
         * the peer */
3562
0
        destroy_freelist_on_error = PR_FALSE;
3563
0
    }
3564
    /* allow us to create objects in SFTK_SlotInit */
3565
4
    sftk_InitFreeLists();
3566
3567
12
    for (i = 0; i < paramStrings.token_count; i++) {
3568
8
        crv = SFTK_SlotInit(paramStrings.configdir,
3569
8
                            paramStrings.updatedir, paramStrings.updateID,
3570
8
                            &paramStrings.tokens[i], moduleIndex);
3571
8
        if (crv != CKR_OK) {
3572
0
            nscFreeAllSlots(moduleIndex);
3573
0
            break;
3574
0
        }
3575
8
    }
3576
3577
4
loser:
3578
3579
4
    sftk_freeParams(&paramStrings);
3580
3581
4
    if (destroy_freelist_on_error && (CKR_OK != crv)) {
3582
        /* idempotent. If the list are already freed, this is a noop */
3583
0
        sftk_CleanupFreeLists();
3584
0
    }
3585
3586
#ifndef NO_FORK_CHECK
3587
    if (CKR_OK == crv) {
3588
#if defined(CHECK_FORK_MIXED)
3589
        /* Before Solaris 10, fork handlers are not unregistered at dlclose()
3590
         * time. So, we only use pthread_atfork on Solaris 10 and later. For
3591
         * earlier versions, we use PID checks.
3592
         */
3593
        char buf[200];
3594
        int major = 0, minor = 0;
3595
3596
        long rv = sysinfo(SI_RELEASE, buf, sizeof(buf));
3597
        if (rv > 0 && rv < sizeof(buf)) {
3598
            if (2 == sscanf(buf, "%d.%d", &major, &minor)) {
3599
                /* Are we on Solaris 10 or greater ? */
3600
                if (major > 5 || (5 == major && minor >= 10)) {
3601
                    /* we are safe to use pthread_atfork */
3602
                    usePthread_atfork = PR_TRUE;
3603
                }
3604
            }
3605
        }
3606
        if (usePthread_atfork) {
3607
            pthread_atfork(NULL, NULL, ForkedChild);
3608
        } else {
3609
            myPid = getpid();
3610
        }
3611
3612
#elif defined(CHECK_FORK_PTHREAD)
3613
        pthread_atfork(NULL, NULL, ForkedChild);
3614
#elif defined(CHECK_FORK_GETPID)
3615
        myPid = getpid();
3616
#else
3617
#error Incorrect fork check method.
3618
#endif
3619
    }
3620
#endif
3621
4
    return crv;
3622
4
}
3623
3624
CK_RV
3625
NSC_Initialize(CK_VOID_PTR pReserved)
3626
4
{
3627
4
    CK_RV crv;
3628
3629
4
    sftk_ForkReset(pReserved, &crv);
3630
3631
4
    if (nsc_init) {
3632
0
        return CKR_CRYPTOKI_ALREADY_INITIALIZED;
3633
0
    }
3634
4
    crv = nsc_CommonInitialize(pReserved, PR_FALSE);
3635
4
    nsc_init = (PRBool)(crv == CKR_OK);
3636
4
    return crv;
3637
4
}
3638
3639
/* NSC_Finalize indicates that an application is done with the
3640
 * Cryptoki library.*/
3641
CK_RV
3642
nsc_CommonFinalize(CK_VOID_PTR pReserved, PRBool isFIPS)
3643
4
{
3644
    /* propagate the fork status to freebl and util */
3645
4
    BL_SetForkState(parentForkedAfterC_Initialize);
3646
4
    UTIL_SetForkState(parentForkedAfterC_Initialize);
3647
3648
4
    nscFreeAllSlots(isFIPS ? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE);
3649
3650
    /* don't muck with the globals if our peer is still initialized */
3651
4
    if (isFIPS && nsc_init) {
3652
0
        return CKR_OK;
3653
0
    }
3654
4
    if (!isFIPS && nsf_init) {
3655
0
        return CKR_OK;
3656
0
    }
3657
3658
4
    sftk_CleanupFreeLists();
3659
4
    sftkdb_Shutdown();
3660
3661
    /* This function does not discard all our previously aquired entropy. */
3662
4
    RNG_RNGShutdown();
3663
3664
    /* tell freeBL to clean up after itself */
3665
4
    BL_Cleanup();
3666
3667
    /* reset fork status in freebl. We must do this before BL_Unload so that
3668
     * this call doesn't force freebl to be reloaded. */
3669
4
    BL_SetForkState(PR_FALSE);
3670
3671
#ifndef NSS_STATIC_SOFTOKEN
3672
    /* unload freeBL shared library from memory. This may only decrement the
3673
     * OS refcount if it's been loaded multiple times, eg. by libssl */
3674
    BL_Unload();
3675
#endif
3676
3677
    /* clean up the default OID table */
3678
4
    SECOID_Shutdown();
3679
3680
4
    sftk_PBELockShutdown();
3681
3682
    /* reset fork status in util */
3683
4
    UTIL_SetForkState(PR_FALSE);
3684
3685
4
    nsc_init = PR_FALSE;
3686
3687
#ifndef NO_FORK_CHECK
3688
#ifdef CHECK_FORK_MIXED
3689
    if (!usePthread_atfork) {
3690
        myPid = 0; /* allow CHECK_FORK in the next softoken initialization to
3691
                    * succeed */
3692
    } else {
3693
        forked = PR_FALSE; /* allow reinitialization */
3694
    }
3695
#elif defined(CHECK_FORK_GETPID)
3696
    myPid = 0; /* allow reinitialization */
3697
#elif defined(CHECK_FORK_PTHREAD)
3698
    forked = PR_FALSE; /* allow reinitialization */
3699
#endif
3700
#endif
3701
4
    return CKR_OK;
3702
4
}
3703
3704
/* Hard-reset the entire softoken PKCS#11 module if the parent process forked
3705
 * while it was initialized. */
3706
PRBool
3707
sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV *crv)
3708
8
{
3709
#ifndef NO_FORK_CHECK
3710
    if (PARENT_FORKED()) {
3711
        parentForkedAfterC_Initialize = PR_TRUE;
3712
        if (nsc_init) {
3713
            /* finalize non-FIPS token */
3714
            *crv = nsc_CommonFinalize(pReserved, PR_FALSE);
3715
            PORT_Assert(CKR_OK == *crv);
3716
            nsc_init = (PRBool) !(*crv == CKR_OK);
3717
        }
3718
        if (nsf_init) {
3719
            /* finalize FIPS token */
3720
            *crv = nsc_CommonFinalize(pReserved, PR_TRUE);
3721
            PORT_Assert(CKR_OK == *crv);
3722
            nsf_init = (PRBool) !(*crv == CKR_OK);
3723
        }
3724
        parentForkedAfterC_Initialize = PR_FALSE;
3725
        return PR_TRUE;
3726
    }
3727
#endif
3728
8
    return PR_FALSE;
3729
8
}
3730
3731
/* NSC_Finalize indicates that an application is done with the
3732
 * Cryptoki library.*/
3733
CK_RV
3734
NSC_Finalize(CK_VOID_PTR pReserved)
3735
4
{
3736
4
    CK_RV crv;
3737
3738
    /* reset entire PKCS#11 module upon fork */
3739
4
    if (sftk_ForkReset(pReserved, &crv)) {
3740
0
        return crv;
3741
0
    }
3742
3743
4
    if (!nsc_init) {
3744
0
        return CKR_OK;
3745
0
    }
3746
3747
4
    crv = nsc_CommonFinalize(pReserved, PR_FALSE);
3748
3749
4
    nsc_init = (PRBool) !(crv == CKR_OK);
3750
3751
4
    return crv;
3752
4
}
3753
3754
extern const char __nss_softokn_version[];
3755
3756
/* NSC_GetInfo returns general information about Cryptoki. */
3757
CK_RV
3758
NSC_GetInfo(CK_INFO_PTR pInfo)
3759
4
{
3760
4
#define NSS_VERSION_VARIABLE __nss_softokn_version
3761
4
#include "verref.h"
3762
3763
4
    CHECK_FORK();
3764
3765
4
    pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
3766
4
    pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
3767
4
    PORT_Memcpy(pInfo->manufacturerID, manufacturerID, 32);
3768
4
    pInfo->libraryVersion.major = SOFTOKEN_VMAJOR;
3769
4
    pInfo->libraryVersion.minor = SOFTOKEN_VMINOR;
3770
4
    PORT_Memcpy(pInfo->libraryDescription, libraryDescription, 32);
3771
4
    pInfo->flags = 0;
3772
4
    return CKR_OK;
3773
4
}
3774
3775
/* NSC_GetInfo returns general information about Cryptoki. */
3776
CK_RV
3777
NSC_GetInfoV2(CK_INFO_PTR pInfo)
3778
0
{
3779
0
    CHECK_FORK();
3780
3781
0
    pInfo->cryptokiVersion.major = 2;
3782
0
    pInfo->cryptokiVersion.minor = 40;
3783
0
    PORT_Memcpy(pInfo->manufacturerID, manufacturerID, 32);
3784
0
    pInfo->libraryVersion.major = SOFTOKEN_VMAJOR;
3785
0
    pInfo->libraryVersion.minor = SOFTOKEN_VMINOR;
3786
0
    PORT_Memcpy(pInfo->libraryDescription, libraryDescription, 32);
3787
0
    pInfo->flags = 0;
3788
0
    return CKR_OK;
3789
0
}
3790
3791
/* NSC_GetSlotList obtains a list of slots in the system. */
3792
CK_RV
3793
nsc_CommonGetSlotList(CK_BBOOL tokenPresent,
3794
                      CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount,
3795
                      unsigned int moduleIndex)
3796
8
{
3797
8
    *pulCount = nscSlotCount[moduleIndex];
3798
8
    if (pSlotList != NULL) {
3799
4
        PORT_Memcpy(pSlotList, nscSlotList[moduleIndex],
3800
4
                    nscSlotCount[moduleIndex] * sizeof(CK_SLOT_ID));
3801
4
    }
3802
8
    return CKR_OK;
3803
8
}
3804
3805
/* NSC_GetSlotList obtains a list of slots in the system. */
3806
CK_RV
3807
NSC_GetSlotList(CK_BBOOL tokenPresent,
3808
                CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount)
3809
8
{
3810
8
    CHECK_FORK();
3811
8
    return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount,
3812
8
                                 NSC_NON_FIPS_MODULE);
3813
8
}
3814
3815
/* NSC_GetSlotInfo obtains information about a particular slot in the system. */
3816
CK_RV
3817
NSC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo)
3818
8
{
3819
8
    SFTKSlot *slot = sftk_SlotFromID(slotID, PR_TRUE);
3820
3821
8
    CHECK_FORK();
3822
3823
8
    if (slot == NULL)
3824
0
        return CKR_SLOT_ID_INVALID;
3825
3826
8
    PORT_Memcpy(pInfo->manufacturerID, manufacturerID,
3827
8
                sizeof(pInfo->manufacturerID));
3828
8
    PORT_Memcpy(pInfo->slotDescription, slot->slotDescription,
3829
8
                sizeof(pInfo->slotDescription));
3830
8
    pInfo->flags = (slot->present) ? CKF_TOKEN_PRESENT : 0;
3831
3832
    /* all user defined slots are defined as removable */
3833
8
    if (slotID >= SFTK_MIN_USER_SLOT_ID) {
3834
0
        pInfo->flags |= CKF_REMOVABLE_DEVICE;
3835
8
    } else {
3836
        /* In the case where we are doing a merge update, we need
3837
         * the DB slot to be removable so the token name can change
3838
         * appropriately. */
3839
8
        SFTKDBHandle *handle = sftk_getKeyDB(slot);
3840
8
        if (handle) {
3841
0
            if (sftkdb_InUpdateMerge(handle)) {
3842
0
                pInfo->flags |= CKF_REMOVABLE_DEVICE;
3843
0
            }
3844
0
            sftk_freeDB(handle);
3845
0
        }
3846
8
    }
3847
3848
    /* If there is no key database, this is for example the case when NSS was
3849
     * initialized with NSS_NoDbInit(), then there won't be any point in
3850
     * requesting a PIN. Set the CKF_USER_PIN_INITIALIZED bit so that
3851
     * PK11_NeedUserInit() doesn't indicate that a PIN is needed.
3852
     */
3853
8
    if (slot->keyDB == NULL) {
3854
8
        pInfo->flags |= CKF_USER_PIN_INITIALIZED;
3855
8
    }
3856
3857
    /* ok we really should read it out of the keydb file. */
3858
    /* pInfo->hardwareVersion.major = NSSLOWKEY_DB_FILE_VERSION; */
3859
8
    pInfo->hardwareVersion.major = SOFTOKEN_VMAJOR;
3860
8
    pInfo->hardwareVersion.minor = SOFTOKEN_VMINOR;
3861
8
    pInfo->firmwareVersion.major = SOFTOKEN_VPATCH;
3862
8
    pInfo->firmwareVersion.minor = SOFTOKEN_VBUILD;
3863
8
    return CKR_OK;
3864
8
}
3865
3866
/*
3867
 * check the current state of the 'needLogin' flag in case the database has
3868
 * been changed underneath us.
3869
 */
3870
static PRBool
3871
sftk_checkNeedLogin(SFTKSlot *slot, SFTKDBHandle *keyHandle)
3872
0
{
3873
0
    PRBool needLogin;
3874
0
    if (sftkdb_PWCached(keyHandle) == SECSuccess) {
3875
0
        PZ_Lock(slot->slotLock);
3876
0
        needLogin = slot->needLogin;
3877
0
        PZ_Unlock(slot->slotLock);
3878
0
    } else {
3879
0
        needLogin = (PRBool)!sftk_hasNullPassword(slot, keyHandle);
3880
0
        PZ_Lock(slot->slotLock);
3881
0
        slot->needLogin = needLogin;
3882
0
        PZ_Unlock(slot->slotLock);
3883
0
    }
3884
0
    return needLogin;
3885
0
}
3886
3887
static PRBool
3888
sftk_isBlank(const char *s, int len)
3889
0
{
3890
0
    int i;
3891
0
    for (i = 0; i < len; i++) {
3892
0
        if (s[i] != ' ') {
3893
0
            return PR_FALSE;
3894
0
        }
3895
0
    }
3896
0
    return PR_TRUE;
3897
0
}
3898
3899
/* NSC_GetTokenInfo obtains information about a particular token in
3900
 * the system. */
3901
CK_RV
3902
NSC_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo)
3903
8
{
3904
8
    SFTKSlot *slot;
3905
8
    SFTKDBHandle *handle;
3906
3907
8
    CHECK_FORK();
3908
3909
8
    if (!nsc_init && !nsf_init)
3910
0
        return CKR_CRYPTOKI_NOT_INITIALIZED;
3911
8
    slot = sftk_SlotFromID(slotID, PR_FALSE);
3912
8
    if (slot == NULL)
3913
0
        return CKR_SLOT_ID_INVALID;
3914
3915
8
    PORT_Memcpy(pInfo->manufacturerID, manufacturerID, 32);
3916
8
    PORT_Memcpy(pInfo->model, "NSS 3           ", 16);
3917
8
    PORT_Memcpy(pInfo->serialNumber, "0000000000000000", 16);
3918
8
    PORT_Memcpy(pInfo->utcTime, "0000000000000000", 16);
3919
8
    pInfo->ulMaxSessionCount = 0;   /* arbitrarily large */
3920
8
    pInfo->ulMaxRwSessionCount = 0; /* arbitarily large */
3921
8
    PZ_Lock(slot->slotLock);        /* Protect sessionCount / rwSessioncount */
3922
8
    pInfo->ulSessionCount = slot->sessionCount;
3923
8
    pInfo->ulRwSessionCount = slot->rwSessionCount;
3924
8
    PZ_Unlock(slot->slotLock); /* Unlock before sftk_getKeyDB */
3925
8
    pInfo->firmwareVersion.major = 0;
3926
8
    pInfo->firmwareVersion.minor = 0;
3927
8
    PORT_Memcpy(pInfo->label, slot->tokDescription, sizeof(pInfo->label));
3928
8
    handle = sftk_getKeyDB(slot);
3929
8
    pInfo->flags = CKF_RNG | CKF_DUAL_CRYPTO_OPERATIONS;
3930
8
    if (handle == NULL) {
3931
8
        pInfo->flags |= CKF_WRITE_PROTECTED;
3932
8
        pInfo->ulMaxPinLen = 0;
3933
8
        pInfo->ulMinPinLen = 0;
3934
8
        pInfo->ulTotalPublicMemory = 0;
3935
8
        pInfo->ulFreePublicMemory = 0;
3936
8
        pInfo->ulTotalPrivateMemory = 0;
3937
8
        pInfo->ulFreePrivateMemory = 0;
3938
8
        pInfo->hardwareVersion.major = 4;
3939
8
        pInfo->hardwareVersion.minor = 0;
3940
8
    } else {
3941
        /*
3942
         * we have three possible states which we may be in:
3943
         *   (1) No DB password has been initialized. This also means we
3944
         *   have no keys in the key db.
3945
         *   (2) Password initialized to NULL. This means we have keys, but
3946
         *   the user has chosen not use a password.
3947
         *   (3) Finally we have an initialized password whicn is not NULL, and
3948
         *   we will need to prompt for it.
3949
         */
3950
0
        if (sftkdb_HasPasswordSet(handle) == SECFailure) {
3951
0
            pInfo->flags |= CKF_LOGIN_REQUIRED;
3952
0
        } else if (!sftk_checkNeedLogin(slot, handle)) {
3953
0
            pInfo->flags |= CKF_USER_PIN_INITIALIZED;
3954
0
        } else {
3955
0
            pInfo->flags |= CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED;
3956
            /*
3957
             * if we are doing a merge style update, and we need to get the password
3958
             * of our source database (the database we are updating from), make sure we
3959
             * return a token name that will match the database we are prompting for.
3960
             */
3961
0
            if (sftkdb_NeedUpdateDBPassword(handle)) {
3962
                /* if we have an update tok description, use it. otherwise
3963
                 * use the updateID for this database */
3964
0
                if (!sftk_isBlank(slot->updateTokDescription,
3965
0
                                  sizeof(pInfo->label))) {
3966
0
                    PORT_Memcpy(pInfo->label, slot->updateTokDescription,
3967
0
                                sizeof(pInfo->label));
3968
0
                } else {
3969
                    /* build from updateID */
3970
0
                    const char *updateID = sftkdb_GetUpdateID(handle);
3971
0
                    if (updateID) {
3972
0
                        sftk_setStringName(updateID, (char *)pInfo->label,
3973
0
                                           sizeof(pInfo->label), PR_FALSE);
3974
0
                    }
3975
0
                }
3976
0
            }
3977
0
        }
3978
0
        pInfo->ulMaxPinLen = SFTK_MAX_PIN;
3979
0
        pInfo->ulMinPinLen = (CK_ULONG)slot->minimumPinLen;
3980
0
        pInfo->ulTotalPublicMemory = 1;
3981
0
        pInfo->ulFreePublicMemory = 1;
3982
0
        pInfo->ulTotalPrivateMemory = 1;
3983
0
        pInfo->ulFreePrivateMemory = 1;
3984
#ifdef SHDB_FIXME
3985
        pInfo->hardwareVersion.major = CERT_DB_FILE_VERSION;
3986
        pInfo->hardwareVersion.minor = handle->version;
3987
#else
3988
0
        pInfo->hardwareVersion.major = 0;
3989
0
        pInfo->hardwareVersion.minor = 0;
3990
0
#endif
3991
0
        sftk_freeDB(handle);
3992
0
    }
3993
    /*
3994
     * CKF_LOGIN_REQUIRED CKF_USER_PIN_INITIALIZED  how CKF_TOKEN_INITIALIZED
3995
     *                                              should be set
3996
     *         0                   0                           1
3997
     *         1                   0                           0
3998
     *         0                   1                           1
3999
     *         1                   1                           1
4000
     */
4001
8
    if (!(pInfo->flags & CKF_LOGIN_REQUIRED) ||
4002
8
        (pInfo->flags & CKF_USER_PIN_INITIALIZED)) {
4003
8
        pInfo->flags |= CKF_TOKEN_INITIALIZED;
4004
8
    }
4005
8
    return CKR_OK;
4006
8
}
4007
4008
/* NSC_GetMechanismList obtains a list of mechanism types
4009
 * supported by a token. */
4010
CK_RV
4011
NSC_GetMechanismList(CK_SLOT_ID slotID,
4012
                     CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount)
4013
16
{
4014
16
    CK_ULONG i;
4015
4016
16
    CHECK_FORK();
4017
4018
16
    switch (slotID) {
4019
        /* default: */
4020
8
        case NETSCAPE_SLOT_ID:
4021
8
            *pulCount = mechanismCount;
4022
8
            if (pMechanismList != NULL) {
4023
940
                for (i = 0; i < mechanismCount; i++) {
4024
936
                    pMechanismList[i] = mechanisms[i].type;
4025
936
                }
4026
4
            }
4027
8
            break;
4028
8
        default:
4029
8
            *pulCount = 0;
4030
1.88k
            for (i = 0; i < mechanismCount; i++) {
4031
1.87k
                if (mechanisms[i].privkey) {
4032
1.44k
                    (*pulCount)++;
4033
1.44k
                    if (pMechanismList != NULL) {
4034
724
                        *pMechanismList++ = mechanisms[i].type;
4035
724
                    }
4036
1.44k
                }
4037
1.87k
            }
4038
8
            break;
4039
16
    }
4040
16
    return CKR_OK;
4041
16
}
4042
4043
/* NSC_GetMechanismInfo obtains information about a particular mechanism
4044
 * possibly supported by a token. */
4045
CK_RV
4046
NSC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
4047
                     CK_MECHANISM_INFO_PTR pInfo)
4048
126k
{
4049
126k
    PRBool isPrivateKey;
4050
126k
    CK_ULONG i;
4051
4052
126k
    CHECK_FORK();
4053
4054
126k
    switch (slotID) {
4055
116k
        case NETSCAPE_SLOT_ID:
4056
116k
            isPrivateKey = PR_FALSE;
4057
116k
            break;
4058
10.1k
        default:
4059
10.1k
            isPrivateKey = PR_TRUE;
4060
10.1k
            break;
4061
126k
    }
4062
6.46M
    for (i = 0; i < mechanismCount; i++) {
4063
6.46M
        if (type == mechanisms[i].type) {
4064
126k
            if (isPrivateKey && !mechanisms[i].privkey) {
4065
0
                return CKR_MECHANISM_INVALID;
4066
0
            }
4067
126k
            PORT_Memcpy(pInfo, &mechanisms[i].info, sizeof(CK_MECHANISM_INFO));
4068
126k
            return CKR_OK;
4069
126k
        }
4070
6.46M
    }
4071
0
    return CKR_MECHANISM_INVALID;
4072
126k
}
4073
4074
/*
4075
 * If we are using the V2 interface, strip out the message flags
4076
 */
4077
0
#define SFTK_MESSAGE_FLAGS (CKF_MESSAGE_ENCRYPT | CKF_MESSAGE_DECRYPT | CKF_MESSAGE_SIGN | CKF_MESSAGE_VERIFY)
4078
CK_RV
4079
NSC_GetMechanismInfoV2(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
4080
                       CK_MECHANISM_INFO_PTR pInfo)
4081
0
{
4082
0
    CK_RV crv;
4083
0
    crv = NSC_GetMechanismInfo(slotID, type, pInfo);
4084
0
    if (crv == CKR_OK) {
4085
0
        pInfo->flags = pInfo->flags & ~SFTK_MESSAGE_FLAGS;
4086
0
    }
4087
0
    return crv;
4088
0
}
4089
4090
CK_RV
4091
sftk_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op)
4092
288k
{
4093
288k
    CK_ULONG i;
4094
288k
    CK_FLAGS flags = sftk_AttributeToFlags(op);
4095
4096
288k
    if (flags == 0) {
4097
0
        return CKR_ARGUMENTS_BAD;
4098
0
    }
4099
16.1M
    for (i = 0; i < mechanismCount; i++) {
4100
16.1M
        if (type == mechanisms[i].type) {
4101
288k
            return (flags & mechanisms[i].info.flags) ? CKR_OK
4102
288k
                                                      : CKR_MECHANISM_INVALID;
4103
288k
        }
4104
16.1M
    }
4105
5
    return CKR_MECHANISM_INVALID;
4106
288k
}
4107
4108
/* NSC_InitToken initializes a token. */
4109
CK_RV
4110
NSC_InitToken(CK_SLOT_ID slotID, CK_CHAR_PTR pPin,
4111
              CK_ULONG ulPinLen, CK_CHAR_PTR pLabel)
4112
0
{
4113
0
    SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE);
4114
0
    SFTKDBHandle *handle;
4115
0
    SECStatus rv;
4116
0
    unsigned int i;
4117
0
    SFTKObject *object;
4118
4119
0
    CHECK_FORK();
4120
4121
0
    if (slot == NULL)
4122
0
        return CKR_SLOT_ID_INVALID;
4123
4124
    /* don't initialize the database if we aren't talking to a token
4125
     * that uses the key database.
4126
     */
4127
0
    if (slotID == NETSCAPE_SLOT_ID) {
4128
0
        return CKR_TOKEN_WRITE_PROTECTED;
4129
0
    }
4130
4131
    /* first, delete all our loaded key and cert objects from our
4132
     * internal list. */
4133
0
    PZ_Lock(slot->objectLock);
4134
0
    for (i = 0; i < slot->sessObjHashSize; i++) {
4135
0
        do {
4136
0
            object = slot->sessObjHashTable[i];
4137
            /* hand deque */
4138
            /* this duplicates function of NSC_close session functions, but
4139
             * because we know that we are freeing all the sessions, we can
4140
             * do more efficient processing */
4141
0
            if (object) {
4142
0
                slot->sessObjHashTable[i] = object->next;
4143
4144
0
                if (object->next)
4145
0
                    object->next->prev = NULL;
4146
0
                object->next = object->prev = NULL;
4147
0
            }
4148
0
            if (object)
4149
0
                sftk_FreeObject(object);
4150
0
        } while (object != NULL);
4151
0
    }
4152
0
    slot->DB_loaded = PR_FALSE;
4153
0
    PZ_Unlock(slot->objectLock);
4154
4155
    /* then clear out the key database */
4156
0
    handle = sftk_getKeyDB(slot);
4157
0
    if (handle == NULL) {
4158
0
        return CKR_TOKEN_WRITE_PROTECTED;
4159
0
    }
4160
4161
0
    rv = sftkdb_ResetKeyDB(handle);
4162
    /* clear the password */
4163
0
    sftkdb_ClearPassword(handle);
4164
    /* update slot->needLogin (should be true now since no password is set) */
4165
0
    sftk_checkNeedLogin(slot, handle);
4166
0
    sftk_freeDB(handle);
4167
0
    if (rv != SECSuccess) {
4168
0
        return CKR_DEVICE_ERROR;
4169
0
    }
4170
4171
0
    return CKR_OK;
4172
0
}
4173
4174
/* NSC_InitPIN initializes the normal user's PIN. */
4175
CK_RV
4176
NSC_InitPIN(CK_SESSION_HANDLE hSession,
4177
            CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
4178
0
{
4179
0
    SFTKSession *sp = NULL;
4180
0
    SFTKSlot *slot;
4181
0
    SFTKDBHandle *handle = NULL;
4182
0
    char newPinStr[SFTK_MAX_PIN + 1];
4183
0
    SECStatus rv;
4184
0
    CK_RV crv = CKR_SESSION_HANDLE_INVALID;
4185
0
    PRBool tokenRemoved = PR_FALSE;
4186
4187
0
    CHECK_FORK();
4188
4189
0
    sp = sftk_SessionFromHandle(hSession);
4190
0
    if (sp == NULL) {
4191
0
        goto loser;
4192
0
    }
4193
4194
0
    slot = sftk_SlotFromSession(sp);
4195
0
    if (slot == NULL) {
4196
0
        goto loser;
4197
0
    }
4198
4199
0
    handle = sftk_getKeyDB(slot);
4200
0
    if (handle == NULL) {
4201
0
        crv = CKR_PIN_LEN_RANGE;
4202
0
        goto loser;
4203
0
    }
4204
4205
0
    if (sp->info.state != CKS_RW_SO_FUNCTIONS) {
4206
0
        crv = CKR_USER_NOT_LOGGED_IN;
4207
0
        goto loser;
4208
0
    }
4209
4210
0
    sftk_FreeSession(sp);
4211
0
    sp = NULL;
4212
4213
    /* make sure the pins aren't too long */
4214
0
    if (ulPinLen > SFTK_MAX_PIN) {
4215
0
        crv = CKR_PIN_LEN_RANGE;
4216
0
        goto loser;
4217
0
    }
4218
0
    if (ulPinLen < (CK_ULONG)slot->minimumPinLen) {
4219
0
        crv = CKR_PIN_LEN_RANGE;
4220
0
        goto loser;
4221
0
    }
4222
4223
0
    if (sftkdb_HasPasswordSet(handle) != SECFailure) {
4224
0
        crv = CKR_DEVICE_ERROR;
4225
0
        goto loser;
4226
0
    }
4227
4228
    /* convert to null terminated string */
4229
0
    PORT_Memcpy(newPinStr, pPin, ulPinLen);
4230
0
    newPinStr[ulPinLen] = 0;
4231
4232
    /* build the hashed pins which we pass around */
4233
4234
    /* change the data base */
4235
0
    rv = sftkdb_ChangePassword(handle, NULL, newPinStr, &tokenRemoved);
4236
0
    if (tokenRemoved) {
4237
0
        sftk_CloseAllSessions(slot, PR_FALSE);
4238
0
    }
4239
0
    PORT_Memset(newPinStr, 0, ulPinLen);
4240
0
    sftk_freeDB(handle);
4241
0
    handle = NULL;
4242
4243
    /* Now update our local copy of the pin */
4244
0
    if (rv == SECSuccess) {
4245
0
        if (ulPinLen == 0) {
4246
0
            PZ_Lock(slot->slotLock);
4247
0
            slot->needLogin = PR_FALSE;
4248
0
            PZ_Unlock(slot->slotLock);
4249
0
        }
4250
        /* database has been initialized, now force min password in FIPS
4251
         * mode. NOTE: if we are in level1, we may not have a password, but
4252
         * forcing it now will prevent an insufficient password from being set.
4253
         */
4254
0
        if ((sftk_GetModuleIndex(slot->slotID) == NSC_FIPS_MODULE) &&
4255
0
            (slot->minimumPinLen < FIPS_MIN_PIN)) {
4256
0
            slot->minimumPinLen = FIPS_MIN_PIN;
4257
0
        }
4258
0
        return CKR_OK;
4259
0
    }
4260
0
    crv = CKR_PIN_INCORRECT;
4261
4262
0
loser:
4263
0
    if (sp) {
4264
0
        sftk_FreeSession(sp);
4265
0
    }
4266
0
    if (handle) {
4267
0
        sftk_freeDB(handle);
4268
0
    }
4269
0
    return crv;
4270
0
}
4271
4272
/* NSC_SetPIN modifies the PIN of user that is currently logged in. */
4273
/* NOTE: This is only valid for the PRIVATE_KEY_SLOT */
4274
CK_RV
4275
NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin,
4276
           CK_ULONG ulOldLen, CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen)
4277
0
{
4278
0
    SFTKSession *sp = NULL;
4279
0
    SFTKSlot *slot;
4280
0
    SFTKDBHandle *handle = NULL;
4281
0
    char newPinStr[SFTK_MAX_PIN + 1], oldPinStr[SFTK_MAX_PIN + 1];
4282
0
    SECStatus rv;
4283
0
    CK_RV crv = CKR_SESSION_HANDLE_INVALID;
4284
0
    PRBool needLogin;
4285
0
    PRBool tokenRemoved = PR_FALSE;
4286
4287
0
    CHECK_FORK();
4288
4289
0
    sp = sftk_SessionFromHandle(hSession);
4290
0
    if (sp == NULL) {
4291
0
        goto loser;
4292
0
    }
4293
4294
0
    slot = sftk_SlotFromSession(sp);
4295
0
    if (!slot) {
4296
0
        goto loser;
4297
0
    }
4298
4299
0
    handle = sftk_getKeyDB(slot);
4300
0
    if (handle == NULL) {
4301
0
        sftk_FreeSession(sp);
4302
0
        return CKR_PIN_LEN_RANGE; /* XXX FIXME wrong return value */
4303
0
    }
4304
4305
0
    PZ_Lock(slot->slotLock);
4306
0
    needLogin = slot->needLogin;
4307
0
    PZ_Unlock(slot->slotLock);
4308
0
    if (needLogin && sp->info.state != CKS_RW_USER_FUNCTIONS) {
4309
0
        crv = CKR_USER_NOT_LOGGED_IN;
4310
0
        goto loser;
4311
0
    }
4312
4313
0
    sftk_FreeSession(sp);
4314
0
    sp = NULL;
4315
4316
    /* make sure the pins aren't too long */
4317
0
    if ((ulNewLen > SFTK_MAX_PIN) || (ulOldLen > SFTK_MAX_PIN)) {
4318
0
        crv = CKR_PIN_LEN_RANGE;
4319
0
        goto loser;
4320
0
    }
4321
    /* check the length of new pin, unless both old and new passwords
4322
     * are empty */
4323
0
    if ((ulNewLen != 0 || ulOldLen != 0) &&
4324
0
        ulNewLen < (CK_ULONG)slot->minimumPinLen) {
4325
0
        crv = CKR_PIN_LEN_RANGE;
4326
0
        goto loser;
4327
0
    }
4328
4329
    /* convert to null terminated string */
4330
0
    PORT_Memcpy(newPinStr, pNewPin, ulNewLen);
4331
0
    newPinStr[ulNewLen] = 0;
4332
0
    PORT_Memcpy(oldPinStr, pOldPin, ulOldLen);
4333
0
    oldPinStr[ulOldLen] = 0;
4334
4335
    /* change the data base password */
4336
0
    PR_Lock(slot->pwCheckLock);
4337
0
    rv = sftkdb_ChangePassword(handle, oldPinStr, newPinStr, &tokenRemoved);
4338
0
    PORT_Memset(newPinStr, 0, ulNewLen);
4339
0
    PORT_Memset(oldPinStr, 0, ulOldLen);
4340
0
    if (tokenRemoved) {
4341
0
        sftk_CloseAllSessions(slot, PR_FALSE);
4342
0
    }
4343
0
    if ((rv != SECSuccess) && (sftk_isFIPS(slot->slotID))) {
4344
0
        PR_Sleep(loginWaitTime);
4345
0
    }
4346
0
    PR_Unlock(slot->pwCheckLock);
4347
4348
    /* Now update our local copy of the pin */
4349
0
    if (rv == SECSuccess) {
4350
0
        PZ_Lock(slot->slotLock);
4351
0
        slot->needLogin = (PRBool)(ulNewLen != 0);
4352
0
        slot->isLoggedIn = (PRBool)(sftkdb_PWCached(handle) == SECSuccess);
4353
0
        PZ_Unlock(slot->slotLock);
4354
        /* Reset login flags. */
4355
0
        if (ulNewLen == 0) {
4356
0
            PZ_Lock(slot->slotLock);
4357
0
            slot->isLoggedIn = PR_FALSE;
4358
0
            slot->ssoLoggedIn = PR_FALSE;
4359
0
            PZ_Unlock(slot->slotLock);
4360
4361
0
            tokenRemoved = PR_FALSE;
4362
0
            rv = sftkdb_CheckPasswordNull(handle, &tokenRemoved);
4363
0
            if (tokenRemoved) {
4364
0
                sftk_CloseAllSessions(slot, PR_FALSE);
4365
0
            }
4366
0
        }
4367
0
        sftk_update_all_states(slot);
4368
0
        sftk_freeDB(handle);
4369
0
        return CKR_OK;
4370
0
    }
4371
0
    crv = CKR_PIN_INCORRECT;
4372
0
loser:
4373
0
    if (sp) {
4374
0
        sftk_FreeSession(sp);
4375
0
    }
4376
0
    if (handle) {
4377
0
        sftk_freeDB(handle);
4378
0
    }
4379
0
    return crv;
4380
0
}
4381
4382
/* NSC_OpenSession opens a session between an application and a token. */
4383
CK_RV
4384
NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags,
4385
                CK_VOID_PTR pApplication, CK_NOTIFY Notify, CK_SESSION_HANDLE_PTR phSession)
4386
858k
{
4387
858k
    SFTKSlot *slot;
4388
858k
    CK_SESSION_HANDLE sessionID;
4389
858k
    SFTKSession *session;
4390
858k
    SFTKSession *sameID;
4391
4392
858k
    CHECK_FORK();
4393
4394
858k
    slot = sftk_SlotFromID(slotID, PR_FALSE);
4395
858k
    if (slot == NULL)
4396
0
        return CKR_SLOT_ID_INVALID;
4397
4398
    /* new session (we only have serial sessions) */
4399
858k
    session = sftk_NewSession(slotID, Notify, pApplication,
4400
858k
                              flags | CKF_SERIAL_SESSION);
4401
858k
    if (session == NULL)
4402
0
        return CKR_HOST_MEMORY;
4403
4404
858k
    if (slot->readOnly && (flags & CKF_RW_SESSION)) {
4405
        /* NETSCAPE_SLOT_ID is Read ONLY */
4406
0
        session->info.flags &= ~CKF_RW_SESSION;
4407
0
    }
4408
858k
    PZ_Lock(slot->slotLock);
4409
858k
    ++slot->sessionCount;
4410
858k
    PZ_Unlock(slot->slotLock);
4411
858k
    if (session->info.flags & CKF_RW_SESSION) {
4412
0
        (void)PR_ATOMIC_INCREMENT(&slot->rwSessionCount);
4413
0
    }
4414
4415
858k
    do {
4416
858k
        PZLock *lock;
4417
858k
        do {
4418
858k
            sessionID = (PR_ATOMIC_INCREMENT(&slot->sessionIDCount) & 0xffffff) | (slot->index << 24);
4419
858k
        } while (sessionID == CK_INVALID_HANDLE);
4420
858k
        lock = SFTK_SESSION_LOCK(slot, sessionID);
4421
858k
        PZ_Lock(lock);
4422
858k
        sftkqueue_find(sameID, sessionID, slot->head, slot->sessHashSize);
4423
858k
        if (sameID == NULL) {
4424
858k
            session->handle = sessionID;
4425
858k
            sftk_update_state(slot, session);
4426
858k
            sftkqueue_add(session, sessionID, slot->head, slot->sessHashSize);
4427
858k
        } else {
4428
0
            slot->sessionIDConflict++; /* for debugging */
4429
0
        }
4430
858k
        PZ_Unlock(lock);
4431
858k
    } while (sameID != NULL);
4432
4433
858k
    *phSession = sessionID;
4434
858k
    return CKR_OK;
4435
858k
}
4436
4437
/* NSC_CloseSession closes a session between an application and a token. */
4438
CK_RV
4439
NSC_CloseSession(CK_SESSION_HANDLE hSession)
4440
858k
{
4441
858k
    SFTKSlot *slot;
4442
858k
    SFTKSession *session;
4443
858k
    PRBool sessionFound;
4444
858k
    PZLock *lock;
4445
4446
858k
    CHECK_FORK();
4447
4448
858k
    session = sftk_SessionFromHandle(hSession);
4449
858k
    if (session == NULL)
4450
0
        return CKR_SESSION_HANDLE_INVALID;
4451
858k
    slot = sftk_SlotFromSession(session);
4452
858k
    sessionFound = PR_FALSE;
4453
4454
    /* lock */
4455
858k
    lock = SFTK_SESSION_LOCK(slot, hSession);
4456
858k
    PZ_Lock(lock);
4457
858k
    if (sftkqueue_is_queued(session, hSession, slot->head, slot->sessHashSize)) {
4458
858k
        sessionFound = PR_TRUE;
4459
858k
        sftkqueue_delete(session, hSession, slot->head, slot->sessHashSize);
4460
858k
    }
4461
858k
    PZ_Unlock(lock);
4462
4463
858k
    if (sessionFound) {
4464
858k
        SFTKDBHandle *handle;
4465
858k
        handle = sftk_getKeyDB(slot);
4466
858k
        PZ_Lock(slot->slotLock);
4467
858k
        if (--slot->sessionCount == 0) {
4468
0
            slot->isLoggedIn = PR_FALSE;
4469
0
            if (slot->needLogin && handle) {
4470
0
                sftkdb_ClearPassword(handle);
4471
0
            }
4472
0
        }
4473
858k
        PZ_Unlock(slot->slotLock);
4474
858k
        if (handle) {
4475
0
            sftk_freeDB(handle);
4476
0
        }
4477
858k
        if (session->info.flags & CKF_RW_SESSION) {
4478
0
            (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount);
4479
0
        }
4480
858k
        sftk_DestroySession(session);
4481
858k
        session = NULL;
4482
858k
    }
4483
4484
858k
    return CKR_OK;
4485
858k
}
4486
4487
/* NSC_CloseAllSessions closes all sessions with a token. */
4488
CK_RV
4489
NSC_CloseAllSessions(CK_SLOT_ID slotID)
4490
16
{
4491
16
    SFTKSlot *slot;
4492
4493
#ifndef NO_FORK_CHECK
4494
    /* skip fork check if we are being called from C_Initialize or C_Finalize */
4495
    if (!parentForkedAfterC_Initialize) {
4496
        CHECK_FORK();
4497
    }
4498
#endif
4499
4500
16
    slot = sftk_SlotFromID(slotID, PR_FALSE);
4501
16
    if (slot == NULL)
4502
0
        return CKR_SLOT_ID_INVALID;
4503
4504
16
    return sftk_CloseAllSessions(slot, PR_TRUE);
4505
16
}
4506
4507
/* NSC_GetSessionInfo obtains information about the session. */
4508
CK_RV
4509
NSC_GetSessionInfo(CK_SESSION_HANDLE hSession,
4510
                   CK_SESSION_INFO_PTR pInfo)
4511
0
{
4512
0
    SFTKSession *session;
4513
4514
0
    CHECK_FORK();
4515
4516
0
    session = sftk_SessionFromHandle(hSession);
4517
0
    if (session == NULL)
4518
0
        return CKR_SESSION_HANDLE_INVALID;
4519
4520
0
    PORT_Memcpy(pInfo, &session->info, sizeof(CK_SESSION_INFO));
4521
0
    sftk_FreeSession(session);
4522
0
    return CKR_OK;
4523
0
}
4524
4525
/* NSC_Login logs a user into a token. */
4526
CK_RV
4527
NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType,
4528
          CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
4529
0
{
4530
0
    SFTKSlot *slot;
4531
0
    SFTKSession *session;
4532
0
    SFTKDBHandle *handle;
4533
0
    CK_FLAGS sessionFlags;
4534
0
    SECStatus rv;
4535
0
    CK_RV crv;
4536
0
    char pinStr[SFTK_MAX_PIN + 1];
4537
0
    PRBool tokenRemoved = PR_FALSE;
4538
0
    PRBool isLoggedIn;
4539
0
    PRBool needLogin;
4540
4541
0
    CHECK_FORK();
4542
4543
    /* get the slot */
4544
0
    slot = sftk_SlotFromSessionHandle(hSession);
4545
0
    if (slot == NULL) {
4546
0
        return CKR_SESSION_HANDLE_INVALID;
4547
0
    }
4548
4549
    /* make sure the session is valid */
4550
0
    session = sftk_SessionFromHandle(hSession);
4551
0
    if (session == NULL) {
4552
0
        return CKR_SESSION_HANDLE_INVALID;
4553
0
    }
4554
0
    sessionFlags = session->info.flags;
4555
0
    sftk_FreeSession(session);
4556
0
    session = NULL;
4557
4558
    /* can't log into the Netscape Slot */
4559
0
    if (slot->slotID == NETSCAPE_SLOT_ID) {
4560
0
        return CKR_USER_TYPE_INVALID;
4561
0
    }
4562
4563
0
    PZ_Lock(slot->slotLock);
4564
0
    isLoggedIn = slot->isLoggedIn;
4565
0
    needLogin = slot->needLogin;
4566
0
    PZ_Unlock(slot->slotLock);
4567
4568
0
    if (isLoggedIn)
4569
0
        return CKR_USER_ALREADY_LOGGED_IN;
4570
0
    if (!needLogin) {
4571
0
        return ulPinLen ? CKR_PIN_INCORRECT : CKR_OK;
4572
0
    }
4573
0
    slot->ssoLoggedIn = PR_FALSE;
4574
4575
0
    if (ulPinLen > SFTK_MAX_PIN)
4576
0
        return CKR_PIN_LEN_RANGE;
4577
4578
    /* convert to null terminated string */
4579
0
    if (ulPinLen) {
4580
0
        PORT_Memcpy(pinStr, pPin, ulPinLen);
4581
0
    }
4582
0
    pinStr[ulPinLen] = 0;
4583
4584
0
    handle = sftk_getKeyDB(slot);
4585
0
    if (handle == NULL) {
4586
0
        PORT_Memset(pinStr, 0, ulPinLen);
4587
0
        return CKR_USER_TYPE_INVALID;
4588
0
    }
4589
4590
    /*
4591
     * Deal with bootstrap. We allow the SSO to login in with a NULL
4592
     * password if and only if we haven't initialized the KEY DB yet.
4593
     * We only allow this on a RW session.
4594
     */
4595
0
    rv = sftkdb_HasPasswordSet(handle);
4596
0
    if (rv == SECFailure) {
4597
        /* allow SSO's to log in only if there is not password on the
4598
         * key database */
4599
0
        if (((userType == CKU_SO) && (sessionFlags & CKF_RW_SESSION))
4600
            /* fips always needs to authenticate, even if there isn't a db */
4601
0
            || (sftk_isFIPS(slot->slotID))) {
4602
            /* should this be a fixed password? */
4603
0
            if (ulPinLen == 0) {
4604
0
                sftkdb_ClearPassword(handle);
4605
0
                PZ_Lock(slot->slotLock);
4606
0
                slot->isLoggedIn = PR_TRUE;
4607
0
                slot->ssoLoggedIn = (PRBool)(userType == CKU_SO);
4608
0
                PZ_Unlock(slot->slotLock);
4609
0
                sftk_update_all_states(slot);
4610
0
                crv = CKR_OK;
4611
0
                goto done;
4612
0
            }
4613
0
            crv = CKR_PIN_INCORRECT;
4614
0
            goto done;
4615
0
        }
4616
0
        crv = CKR_USER_TYPE_INVALID;
4617
0
        goto done;
4618
0
    }
4619
4620
    /* don't allow the SSO to log in if the user is already initialized */
4621
0
    if (userType != CKU_USER) {
4622
0
        crv = CKR_USER_TYPE_INVALID;
4623
0
        goto done;
4624
0
    }
4625
4626
    /* build the hashed pins which we pass around */
4627
0
    PR_Lock(slot->pwCheckLock);
4628
0
    rv = sftkdb_CheckPassword(handle, pinStr, &tokenRemoved);
4629
0
    if (tokenRemoved) {
4630
0
        sftk_CloseAllSessions(slot, PR_FALSE);
4631
0
    }
4632
0
    if ((rv != SECSuccess) && (sftk_isFIPS(slot->slotID))) {
4633
0
        PR_Sleep(loginWaitTime);
4634
0
    }
4635
0
    PR_Unlock(slot->pwCheckLock);
4636
0
    if (rv == SECSuccess) {
4637
0
        PZ_Lock(slot->slotLock);
4638
        /* make sure the login state matches the underlying
4639
         * database state */
4640
0
        slot->isLoggedIn = sftkdb_PWCached(handle) == SECSuccess ? PR_TRUE : PR_FALSE;
4641
0
        PZ_Unlock(slot->slotLock);
4642
4643
0
        sftk_freeDB(handle);
4644
0
        handle = NULL;
4645
4646
        /* update all sessions */
4647
0
        sftk_update_all_states(slot);
4648
0
        return CKR_OK;
4649
0
    }
4650
4651
0
    crv = CKR_PIN_INCORRECT;
4652
0
done:
4653
0
    PORT_Memset(pinStr, 0, ulPinLen);
4654
0
    if (handle) {
4655
0
        sftk_freeDB(handle);
4656
0
    }
4657
0
    return crv;
4658
0
}
4659
4660
CK_RV
4661
NSC_LoginUser(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType,
4662
              CK_CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pUsername,
4663
              CK_ULONG ulUsernameLen)
4664
0
{
4665
    /* softoken currently does not support additional users */
4666
0
    return CKR_OPERATION_NOT_INITIALIZED;
4667
0
}
4668
4669
/* NSC_Logout logs a user out from a token. */
4670
CK_RV
4671
NSC_Logout(CK_SESSION_HANDLE hSession)
4672
0
{
4673
0
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
4674
0
    SFTKSession *session;
4675
0
    SFTKDBHandle *handle;
4676
4677
0
    CHECK_FORK();
4678
4679
0
    if (slot == NULL) {
4680
0
        return CKR_SESSION_HANDLE_INVALID;
4681
0
    }
4682
0
    session = sftk_SessionFromHandle(hSession);
4683
0
    if (session == NULL)
4684
0
        return CKR_SESSION_HANDLE_INVALID;
4685
0
    sftk_FreeSession(session);
4686
0
    session = NULL;
4687
4688
0
    if (!slot->isLoggedIn)
4689
0
        return CKR_USER_NOT_LOGGED_IN;
4690
4691
0
    handle = sftk_getKeyDB(slot);
4692
0
    PZ_Lock(slot->slotLock);
4693
0
    slot->isLoggedIn = PR_FALSE;
4694
0
    slot->ssoLoggedIn = PR_FALSE;
4695
0
    if (slot->needLogin && handle) {
4696
0
        sftkdb_ClearPassword(handle);
4697
0
    }
4698
0
    PZ_Unlock(slot->slotLock);
4699
0
    if (handle) {
4700
0
        sftk_freeDB(handle);
4701
0
    }
4702
4703
0
    sftk_update_all_states(slot);
4704
0
    return CKR_OK;
4705
0
}
4706
4707
/*
4708
 * Create or remove a new slot on the fly.
4709
 * When creating a slot, "slot" is the slot that the request came from. The
4710
 * resulting slot will live in the same module as "slot".
4711
 * When removing a slot, "slot" is the slot to be removed.
4712
 * "object" is the creation object that specifies the module spec for the slot
4713
 * to add or remove.
4714
 */
4715
static CK_RV
4716
sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class,
4717
                   SFTKObject *object)
4718
0
{
4719
0
    PRBool isValidUserSlot = PR_FALSE;
4720
0
    PRBool isValidFIPSUserSlot = PR_FALSE;
4721
0
    PRBool isValidSlot = PR_FALSE;
4722
0
    PRBool isFIPS = PR_FALSE;
4723
0
    unsigned int moduleIndex = NSC_NON_FIPS_MODULE;
4724
0
    SFTKAttribute *attribute;
4725
0
    sftk_parameters paramStrings;
4726
0
    char *paramString;
4727
0
    CK_SLOT_ID slotID = 0;
4728
0
    SFTKSlot *newSlot = NULL;
4729
0
    CK_RV crv = CKR_OK;
4730
4731
0
    if (class != CKO_NSS_DELSLOT && class != CKO_NSS_NEWSLOT) {
4732
0
        return CKR_ATTRIBUTE_VALUE_INVALID;
4733
0
    }
4734
0
    if (class == CKO_NSS_NEWSLOT && slot->slotID == FIPS_SLOT_ID) {
4735
0
        isFIPS = PR_TRUE;
4736
0
    }
4737
0
    attribute = sftk_FindAttribute(object, CKA_NSS_MODULE_SPEC);
4738
0
    if (attribute == NULL) {
4739
0
        return CKR_TEMPLATE_INCOMPLETE;
4740
0
    }
4741
0
    paramString = (char *)attribute->attrib.pValue;
4742
0
    crv = sftk_parseParameters(paramString, &paramStrings, isFIPS);
4743
0
    if (crv != CKR_OK) {
4744
0
        goto loser;
4745
0
    }
4746
4747
    /* enforce only one at a time */
4748
0
    if (paramStrings.token_count != 1) {
4749
0
        crv = CKR_ATTRIBUTE_VALUE_INVALID;
4750
0
        goto loser;
4751
0
    }
4752
4753
0
    slotID = paramStrings.tokens[0].slotID;
4754
4755
    /* stay within the valid ID space */
4756
0
    isValidUserSlot = (slotID >= SFTK_MIN_USER_SLOT_ID &&
4757
0
                       slotID <= SFTK_MAX_USER_SLOT_ID);
4758
0
    isValidFIPSUserSlot = (slotID >= SFTK_MIN_FIPS_USER_SLOT_ID &&
4759
0
                           slotID <= SFTK_MAX_FIPS_USER_SLOT_ID);
4760
4761
0
    if (class == CKO_NSS_DELSLOT) {
4762
0
        if (slot->slotID == slotID) {
4763
0
            isValidSlot = isValidUserSlot || isValidFIPSUserSlot;
4764
0
        }
4765
0
    } else {
4766
        /* only the crypto or FIPS slots can create new slot objects */
4767
0
        if (slot->slotID == NETSCAPE_SLOT_ID) {
4768
0
            isValidSlot = isValidUserSlot;
4769
0
            moduleIndex = NSC_NON_FIPS_MODULE;
4770
0
        } else if (slot->slotID == FIPS_SLOT_ID) {
4771
0
            isValidSlot = isValidFIPSUserSlot;
4772
0
            moduleIndex = NSC_FIPS_MODULE;
4773
0
        }
4774
0
    }
4775
4776
0
    if (!isValidSlot) {
4777
0
        crv = CKR_ATTRIBUTE_VALUE_INVALID;
4778
0
        goto loser;
4779
0
    }
4780
4781
    /* unload any existing slot at this id */
4782
0
    newSlot = sftk_SlotFromID(slotID, PR_TRUE);
4783
0
    if (newSlot && newSlot->present) {
4784
0
        crv = SFTK_ShutdownSlot(newSlot);
4785
0
        if (crv != CKR_OK) {
4786
0
            goto loser;
4787
0
        }
4788
0
    }
4789
4790
    /* if we were just planning on deleting the slot, then do so now */
4791
0
    if (class == CKO_NSS_DELSLOT) {
4792
        /* sort of a unconventional use of this error code, be we are
4793
         * overusing CKR_ATTRIBUTE_VALUE_INVALID, and it does apply */
4794
0
        crv = newSlot ? CKR_OK : CKR_SLOT_ID_INVALID;
4795
0
        goto loser; /* really exit */
4796
0
    }
4797
4798
0
    if (newSlot) {
4799
0
        crv = SFTK_SlotReInit(newSlot, paramStrings.configdir,
4800
0
                              paramStrings.updatedir, paramStrings.updateID,
4801
0
                              &paramStrings.tokens[0], moduleIndex);
4802
0
    } else {
4803
0
        crv = SFTK_SlotInit(paramStrings.configdir,
4804
0
                            paramStrings.updatedir, paramStrings.updateID,
4805
0
                            &paramStrings.tokens[0], moduleIndex);
4806
0
    }
4807
4808
0
loser:
4809
0
    sftk_freeParams(&paramStrings);
4810
0
    sftk_FreeAttribute(attribute);
4811
4812
0
    return crv;
4813
0
}
4814
4815
/* NSC_CreateObject creates a new object. */
4816
CK_RV
4817
NSC_CreateObject(CK_SESSION_HANDLE hSession,
4818
                 CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
4819
                 CK_OBJECT_HANDLE_PTR phObject)
4820
23.7k
{
4821
23.7k
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
4822
23.7k
    SFTKSession *session;
4823
23.7k
    SFTKObject *object;
4824
    /* make sure class isn't randomly CKO_NSS_NEWSLOT or
4825
     * CKO_NETSCPE_DELSLOT. */
4826
23.7k
    CK_OBJECT_CLASS class = CKO_VENDOR_DEFINED;
4827
23.7k
    CK_RV crv;
4828
23.7k
    int i;
4829
4830
23.7k
    CHECK_FORK();
4831
4832
23.7k
    *phObject = CK_INVALID_HANDLE;
4833
4834
23.7k
    if (slot == NULL) {
4835
0
        return CKR_SESSION_HANDLE_INVALID;
4836
0
    }
4837
    /*
4838
     * now lets create an object to hang the attributes off of
4839
     */
4840
23.7k
    object = sftk_NewObject(slot); /* fill in the handle later */
4841
23.7k
    if (object == NULL) {
4842
0
        return CKR_HOST_MEMORY;
4843
0
    }
4844
4845
    /*
4846
     * sftk_NewObject will set object->isFIPS to PR_TRUE if the slot is FIPS.
4847
     * We don't need to worry about that here, as FC_CreateObject will always
4848
     * disallow the import of secret and private keys, regardless of isFIPS
4849
     * approval status. Therefore, at this point we know that the key is a
4850
     * public key, which is acceptable to be imported in plaintext.
4851
     */
4852
4853
    /*
4854
     * load the template values into the object
4855
     */
4856
183k
    for (i = 0; i < (int)ulCount; i++) {
4857
159k
        crv = sftk_AddAttributeType(object, sftk_attr_expand(&pTemplate[i]));
4858
159k
        if (crv != CKR_OK) {
4859
0
            sftk_FreeObject(object);
4860
0
            return crv;
4861
0
        }
4862
159k
        if ((pTemplate[i].type == CKA_CLASS) && pTemplate[i].pValue) {
4863
23.7k
            class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue;
4864
23.7k
        }
4865
159k
    }
4866
4867
    /* get the session */
4868
23.7k
    session = sftk_SessionFromHandle(hSession);
4869
23.7k
    if (session == NULL) {
4870
0
        sftk_FreeObject(object);
4871
0
        return CKR_SESSION_HANDLE_INVALID;
4872
0
    }
4873
4874
    /*
4875
     * handle pseudo objects (CKO_NEWSLOT)
4876
     */
4877
23.7k
    if ((class == CKO_NSS_NEWSLOT) || (class == CKO_NSS_DELSLOT)) {
4878
0
        crv = sftk_CreateNewSlot(slot, class, object);
4879
0
        goto done;
4880
0
    }
4881
4882
    /*
4883
     * handle the base object stuff
4884
     */
4885
23.7k
    crv = sftk_handleObject(object, session);
4886
23.7k
    *phObject = object->handle;
4887
23.7k
done:
4888
23.7k
    sftk_FreeSession(session);
4889
23.7k
    sftk_FreeObject(object);
4890
4891
23.7k
    return crv;
4892
23.7k
}
4893
4894
/* NSC_CopyObject copies an object, creating a new object for the copy. */
4895
CK_RV
4896
NSC_CopyObject(CK_SESSION_HANDLE hSession,
4897
               CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
4898
               CK_OBJECT_HANDLE_PTR phNewObject)
4899
12
{
4900
12
    SFTKObject *destObject, *srcObject;
4901
12
    SFTKSession *session;
4902
12
    CK_RV crv = CKR_OK;
4903
12
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
4904
12
    int i;
4905
4906
12
    CHECK_FORK();
4907
4908
12
    if (slot == NULL) {
4909
0
        return CKR_SESSION_HANDLE_INVALID;
4910
0
    }
4911
    /* Get srcObject so we can find the class */
4912
12
    session = sftk_SessionFromHandle(hSession);
4913
12
    if (session == NULL) {
4914
0
        return CKR_SESSION_HANDLE_INVALID;
4915
0
    }
4916
12
    srcObject = sftk_ObjectFromHandle(hObject, session);
4917
12
    if (srcObject == NULL) {
4918
0
        sftk_FreeSession(session);
4919
0
        return CKR_OBJECT_HANDLE_INVALID;
4920
0
    }
4921
    /*
4922
     * create an object to hang the attributes off of
4923
     */
4924
12
    destObject = sftk_NewObject(slot); /* fill in the handle later */
4925
12
    if (destObject == NULL) {
4926
0
        sftk_FreeSession(session);
4927
0
        sftk_FreeObject(srcObject);
4928
0
        return CKR_HOST_MEMORY;
4929
0
    }
4930
4931
    /*
4932
     * load the template values into the object
4933
     */
4934
18
    for (i = 0; i < (int)ulCount; i++) {
4935
6
        if (sftk_modifyType(pTemplate[i].type, srcObject->objclass) == SFTK_NEVER) {
4936
0
            crv = CKR_ATTRIBUTE_READ_ONLY;
4937
0
            break;
4938
0
        }
4939
6
        crv = sftk_AddAttributeType(destObject, sftk_attr_expand(&pTemplate[i]));
4940
6
        if (crv != CKR_OK) {
4941
0
            break;
4942
0
        }
4943
6
    }
4944
12
    if (crv != CKR_OK) {
4945
0
        sftk_FreeSession(session);
4946
0
        sftk_FreeObject(srcObject);
4947
0
        sftk_FreeObject(destObject);
4948
0
        return crv;
4949
0
    }
4950
4951
    /* sensitive can only be changed to CK_TRUE */
4952
12
    if (sftk_hasAttribute(destObject, CKA_SENSITIVE)) {
4953
0
        if (!sftk_isTrue(destObject, CKA_SENSITIVE)) {
4954
0
            sftk_FreeSession(session);
4955
0
            sftk_FreeObject(srcObject);
4956
0
            sftk_FreeObject(destObject);
4957
0
            return CKR_ATTRIBUTE_READ_ONLY;
4958
0
        }
4959
0
    }
4960
4961
    /*
4962
     * now copy the old attributes from the new attributes
4963
     */
4964
    /* don't create a token object if we aren't in a rw session */
4965
    /* we need to hold the lock to copy a consistant version of
4966
     * the object. */
4967
12
    crv = sftk_CopyObject(destObject, srcObject);
4968
4969
12
    destObject->objclass = srcObject->objclass;
4970
12
    sftk_FreeObject(srcObject);
4971
12
    if (crv != CKR_OK) {
4972
0
        sftk_FreeObject(destObject);
4973
0
        sftk_FreeSession(session);
4974
0
        return crv;
4975
0
    }
4976
4977
12
    crv = sftk_handleObject(destObject, session);
4978
12
    *phNewObject = destObject->handle;
4979
12
    sftk_FreeSession(session);
4980
12
    sftk_FreeObject(destObject);
4981
4982
12
    return crv;
4983
12
}
4984
4985
/* NSC_GetObjectSize gets the size of an object in bytes. */
4986
CK_RV
4987
NSC_GetObjectSize(CK_SESSION_HANDLE hSession,
4988
                  CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize)
4989
0
{
4990
0
    CHECK_FORK();
4991
4992
0
    *pulSize = 0;
4993
0
    return CKR_OK;
4994
0
}
4995
4996
static CK_RV
4997
nsc_GetTokenAttributeValue(SFTKSession *session, CK_OBJECT_HANDLE hObject,
4998
                           CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
4999
0
{
5000
0
    SFTKSlot *slot = sftk_SlotFromSession(session);
5001
0
    SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, hObject);
5002
0
    SFTKDBHandle *keydb = NULL;
5003
0
    CK_RV crv;
5004
5005
0
    if (dbHandle == NULL) {
5006
0
        return CKR_OBJECT_HANDLE_INVALID;
5007
0
    }
5008
5009
0
    crv = sftkdb_GetAttributeValue(dbHandle, hObject, pTemplate, ulCount);
5010
5011
    /* make sure we don't export any sensitive information */
5012
0
    keydb = sftk_getKeyDB(slot);
5013
0
    if (dbHandle == keydb) {
5014
0
        CK_ULONG i;
5015
0
        for (i = 0; i < ulCount; i++) {
5016
0
            if (sftk_isSensitive(pTemplate[i].type, CKO_PRIVATE_KEY)) {
5017
0
                crv = CKR_ATTRIBUTE_SENSITIVE;
5018
0
                if (pTemplate[i].pValue && (pTemplate[i].ulValueLen != -1)) {
5019
0
                    PORT_Memset(pTemplate[i].pValue, 0,
5020
0
                                pTemplate[i].ulValueLen);
5021
0
                }
5022
0
                pTemplate[i].ulValueLen = -1;
5023
0
            }
5024
0
        }
5025
0
    }
5026
5027
0
    sftk_freeDB(dbHandle);
5028
0
    if (keydb) {
5029
0
        sftk_freeDB(keydb);
5030
0
    }
5031
0
    return crv;
5032
0
}
5033
5034
/* NSC_GetAttributeValue obtains the value of one or more object attributes. */
5035
CK_RV
5036
NSC_GetAttributeValue(CK_SESSION_HANDLE hSession,
5037
                      CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
5038
503k
{
5039
503k
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
5040
503k
    SFTKSession *session;
5041
503k
    SFTKObject *object;
5042
503k
    SFTKAttribute *attribute;
5043
503k
    PRBool sensitive, isLoggedIn, needLogin;
5044
503k
    CK_RV crv;
5045
503k
    int i;
5046
5047
503k
    CHECK_FORK();
5048
5049
503k
    if (slot == NULL) {
5050
0
        return CKR_SESSION_HANDLE_INVALID;
5051
0
    }
5052
    /*
5053
     * make sure we're allowed
5054
     */
5055
503k
    session = sftk_SessionFromHandle(hSession);
5056
503k
    if (session == NULL) {
5057
0
        return CKR_SESSION_HANDLE_INVALID;
5058
0
    }
5059
5060
    /* short circuit everything for token objects */
5061
503k
    if (sftk_isToken(hObject)) {
5062
0
        crv = nsc_GetTokenAttributeValue(session, hObject, pTemplate, ulCount);
5063
0
        sftk_FreeSession(session);
5064
0
        return crv;
5065
0
    }
5066
5067
    /* handle the session object */
5068
503k
    object = sftk_ObjectFromHandle(hObject, session);
5069
503k
    sftk_FreeSession(session);
5070
503k
    if (object == NULL) {
5071
0
        return CKR_OBJECT_HANDLE_INVALID;
5072
0
    }
5073
5074
503k
    PZ_Lock(slot->slotLock);
5075
503k
    isLoggedIn = slot->isLoggedIn;
5076
503k
    needLogin = slot->needLogin;
5077
503k
    PZ_Unlock(slot->slotLock);
5078
5079
    /* don't read a private object if we aren't logged in */
5080
503k
    if (!isLoggedIn && needLogin && sftk_isTrue(object, CKA_PRIVATE)) {
5081
0
        sftk_FreeObject(object);
5082
0
        return CKR_USER_NOT_LOGGED_IN;
5083
0
    }
5084
5085
503k
    crv = CKR_OK;
5086
503k
    sensitive = sftk_isTrue(object, CKA_SENSITIVE);
5087
1.33M
    for (i = 0; i < (int)ulCount; i++) {
5088
        /* Make sure that this attribute is retrievable */
5089
828k
        if (sensitive && sftk_isSensitive(pTemplate[i].type, object->objclass)) {
5090
0
            crv = CKR_ATTRIBUTE_SENSITIVE;
5091
0
            pTemplate[i].ulValueLen = -1;
5092
0
            continue;
5093
0
        }
5094
828k
        attribute = sftk_FindAttribute(object, pTemplate[i].type);
5095
828k
        if (attribute == NULL) {
5096
6
            crv = CKR_ATTRIBUTE_TYPE_INVALID;
5097
6
            pTemplate[i].ulValueLen = -1;
5098
6
            continue;
5099
6
        }
5100
828k
        if (pTemplate[i].pValue != NULL) {
5101
633k
            PORT_Memcpy(pTemplate[i].pValue, attribute->attrib.pValue,
5102
633k
                        attribute->attrib.ulValueLen);
5103
633k
        }
5104
828k
        pTemplate[i].ulValueLen = attribute->attrib.ulValueLen;
5105
828k
        sftk_FreeAttribute(attribute);
5106
828k
    }
5107
5108
503k
    sftk_FreeObject(object);
5109
503k
    return crv;
5110
503k
}
5111
5112
/* NSC_SetAttributeValue modifies the value of one or more object attributes */
5113
CK_RV
5114
NSC_SetAttributeValue(CK_SESSION_HANDLE hSession,
5115
                      CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
5116
52.5k
{
5117
52.5k
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
5118
52.5k
    SFTKSession *session;
5119
52.5k
    SFTKAttribute *attribute;
5120
52.5k
    SFTKObject *object;
5121
52.5k
    PRBool isToken, isLoggedIn, needLogin;
5122
52.5k
    CK_RV crv = CKR_OK;
5123
52.5k
    CK_BBOOL legal;
5124
52.5k
    int i;
5125
5126
52.5k
    CHECK_FORK();
5127
5128
52.5k
    if (slot == NULL) {
5129
0
        return CKR_SESSION_HANDLE_INVALID;
5130
0
    }
5131
    /*
5132
     * make sure we're allowed
5133
     */
5134
52.5k
    session = sftk_SessionFromHandle(hSession);
5135
52.5k
    if (session == NULL) {
5136
0
        return CKR_SESSION_HANDLE_INVALID;
5137
0
    }
5138
5139
52.5k
    object = sftk_ObjectFromHandle(hObject, session);
5140
52.5k
    if (object == NULL) {
5141
0
        sftk_FreeSession(session);
5142
0
        return CKR_OBJECT_HANDLE_INVALID;
5143
0
    }
5144
5145
52.5k
    PZ_Lock(slot->slotLock);
5146
52.5k
    isLoggedIn = slot->isLoggedIn;
5147
52.5k
    needLogin = slot->needLogin;
5148
52.5k
    PZ_Unlock(slot->slotLock);
5149
5150
    /* don't modify a private object if we aren't logged in */
5151
52.5k
    if (!isLoggedIn && needLogin && sftk_isTrue(object, CKA_PRIVATE)) {
5152
0
        sftk_FreeSession(session);
5153
0
        sftk_FreeObject(object);
5154
0
        return CKR_USER_NOT_LOGGED_IN;
5155
0
    }
5156
5157
    /* don't modify a token object if we aren't in a rw session */
5158
52.5k
    isToken = sftk_isTrue(object, CKA_TOKEN);
5159
52.5k
    if (((session->info.flags & CKF_RW_SESSION) == 0) && isToken) {
5160
0
        sftk_FreeSession(session);
5161
0
        sftk_FreeObject(object);
5162
0
        return CKR_SESSION_READ_ONLY;
5163
0
    }
5164
52.5k
    sftk_FreeSession(session);
5165
5166
    /* only change modifiable objects */
5167
52.5k
    if (!sftk_isTrue(object, CKA_MODIFIABLE)) {
5168
0
        sftk_FreeObject(object);
5169
0
        return CKR_ATTRIBUTE_READ_ONLY;
5170
0
    }
5171
5172
105k
    for (i = 0; i < (int)ulCount; i++) {
5173
        /* Make sure that this attribute is changeable */
5174
52.5k
        switch (sftk_modifyType(pTemplate[i].type, object->objclass)) {
5175
0
            case SFTK_NEVER:
5176
0
            case SFTK_ONCOPY:
5177
0
            default:
5178
0
                crv = CKR_ATTRIBUTE_READ_ONLY;
5179
0
                break;
5180
5181
0
            case SFTK_SENSITIVE:
5182
0
                legal = (pTemplate[i].type == CKA_EXTRACTABLE) ? CK_FALSE : CK_TRUE;
5183
0
                if ((*(CK_BBOOL *)pTemplate[i].pValue) != legal) {
5184
0
                    crv = CKR_ATTRIBUTE_READ_ONLY;
5185
0
                }
5186
0
                break;
5187
52.5k
            case SFTK_ALWAYS:
5188
52.5k
                break;
5189
52.5k
        }
5190
52.5k
        if (crv != CKR_OK)
5191
0
            break;
5192
5193
        /* find the old attribute */
5194
52.5k
        attribute = sftk_FindAttribute(object, pTemplate[i].type);
5195
52.5k
        if (attribute == NULL) {
5196
0
            crv = CKR_ATTRIBUTE_TYPE_INVALID;
5197
0
            break;
5198
0
        }
5199
52.5k
        sftk_FreeAttribute(attribute);
5200
52.5k
        crv = sftk_forceAttribute(object, sftk_attr_expand(&pTemplate[i]));
5201
52.5k
        if (crv != CKR_OK)
5202
0
            break;
5203
52.5k
    }
5204
5205
52.5k
    sftk_FreeObject(object);
5206
52.5k
    return crv;
5207
52.5k
}
5208
5209
static CK_RV
5210
sftk_expandSearchList(SFTKSearchResults *search, int count)
5211
0
{
5212
0
    search->array_size += count;
5213
0
    search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles,
5214
0
                                                       sizeof(CK_OBJECT_HANDLE) * search->array_size);
5215
0
    return search->handles ? CKR_OK : CKR_HOST_MEMORY;
5216
0
}
5217
5218
static CK_RV
5219
sftk_searchDatabase(SFTKDBHandle *handle, SFTKSearchResults *search,
5220
                    const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount)
5221
279k
{
5222
279k
    CK_RV crv;
5223
279k
    int objectListSize = search->array_size - search->size;
5224
279k
    CK_OBJECT_HANDLE *array = &search->handles[search->size];
5225
279k
    SDBFind *find = NULL;
5226
279k
    CK_ULONG count;
5227
5228
279k
    crv = sftkdb_FindObjectsInit(handle, pTemplate, ulCount, &find);
5229
279k
    if (crv != CKR_OK)
5230
0
        return crv;
5231
279k
    do {
5232
279k
        crv = sftkdb_FindObjects(handle, find, array, objectListSize, &count);
5233
279k
        if ((crv != CKR_OK) || (count == 0))
5234
279k
            break;
5235
0
        search->size += count;
5236
0
        objectListSize -= count;
5237
0
        if (objectListSize > 0)
5238
0
            break;
5239
0
        crv = sftk_expandSearchList(search, NSC_SEARCH_BLOCK_SIZE);
5240
0
        objectListSize = NSC_SEARCH_BLOCK_SIZE;
5241
0
        array = &search->handles[search->size];
5242
0
    } while (crv == CKR_OK);
5243
0
    sftkdb_FindObjectsFinal(handle, find);
5244
5245
279k
    return crv;
5246
279k
}
5247
5248
/* softoken used to search the SMimeEntries automatically instead of
5249
 * doing this in pk11wrap. This code should really be up in
5250
 * pk11wrap so that it will work with other tokens other than softoken.
5251
 */
5252
CK_RV
5253
sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle,
5254
               SFTKSearchResults *search, CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount)
5255
279k
{
5256
279k
    PRBool isCert = PR_FALSE;
5257
279k
    int emailIndex = -1;
5258
279k
    unsigned int i;
5259
279k
    SFTKSearchResults smime_search;
5260
279k
    CK_ATTRIBUTE smime_template[2];
5261
279k
    CK_OBJECT_CLASS smime_class = CKO_NSS_SMIME;
5262
279k
    SFTKAttribute *attribute = NULL;
5263
279k
    SFTKObject *object = NULL;
5264
279k
    CK_RV crv = CKR_OK;
5265
5266
279k
    smime_search.handles = NULL; /* paranoia, some one is bound to add a goto
5267
                                  * loser before this gets initialized */
5268
5269
    /* see if we are looking for email certs */
5270
839k
    for (i = 0; i < ulCount; i++) {
5271
746k
        if (pTemplate[i].type == CKA_CLASS) {
5272
279k
            if ((pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS) ||
5273
279k
                 (*(CK_OBJECT_CLASS *)pTemplate[i].pValue) != CKO_CERTIFICATE)) {
5274
                /* not a cert, skip out */
5275
185k
                break;
5276
185k
            }
5277
93.5k
            isCert = PR_TRUE;
5278
466k
        } else if (pTemplate[i].type == CKA_NSS_EMAIL) {
5279
0
            emailIndex = i;
5280
0
        }
5281
560k
        if (isCert && (emailIndex != -1))
5282
0
            break;
5283
560k
    }
5284
5285
279k
    if (!isCert || (emailIndex == -1)) {
5286
279k
        return CKR_OK;
5287
279k
    }
5288
5289
    /* we are doing a cert and email search, find the SMimeEntry */
5290
0
    smime_template[0].type = CKA_CLASS;
5291
0
    smime_template[0].pValue = &smime_class;
5292
0
    smime_template[0].ulValueLen = sizeof(smime_class);
5293
0
    smime_template[1] = pTemplate[emailIndex];
5294
5295
0
    smime_search.handles = (CK_OBJECT_HANDLE *)
5296
0
        PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE);
5297
0
    if (smime_search.handles == NULL) {
5298
0
        crv = CKR_HOST_MEMORY;
5299
0
        goto loser;
5300
0
    }
5301
0
    smime_search.index = 0;
5302
0
    smime_search.size = 0;
5303
0
    smime_search.array_size = NSC_SEARCH_BLOCK_SIZE;
5304
5305
0
    crv = sftk_searchDatabase(handle, &smime_search, smime_template, 2);
5306
0
    if (crv != CKR_OK || smime_search.size == 0) {
5307
0
        goto loser;
5308
0
    }
5309
5310
    /* get the SMime subject */
5311
0
    object = sftk_NewTokenObject(slot, NULL, smime_search.handles[0]);
5312
0
    if (object == NULL) {
5313
0
        crv = CKR_HOST_MEMORY; /* is there any other reason for this failure? */
5314
0
        goto loser;
5315
0
    }
5316
0
    attribute = sftk_FindAttribute(object, CKA_SUBJECT);
5317
0
    if (attribute == NULL) {
5318
0
        crv = CKR_ATTRIBUTE_TYPE_INVALID;
5319
0
        goto loser;
5320
0
    }
5321
5322
    /* now find the certs with that subject */
5323
0
    pTemplate[emailIndex] = attribute->attrib;
5324
    /* now add the appropriate certs to the search list */
5325
0
    crv = sftk_searchDatabase(handle, search, pTemplate, ulCount);
5326
0
    pTemplate[emailIndex] = smime_template[1]; /* restore the user's template*/
5327
5328
0
loser:
5329
0
    if (attribute) {
5330
0
        sftk_FreeAttribute(attribute);
5331
0
    }
5332
0
    if (object) {
5333
0
        sftk_FreeObject(object);
5334
0
    }
5335
0
    if (smime_search.handles) {
5336
0
        PORT_Free(smime_search.handles);
5337
0
    }
5338
5339
0
    return crv;
5340
0
}
5341
5342
static void
5343
sftk_pruneSearch(CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount,
5344
                 PRBool *searchCertDB, PRBool *searchKeyDB)
5345
279k
{
5346
279k
    CK_ULONG i;
5347
5348
279k
    *searchCertDB = PR_TRUE;
5349
279k
    *searchKeyDB = PR_TRUE;
5350
559k
    for (i = 0; i < ulCount; i++) {
5351
559k
        if (pTemplate[i].type == CKA_CLASS && pTemplate[i].pValue != NULL) {
5352
279k
            CK_OBJECT_CLASS class = *((CK_OBJECT_CLASS *)pTemplate[i].pValue);
5353
279k
            if (class == CKO_PRIVATE_KEY || class == CKO_SECRET_KEY) {
5354
0
                *searchCertDB = PR_FALSE;
5355
279k
            } else {
5356
279k
                *searchKeyDB = PR_FALSE;
5357
279k
            }
5358
279k
            break;
5359
279k
        }
5360
559k
    }
5361
279k
}
5362
5363
static CK_RV
5364
sftk_searchTokenList(SFTKSlot *slot, SFTKSearchResults *search,
5365
                     CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount,
5366
                     PRBool isLoggedIn)
5367
279k
{
5368
279k
    CK_RV crv = CKR_OK;
5369
279k
    CK_RV crv2;
5370
279k
    PRBool searchCertDB;
5371
279k
    PRBool searchKeyDB;
5372
5373
279k
    sftk_pruneSearch(pTemplate, ulCount, &searchCertDB, &searchKeyDB);
5374
5375
279k
    if (searchCertDB) {
5376
279k
        SFTKDBHandle *certHandle = sftk_getCertDB(slot);
5377
279k
        crv = sftk_searchDatabase(certHandle, search, pTemplate, ulCount);
5378
279k
        crv2 = sftk_emailhack(slot, certHandle, search, pTemplate, ulCount);
5379
279k
        if (crv == CKR_OK)
5380
279k
            crv = crv2;
5381
279k
        sftk_freeDB(certHandle);
5382
279k
    }
5383
5384
279k
    if (crv == CKR_OK && isLoggedIn && searchKeyDB) {
5385
0
        SFTKDBHandle *keyHandle = sftk_getKeyDB(slot);
5386
0
        crv = sftk_searchDatabase(keyHandle, search, pTemplate, ulCount);
5387
0
        sftk_freeDB(keyHandle);
5388
0
    }
5389
279k
    return crv;
5390
279k
}
5391
5392
/* NSC_FindObjectsInit initializes a search for token and session objects
5393
 * that match a template. */
5394
CK_RV
5395
NSC_FindObjectsInit(CK_SESSION_HANDLE hSession,
5396
                    CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
5397
279k
{
5398
279k
    SFTKSearchResults *search = NULL, *freeSearch = NULL;
5399
279k
    SFTKSession *session = NULL;
5400
279k
    SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
5401
279k
    CK_RV crv = CKR_OK;
5402
279k
    PRBool isLoggedIn;
5403
5404
279k
    CHECK_FORK();
5405
5406
279k
    if (slot == NULL) {
5407
0
        return CKR_SESSION_HANDLE_INVALID;
5408
0
    }
5409
279k
    session = sftk_SessionFromHandle(hSession);
5410
279k
    if (session == NULL) {
5411
0
        crv = CKR_SESSION_HANDLE_INVALID;
5412
0
        goto loser;
5413
0
    }
5414
5415
279k
    search = (SFTKSearchResults *)PORT_Alloc(sizeof(SFTKSearchResults));
5416
279k
    if (search == NULL) {
5417
0
        crv = CKR_HOST_MEMORY;
5418
0
        goto loser;
5419
0
    }
5420
279k
    search->handles = (CK_OBJECT_HANDLE *)
5421
279k
        PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE);
5422
279k
    if (search->handles == NULL) {
5423
0
        crv = CKR_HOST_MEMORY;
5424
0
        goto loser;
5425
0
    }
5426
279k
    search->index = 0;
5427
279k
    search->size = 0;
5428
279k
    search->array_size = NSC_SEARCH_BLOCK_SIZE;
5429
5430
279k
    PZ_Lock(slot->slotLock);
5431
279k
    isLoggedIn = (PRBool)((!slot->needLogin) || slot->isLoggedIn);
5432
279k
    PZ_Unlock(slot->slotLock);
5433
5434
279k
    PRBool validTokenAttribute = PR_FALSE;
5435
279k
    PRBool tokenAttributeValue = PR_FALSE;
5436
279k
    for (CK_ULONG i = 0; i < ulCount; i++) {
5437
279k
        CK_ATTRIBUTE_PTR attr = &pTemplate[i];
5438
279k
        if (attr->type == CKA_TOKEN && attr->pValue && attr->ulValueLen == sizeof(CK_BBOOL)) {
5439
279k
            if (*(CK_BBOOL *)attr->pValue == CK_TRUE) {
5440
279k
                validTokenAttribute = PR_TRUE;
5441
279k
                tokenAttributeValue = PR_TRUE;
5442
279k
            } else if (*(CK_BBOOL *)attr->pValue == CK_FALSE) {
5443
0
                validTokenAttribute = PR_TRUE;
5444
0
                tokenAttributeValue = PR_FALSE;
5445
0
            }
5446
279k
            break;
5447
279k
        }
5448
279k
    }
5449
5450
    // Search over the token object list if the template's CKA_TOKEN attribute is set to
5451
    // CK_TRUE or if it is not set.
5452
279k
    if (validTokenAttribute == PR_FALSE || tokenAttributeValue == PR_TRUE) {
5453
279k
        crv = sftk_searchTokenList(slot, search, pTemplate, ulCount, isLoggedIn);
5454
279k
        if (crv != CKR_OK) {
5455
0
            goto loser;
5456
0
        }
5457
279k
    }
5458
5459
    // Search over the session object list if the template's CKA_TOKEN attribute is set to
5460
    // CK_FALSE or if it is not set.
5461
279k
    if (validTokenAttribute == PR_FALSE || tokenAttributeValue == PR_FALSE) {
5462
8
        crv = sftk_searchObjectList(search, slot->sessObjHashTable,
5463
8
                                    slot->sessObjHashSize, slot->objectLock,
5464
8
                                    pTemplate, ulCount, isLoggedIn);
5465
8
        if (crv != CKR_OK) {
5466
0
            goto loser;
5467
0
        }
5468
8
    }
5469
5470
279k
    if ((freeSearch = session->search) != NULL) {
5471
0
        session->search = NULL;
5472
0
        sftk_FreeSearch(freeSearch);
5473
0
    }
5474
279k
    session->search = search;
5475
279k
    sftk_FreeSession(session);
5476
279k
    return CKR_OK;
5477
5478
0
loser:
5479
0
    if (search) {
5480
0
        sftk_FreeSearch(search);
5481
0
    }
5482
0
    if (session) {
5483
0
        sftk_FreeSession(session);
5484
0
    }
5485
0
    return crv;
5486
279k
}
5487
5488
/* NSC_FindObjects continues a search for token and session objects
5489
 * that match a template, obtaining additional object handles. */
5490
CK_RV
5491
NSC_FindObjects(CK_SESSION_HANDLE hSession,
5492
                CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount,
5493
                CK_ULONG_PTR pulObjectCount)
5494
279k
{
5495
279k
    SFTKSession *session;
5496
279k
    SFTKSearchResults *search;
5497
279k
    int transfer;
5498
279k
    int left;
5499
5500
279k
    CHECK_FORK();
5501
5502
279k
    *pulObjectCount = 0;
5503
279k
    session = sftk_SessionFromHandle(hSession);
5504
279k
    if (session == NULL)
5505
0
        return CKR_SESSION_HANDLE_INVALID;
5506
279k
    if (session->search == NULL) {
5507
0
        sftk_FreeSession(session);
5508
0
        return CKR_OK;
5509
0
    }
5510
279k
    search = session->search;
5511
279k
    left = session->search->size - session->search->index;
5512
279k
    transfer = ((int)ulMaxObjectCount > left) ? left : ulMaxObjectCount;
5513
279k
    if (transfer > 0) {
5514
0
        PORT_Memcpy(phObject, &search->handles[search->index],
5515
0
                    transfer * sizeof(CK_OBJECT_HANDLE));
5516
279k
    } else {
5517
279k
        *phObject = CK_INVALID_HANDLE;
5518
279k
    }
5519
5520
279k
    search->index += transfer;
5521
279k
    if (search->index == search->size) {
5522
279k
        session->search = NULL;
5523
279k
        sftk_FreeSearch(search);
5524
279k
    }
5525
279k
    *pulObjectCount = transfer;
5526
279k
    sftk_FreeSession(session);
5527
279k
    return CKR_OK;
5528
279k
}
5529
5530
/* NSC_FindObjectsFinal finishes a search for token and session objects. */
5531
CK_RV
5532
NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession)
5533
279k
{
5534
279k
    SFTKSession *session;
5535
279k
    SFTKSearchResults *search;
5536
5537
279k
    CHECK_FORK();
5538
5539
279k
    session = sftk_SessionFromHandle(hSession);
5540
279k
    if (session == NULL)
5541
0
        return CKR_SESSION_HANDLE_INVALID;
5542
279k
    search = session->search;
5543
279k
    session->search = NULL;
5544
279k
    sftk_FreeSession(session);
5545
279k
    if (search != NULL) {
5546
0
        sftk_FreeSearch(search);
5547
0
    }
5548
279k
    return CKR_OK;
5549
279k
}
5550
5551
CK_RV
5552
NSC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot,
5553
                     CK_VOID_PTR pReserved)
5554
0
{
5555
0
    CHECK_FORK();
5556
5557
0
    return CKR_FUNCTION_NOT_SUPPORTED;
5558
0
}
5559
5560
static CK_RV
5561
nsc_NSSGetFIPSStatus(CK_SESSION_HANDLE hSession,
5562
                     CK_OBJECT_HANDLE hObject,
5563
                     CK_ULONG ulOperationType,
5564
                     CK_ULONG *pulFIPSStatus)
5565
0
{
5566
0
    CK_ULONG sessionState = CKS_NSS_UNINITIALIZED;
5567
0
    CK_ULONG objectState = CKS_NSS_UNINITIALIZED;
5568
0
    PRBool needSession = PR_FALSE;
5569
0
    PRBool needObject = PR_FALSE;
5570
0
    SFTKSession *session;
5571
0
    SFTKObject *object;
5572
5573
0
    *pulFIPSStatus = CKS_NSS_FIPS_NOT_OK;
5574
5575
    /* first determine what we need to look up */
5576
0
    switch (ulOperationType) {
5577
0
        case CKT_NSS_SESSION_CHECK:
5578
0
        case CKT_NSS_SESSION_LAST_CHECK:
5579
0
            needSession = PR_TRUE;
5580
0
            needObject = PR_FALSE;
5581
0
            break;
5582
0
        case CKT_NSS_OBJECT_CHECK:
5583
0
            needSession = PR_FALSE;
5584
0
            needObject = PR_TRUE;
5585
0
            break;
5586
0
        case CKT_NSS_BOTH_CHECK:
5587
0
            needSession = PR_TRUE;
5588
0
            needObject = PR_TRUE;
5589
0
            break;
5590
0
        default:
5591
0
            return CKR_ARGUMENTS_BAD;
5592
0
    }
5593
5594
    /* we always need the session handle, the object handle is only
5595
     * meaningful if there is a session */
5596
0
    session = sftk_SessionFromHandle(hSession);
5597
0
    if (!session) {
5598
0
        return CKR_SESSION_HANDLE_INVALID;
5599
0
    }
5600
0
    if (needSession) {
5601
0
        if (CKT_NSS_SESSION_LAST_CHECK == ulOperationType) {
5602
0
            sessionState = session->lastOpWasFIPS ? CKS_NSS_FIPS_OK : CKS_NSS_FIPS_NOT_OK;
5603
0
        } else {
5604
0
            if (session->enc_context) {
5605
0
                sessionState = session->enc_context->isFIPS ? CKS_NSS_FIPS_OK : CKS_NSS_FIPS_NOT_OK;
5606
0
            }
5607
0
            if (sessionState != CKS_NSS_FIPS_NOT_OK && session->hash_context) {
5608
0
                sessionState = session->hash_context->isFIPS ? CKS_NSS_FIPS_OK : CKS_NSS_FIPS_NOT_OK;
5609
0
            }
5610
            /* sessionState is set to CKS_NSS_UNINITIALIZED if neither
5611
             * context exists */
5612
0
        }
5613
0
    }
5614
5615
0
    if (needObject) {
5616
0
        object = sftk_ObjectFromHandle(hObject, session);
5617
0
        if (!object) {
5618
0
            sftk_FreeSession(session);
5619
0
            return CKR_OBJECT_HANDLE_INVALID;
5620
0
        }
5621
0
        objectState = object->isFIPS ? CKS_NSS_FIPS_OK : CKS_NSS_FIPS_NOT_OK;
5622
0
        sftk_FreeObject(object);
5623
0
    }
5624
5625
0
    sftk_FreeSession(session);
5626
5627
    /* If we didn't fetch the state, then it is uninitialized.
5628
     * The session state can also be uninitialized if there are no active
5629
     * crypto operations on the session. Turns out the rules for combining
5630
     * the states are the same whether or not the state was uninitialzed
5631
     * because we didn't fetch it or because there wasn't a state to fetch.
5632
     */
5633
5634
    /* if the object State is uninitialized, return the state of the session. */
5635
0
    if (objectState == CKS_NSS_UNINITIALIZED) {
5636
        /* if they are both uninitalized, return CKS_FIPS_NOT_OK */
5637
0
        if (sessionState == CKS_NSS_UNINITIALIZED) {
5638
            /* *pulFIPSStatus already set to CKS_FIPS_NOT_OK */
5639
0
            return CKR_OK;
5640
0
        }
5641
0
        *pulFIPSStatus = sessionState;
5642
0
        return CKR_OK;
5643
0
    }
5644
    /* objectState is initialized, if sessionState is uninitialized, we can
5645
     * just return objectState */
5646
0
    if (sessionState == CKS_NSS_UNINITIALIZED) {
5647
0
        *pulFIPSStatus = objectState;
5648
0
        return CKR_OK;
5649
0
    }
5650
5651
    /* they are are not equal, one must be CKS_FIPS_NOT_OK, so we return that
5652
     * value CKS_FIPS_NOT_OK */
5653
0
    if (objectState != sessionState) {
5654
        /* *pulFIPSStatus already set to CKS_FIPS_NOT_OK */
5655
0
        return CKR_OK;
5656
0
    }
5657
5658
    /* objectState and sessionState or the same, so we can return either */
5659
0
    *pulFIPSStatus = sessionState;
5660
0
    return CKR_OK;
5661
0
}