Coverage Report

Created: 2025-07-27 06:08

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