Coverage Report

Created: 2024-05-20 06:23

/src/nss/lib/pk11wrap/pk11pars.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
 * The following handles the loading, unloading and management of
6
 * various PCKS #11 modules
7
 */
8
9
#include <ctype.h>
10
#include <assert.h>
11
#include "pkcs11.h"
12
#include "seccomon.h"
13
#include "secmod.h"
14
#include "secmodi.h"
15
#include "secmodti.h"
16
#include "pki3hack.h"
17
#include "secerr.h"
18
#include "nss.h"
19
#include "utilpars.h"
20
#include "pk11pub.h"
21
22
/* create a new module */
23
static SECMODModule *
24
secmod_NewModule(void)
25
2
{
26
2
    SECMODModule *newMod;
27
2
    PLArenaPool *arena;
28
29
    /* create an arena in which dllName and commonName can be
30
     * allocated.
31
     */
32
2
    arena = PORT_NewArena(512);
33
2
    if (arena == NULL) {
34
0
        return NULL;
35
0
    }
36
37
2
    newMod = (SECMODModule *)PORT_ArenaAlloc(arena, sizeof(SECMODModule));
38
2
    if (newMod == NULL) {
39
0
        PORT_FreeArena(arena, PR_FALSE);
40
0
        return NULL;
41
0
    }
42
43
    /*
44
     * initialize of the fields of the module
45
     */
46
2
    newMod->arena = arena;
47
2
    newMod->internal = PR_FALSE;
48
2
    newMod->loaded = PR_FALSE;
49
2
    newMod->isFIPS = PR_FALSE;
50
2
    newMod->dllName = NULL;
51
2
    newMod->commonName = NULL;
52
2
    newMod->library = NULL;
53
2
    newMod->functionList = NULL;
54
2
    newMod->slotCount = 0;
55
2
    newMod->slots = NULL;
56
2
    newMod->slotInfo = NULL;
57
2
    newMod->slotInfoCount = 0;
58
2
    newMod->refCount = 1;
59
2
    newMod->ssl[0] = 0;
60
2
    newMod->ssl[1] = 0;
61
2
    newMod->libraryParams = NULL;
62
2
    newMod->moduleDBFunc = NULL;
63
2
    newMod->parent = NULL;
64
2
    newMod->isCritical = PR_FALSE;
65
2
    newMod->isModuleDB = PR_FALSE;
66
2
    newMod->moduleDBOnly = PR_FALSE;
67
2
    newMod->trustOrder = 0;
68
2
    newMod->cipherOrder = 0;
69
2
    newMod->evControlMask = 0;
70
2
    newMod->refLock = PZ_NewLock(nssILockRefLock);
71
2
    if (newMod->refLock == NULL) {
72
0
        PORT_FreeArena(arena, PR_FALSE);
73
0
        return NULL;
74
0
    }
75
2
    return newMod;
76
2
}
77
78
/* private flags for isModuleDB (field in SECMODModule). */
79
/* The meaing of these flags is as follows:
80
 *
81
 * SECMOD_FLAG_MODULE_DB_IS_MODULE_DB - This is a module that accesses the
82
 *   database of other modules to load. Module DBs are loadable modules that
83
 *   tells NSS which PKCS #11 modules to load and when. These module DBs are
84
 *   chainable. That is, one module DB can load another one. NSS system init
85
 *   design takes advantage of this feature. In system NSS, a fixed system
86
 *   module DB loads the system defined libraries, then chains out to the
87
 *   traditional module DBs to load any system or user configured modules
88
 *   (like smart cards). This bit is the same as the already existing meaning
89
 *   of  isModuleDB = PR_TRUE. None of the other module db flags should be set
90
 *   if this flag isn't on.
91
 *
92
 * SECMOD_FLAG_MODULE_DB_SKIP_FIRST - This flag tells NSS to skip the first
93
 *   PKCS #11 module presented by a module DB. This allows the OS to load a
94
 *   softoken from the system module, then ask the existing module DB code to
95
 *   load the other PKCS #11 modules in that module DB (skipping it's request
96
 *   to load softoken). This gives the system init finer control over the
97
 *   configuration of that softoken module.
98
 *
99
 * SECMOD_FLAG_MODULE_DB_DEFAULT_MODDB - This flag allows system init to mark a
100
 *   different module DB as the 'default' module DB (the one in which
101
 *   'Add module' changes will go). Without this flag NSS takes the first
102
 *   module as the default Module DB, but in system NSS, that first module
103
 *   is the system module, which is likely read only (at least to the user).
104
 *   This  allows system NSS to delegate those changes to the user's module DB,
105
 *   preserving the user's ability to load new PKCS #11 modules (which only
106
 *   affect him), from existing applications like Firefox.
107
 */
108
1
#define SECMOD_FLAG_MODULE_DB_IS_MODULE_DB 0x01 /* must be set if any of the \
109
                                                 *other flags are set */
110
1
#define SECMOD_FLAG_MODULE_DB_SKIP_FIRST 0x02
111
1
#define SECMOD_FLAG_MODULE_DB_DEFAULT_MODDB 0x04
112
2
#define SECMOD_FLAG_MODULE_DB_POLICY_ONLY 0x08
113
114
/* private flags for internal (field in SECMODModule). */
115
/* The meaing of these flags is as follows:
116
 *
117
 * SECMOD_FLAG_INTERNAL_IS_INTERNAL - This is a marks the the module is
118
 *   the internal module (that is, softoken). This bit is the same as the
119
 *   already existing meaning of internal = PR_TRUE. None of the other
120
 *   internal flags should be set if this flag isn't on.
121
 *
122
 * SECMOD_FLAG_MODULE_INTERNAL_KEY_SLOT - This flag allows system init to mark
123
 *   a  different slot returned byt PK11_GetInternalKeySlot(). The 'primary'
124
 *   slot defined by this module will be the new internal key slot.
125
 */
126
2
#define SECMOD_FLAG_INTERNAL_IS_INTERNAL 0x01 /* must be set if any of \
127
                                               *the other flags are set */
128
4
#define SECMOD_FLAG_INTERNAL_KEY_SLOT 0x02
129
130
/* private flags for policy check. */
131
0
#define SECMOD_FLAG_POLICY_CHECK_IDENTIFIER 0x01
132
0
#define SECMOD_FLAG_POLICY_CHECK_VALUE 0x02
133
134
/*
135
 * for 3.4 we continue to use the old SECMODModule structure
136
 */
137
SECMODModule *
138
SECMOD_CreateModule(const char *library, const char *moduleName,
139
                    const char *parameters, const char *nss)
140
0
{
141
0
    return SECMOD_CreateModuleEx(library, moduleName, parameters, nss, NULL);
142
0
}
143
144
/*
145
 * NSS config options format:
146
 *
147
 * The specified ciphers will be allowed by policy, but an application
148
 * may allow more by policy explicitly:
149
 * config="allow=curve1:curve2:hash1:hash2:rsa-1024..."
150
 *
151
 * Only the specified hashes and curves will be allowed:
152
 * config="disallow=all allow=sha1:sha256:secp256r1:secp384r1"
153
 *
154
 * Only the specified hashes and curves will be allowed, and
155
 *  RSA keys of 2048 or more will be accepted, and DH key exchange
156
 *  with 1024-bit primes or more:
157
 * config="disallow=all allow=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024"
158
 *
159
 * A policy that enables the AES ciphersuites and the SECP256/384 curves:
160
 * config="allow=aes128-cbc:aes128-gcm:TLS1.0:TLS1.2:TLS1.1:HMAC-SHA1:SHA1:SHA256:SHA384:RSA:ECDHE-RSA:SECP256R1:SECP384R1"
161
 *
162
 * Disallow values are parsed first, then allow values, independent of the
163
 * order they appear.
164
 *
165
 * flags: turn on the following flags:
166
 *    policy-lock: turn off the ability for applications to change policy with
167
 *                 the call NSS_SetAlgorithmPolicy or the other system policy
168
 *                 calls (SSL_SetPolicy, etc.)
169
 *    ssl-lock:    turn off the ability to change the ssl defaults.
170
 *
171
 * The following only apply to ssl cipher suites (future smime)
172
 *
173
 * enable: turn on ciphersuites by default.
174
 * disable: turn off ciphersuites by default without disallowing them by policy.
175
 *
176
 *
177
 */
178
179
typedef struct {
180
    const char *name;
181
    unsigned name_size;
182
    SECOidTag oid;
183
    PRUint32 val;
184
} oidValDef;
185
186
typedef struct {
187
    const char *name;
188
    unsigned name_size;
189
    PRInt32 option;
190
} optionFreeDef;
191
192
typedef struct {
193
    const char *name;
194
    unsigned name_size;
195
    PRUint32 flag;
196
} policyFlagDef;
197
198
/*
199
 *  This table should be merged with the SECOID table.
200
 */
201
#define CIPHER_NAME(x) x, (sizeof(x) - 1)
202
static const oidValDef curveOptList[] = {
203
    /* Curves */
204
    { CIPHER_NAME("PRIME192V1"), SEC_OID_ANSIX962_EC_PRIME192V1,
205
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
206
    { CIPHER_NAME("PRIME192V2"), SEC_OID_ANSIX962_EC_PRIME192V2,
207
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
208
    { CIPHER_NAME("PRIME192V3"), SEC_OID_ANSIX962_EC_PRIME192V3,
209
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
210
    { CIPHER_NAME("PRIME239V1"), SEC_OID_ANSIX962_EC_PRIME239V1,
211
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
212
    { CIPHER_NAME("PRIME239V2"), SEC_OID_ANSIX962_EC_PRIME239V2,
213
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
214
    { CIPHER_NAME("PRIME239V3"), SEC_OID_ANSIX962_EC_PRIME239V3,
215
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
216
    { CIPHER_NAME("PRIME256V1"), SEC_OID_ANSIX962_EC_PRIME256V1,
217
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
218
    { CIPHER_NAME("SECP112R1"), SEC_OID_SECG_EC_SECP112R1,
219
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
220
    { CIPHER_NAME("SECP112R2"), SEC_OID_SECG_EC_SECP112R2,
221
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
222
    { CIPHER_NAME("SECP128R1"), SEC_OID_SECG_EC_SECP128R1,
223
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
224
    { CIPHER_NAME("SECP128R2"), SEC_OID_SECG_EC_SECP128R2,
225
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
226
    { CIPHER_NAME("SECP160K1"), SEC_OID_SECG_EC_SECP160K1,
227
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
228
    { CIPHER_NAME("SECP160R1"), SEC_OID_SECG_EC_SECP160R1,
229
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
230
    { CIPHER_NAME("SECP160R2"), SEC_OID_SECG_EC_SECP160R2,
231
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
232
    { CIPHER_NAME("SECP192K1"), SEC_OID_SECG_EC_SECP192K1,
233
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
234
    { CIPHER_NAME("SECP192R1"), SEC_OID_ANSIX962_EC_PRIME192V1,
235
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
236
    { CIPHER_NAME("SECP224K1"), SEC_OID_SECG_EC_SECP224K1,
237
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
238
    { CIPHER_NAME("SECP256K1"), SEC_OID_SECG_EC_SECP256K1,
239
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
240
    { CIPHER_NAME("SECP256R1"), SEC_OID_ANSIX962_EC_PRIME256V1,
241
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
242
    { CIPHER_NAME("SECP384R1"), SEC_OID_SECG_EC_SECP384R1,
243
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
244
    { CIPHER_NAME("SECP521R1"), SEC_OID_SECG_EC_SECP521R1,
245
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
246
    { CIPHER_NAME("CURVE25519"), SEC_OID_CURVE25519,
247
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
248
    { CIPHER_NAME("XYBER768D00"), SEC_OID_XYBER768D00, 0 },
249
    /* ANSI X9.62 named elliptic curves (characteristic two field) */
250
    { CIPHER_NAME("C2PNB163V1"), SEC_OID_ANSIX962_EC_C2PNB163V1,
251
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
252
    { CIPHER_NAME("C2PNB163V2"), SEC_OID_ANSIX962_EC_C2PNB163V2,
253
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
254
    { CIPHER_NAME("C2PNB163V3"), SEC_OID_ANSIX962_EC_C2PNB163V3,
255
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
256
    { CIPHER_NAME("C2PNB176V1"), SEC_OID_ANSIX962_EC_C2PNB176V1,
257
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
258
    { CIPHER_NAME("C2TNB191V1"), SEC_OID_ANSIX962_EC_C2TNB191V1,
259
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
260
    { CIPHER_NAME("C2TNB191V2"), SEC_OID_ANSIX962_EC_C2TNB191V2,
261
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
262
    { CIPHER_NAME("C2TNB191V3"), SEC_OID_ANSIX962_EC_C2TNB191V3,
263
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
264
    { CIPHER_NAME("C2ONB191V4"), SEC_OID_ANSIX962_EC_C2ONB191V4,
265
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
266
    { CIPHER_NAME("C2ONB191V5"), SEC_OID_ANSIX962_EC_C2ONB191V5,
267
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
268
    { CIPHER_NAME("C2PNB208W1"), SEC_OID_ANSIX962_EC_C2PNB208W1,
269
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
270
    { CIPHER_NAME("C2TNB239V1"), SEC_OID_ANSIX962_EC_C2TNB239V1,
271
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
272
    { CIPHER_NAME("C2TNB239V2"), SEC_OID_ANSIX962_EC_C2TNB239V2,
273
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
274
    { CIPHER_NAME("C2TNB239V3"), SEC_OID_ANSIX962_EC_C2TNB239V3,
275
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
276
    { CIPHER_NAME("C2ONB239V4"), SEC_OID_ANSIX962_EC_C2ONB239V4,
277
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
278
    { CIPHER_NAME("C2ONB239V5"), SEC_OID_ANSIX962_EC_C2ONB239V5,
279
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
280
    { CIPHER_NAME("C2PNB272W1"), SEC_OID_ANSIX962_EC_C2PNB272W1,
281
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
282
    { CIPHER_NAME("C2PNB304W1"), SEC_OID_ANSIX962_EC_C2PNB304W1,
283
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
284
    { CIPHER_NAME("C2TNB359V1"), SEC_OID_ANSIX962_EC_C2TNB359V1,
285
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
286
    { CIPHER_NAME("C2PNB368W1"), SEC_OID_ANSIX962_EC_C2PNB368W1,
287
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
288
    { CIPHER_NAME("C2TNB431R1"), SEC_OID_ANSIX962_EC_C2TNB431R1,
289
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
290
    /* SECG named elliptic curves (characteristic two field) */
291
    { CIPHER_NAME("SECT113R1"), SEC_OID_SECG_EC_SECT113R1,
292
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
293
    { CIPHER_NAME("SECT131R1"), SEC_OID_SECG_EC_SECT113R2,
294
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
295
    { CIPHER_NAME("SECT131R1"), SEC_OID_SECG_EC_SECT131R1,
296
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
297
    { CIPHER_NAME("SECT131R2"), SEC_OID_SECG_EC_SECT131R2,
298
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
299
    { CIPHER_NAME("SECT163K1"), SEC_OID_SECG_EC_SECT163K1,
300
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
301
    { CIPHER_NAME("SECT163R1"), SEC_OID_SECG_EC_SECT163R1,
302
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
303
    { CIPHER_NAME("SECT163R2"), SEC_OID_SECG_EC_SECT163R2,
304
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
305
    { CIPHER_NAME("SECT193R1"), SEC_OID_SECG_EC_SECT193R1,
306
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
307
    { CIPHER_NAME("SECT193R2"), SEC_OID_SECG_EC_SECT193R2,
308
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
309
    { CIPHER_NAME("SECT233K1"), SEC_OID_SECG_EC_SECT233K1,
310
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
311
    { CIPHER_NAME("SECT233R1"), SEC_OID_SECG_EC_SECT233R1,
312
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
313
    { CIPHER_NAME("SECT239K1"), SEC_OID_SECG_EC_SECT239K1,
314
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
315
    { CIPHER_NAME("SECT283K1"), SEC_OID_SECG_EC_SECT283K1,
316
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
317
    { CIPHER_NAME("SECT283R1"), SEC_OID_SECG_EC_SECT283R1,
318
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
319
    { CIPHER_NAME("SECT409K1"), SEC_OID_SECG_EC_SECT409K1,
320
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
321
    { CIPHER_NAME("SECT409R1"), SEC_OID_SECG_EC_SECT409R1,
322
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
323
    { CIPHER_NAME("SECT571K1"), SEC_OID_SECG_EC_SECT571K1,
324
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
325
    { CIPHER_NAME("SECT571R1"), SEC_OID_SECG_EC_SECT571R1,
326
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE },
327
};
328
329
static const oidValDef hashOptList[] = {
330
    /* Hashes */
331
    { CIPHER_NAME("MD2"), SEC_OID_MD2,
332
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
333
    { CIPHER_NAME("MD4"), SEC_OID_MD4,
334
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
335
    { CIPHER_NAME("MD5"), SEC_OID_MD5,
336
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
337
    { CIPHER_NAME("SHA1"), SEC_OID_SHA1,
338
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
339
    { CIPHER_NAME("SHA224"), SEC_OID_SHA224,
340
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
341
    { CIPHER_NAME("SHA256"), SEC_OID_SHA256,
342
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
343
    { CIPHER_NAME("SHA384"), SEC_OID_SHA384,
344
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
345
    { CIPHER_NAME("SHA512"), SEC_OID_SHA512,
346
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE }
347
};
348
349
static const oidValDef macOptList[] = {
350
    /* MACs */
351
    { CIPHER_NAME("HMAC-SHA1"), SEC_OID_HMAC_SHA1, NSS_USE_ALG_IN_SSL },
352
    { CIPHER_NAME("HMAC-SHA224"), SEC_OID_HMAC_SHA224, NSS_USE_ALG_IN_SSL },
353
    { CIPHER_NAME("HMAC-SHA256"), SEC_OID_HMAC_SHA256, NSS_USE_ALG_IN_SSL },
354
    { CIPHER_NAME("HMAC-SHA384"), SEC_OID_HMAC_SHA384, NSS_USE_ALG_IN_SSL },
355
    { CIPHER_NAME("HMAC-SHA512"), SEC_OID_HMAC_SHA512, NSS_USE_ALG_IN_SSL },
356
    { CIPHER_NAME("HMAC-MD5"), SEC_OID_HMAC_MD5, NSS_USE_ALG_IN_SSL },
357
};
358
359
static const oidValDef cipherOptList[] = {
360
    /* Ciphers */
361
    { CIPHER_NAME("AES128-CBC"), SEC_OID_AES_128_CBC, NSS_USE_ALG_IN_SSL },
362
    { CIPHER_NAME("AES192-CBC"), SEC_OID_AES_192_CBC, NSS_USE_ALG_IN_SSL },
363
    { CIPHER_NAME("AES256-CBC"), SEC_OID_AES_256_CBC, NSS_USE_ALG_IN_SSL },
364
    { CIPHER_NAME("AES128-GCM"), SEC_OID_AES_128_GCM, NSS_USE_ALG_IN_SSL },
365
    { CIPHER_NAME("AES192-GCM"), SEC_OID_AES_192_GCM, NSS_USE_ALG_IN_SSL },
366
    { CIPHER_NAME("AES256-GCM"), SEC_OID_AES_256_GCM, NSS_USE_ALG_IN_SSL },
367
    { CIPHER_NAME("CAMELLIA128-CBC"), SEC_OID_CAMELLIA_128_CBC, NSS_USE_ALG_IN_SSL },
368
    { CIPHER_NAME("CAMELLIA192-CBC"), SEC_OID_CAMELLIA_192_CBC, NSS_USE_ALG_IN_SSL },
369
    { CIPHER_NAME("CAMELLIA256-CBC"), SEC_OID_CAMELLIA_256_CBC, NSS_USE_ALG_IN_SSL },
370
    { CIPHER_NAME("CHACHA20-POLY1305"), SEC_OID_CHACHA20_POLY1305, NSS_USE_ALG_IN_SSL },
371
    { CIPHER_NAME("SEED-CBC"), SEC_OID_SEED_CBC, NSS_USE_ALG_IN_SSL },
372
    { CIPHER_NAME("DES-EDE3-CBC"), SEC_OID_DES_EDE3_CBC, NSS_USE_ALG_IN_SSL },
373
    { CIPHER_NAME("DES-40-CBC"), SEC_OID_DES_40_CBC, NSS_USE_ALG_IN_SSL },
374
    { CIPHER_NAME("DES-CBC"), SEC_OID_DES_CBC, NSS_USE_ALG_IN_SSL },
375
    { CIPHER_NAME("NULL-CIPHER"), SEC_OID_NULL_CIPHER, NSS_USE_ALG_IN_SSL },
376
    { CIPHER_NAME("RC2"), SEC_OID_RC2_CBC, NSS_USE_ALG_IN_SSL },
377
    { CIPHER_NAME("RC4"), SEC_OID_RC4, NSS_USE_ALG_IN_SSL },
378
    { CIPHER_NAME("IDEA"), SEC_OID_IDEA_CBC, NSS_USE_ALG_IN_SSL },
379
};
380
381
static const oidValDef kxOptList[] = {
382
    /* Key exchange */
383
    { CIPHER_NAME("RSA"), SEC_OID_TLS_RSA, NSS_USE_ALG_IN_SSL_KX },
384
    { CIPHER_NAME("RSA-EXPORT"), SEC_OID_TLS_RSA_EXPORT, NSS_USE_ALG_IN_SSL_KX },
385
    { CIPHER_NAME("DHE-RSA"), SEC_OID_TLS_DHE_RSA, NSS_USE_ALG_IN_SSL_KX },
386
    { CIPHER_NAME("DHE-DSS"), SEC_OID_TLS_DHE_DSS, NSS_USE_ALG_IN_SSL_KX },
387
    { CIPHER_NAME("DH-RSA"), SEC_OID_TLS_DH_RSA, NSS_USE_ALG_IN_SSL_KX },
388
    { CIPHER_NAME("DH-DSS"), SEC_OID_TLS_DH_DSS, NSS_USE_ALG_IN_SSL_KX },
389
    { CIPHER_NAME("ECDHE-ECDSA"), SEC_OID_TLS_ECDHE_ECDSA, NSS_USE_ALG_IN_SSL_KX },
390
    { CIPHER_NAME("ECDHE-RSA"), SEC_OID_TLS_ECDHE_RSA, NSS_USE_ALG_IN_SSL_KX },
391
    { CIPHER_NAME("ECDH-ECDSA"), SEC_OID_TLS_ECDH_ECDSA, NSS_USE_ALG_IN_SSL_KX },
392
    { CIPHER_NAME("ECDH-RSA"), SEC_OID_TLS_ECDH_RSA, NSS_USE_ALG_IN_SSL_KX },
393
};
394
395
static const oidValDef signOptList[] = {
396
    /* Signatures */
397
    { CIPHER_NAME("DSA"), SEC_OID_ANSIX9_DSA_SIGNATURE,
398
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
399
    { CIPHER_NAME("RSA-PKCS"), SEC_OID_PKCS1_RSA_ENCRYPTION,
400
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
401
    { CIPHER_NAME("RSA-PSS"), SEC_OID_PKCS1_RSA_PSS_SIGNATURE,
402
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
403
    { CIPHER_NAME("ECDSA"), SEC_OID_ANSIX962_EC_PUBLIC_KEY,
404
      NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_SIGNATURE },
405
    { CIPHER_NAME("ED25519"), SEC_OID_ED25519_PUBLIC_KEY,
406
      NSS_USE_ALG_IN_SIGNATURE },
407
};
408
409
typedef struct {
410
    const oidValDef *list;
411
    PRUint32 entries;
412
    const char *description;
413
    PRBool allowEmpty;
414
} algListsDef;
415
416
static const algListsDef algOptLists[] = {
417
    { curveOptList, PR_ARRAY_SIZE(curveOptList), "ECC", PR_FALSE },
418
    { hashOptList, PR_ARRAY_SIZE(hashOptList), "HASH", PR_FALSE },
419
    { macOptList, PR_ARRAY_SIZE(macOptList), "MAC", PR_FALSE },
420
    { cipherOptList, PR_ARRAY_SIZE(cipherOptList), "CIPHER", PR_FALSE },
421
    { kxOptList, PR_ARRAY_SIZE(kxOptList), "OTHER-KX", PR_FALSE },
422
    { signOptList, PR_ARRAY_SIZE(signOptList), "OTHER-SIGN", PR_FALSE },
423
};
424
425
static const optionFreeDef sslOptList[] = {
426
    /* Versions */
427
    { CIPHER_NAME("SSL2.0"), 0x002 },
428
    { CIPHER_NAME("SSL3.0"), 0x300 },
429
    { CIPHER_NAME("SSL3.1"), 0x301 },
430
    { CIPHER_NAME("TLS1.0"), 0x301 },
431
    { CIPHER_NAME("TLS1.1"), 0x302 },
432
    { CIPHER_NAME("TLS1.2"), 0x303 },
433
    { CIPHER_NAME("TLS1.3"), 0x304 },
434
    { CIPHER_NAME("DTLS1.0"), 0x302 },
435
    { CIPHER_NAME("DTLS1.1"), 0x302 },
436
    { CIPHER_NAME("DTLS1.2"), 0x303 },
437
    { CIPHER_NAME("DTLS1.3"), 0x304 },
438
};
439
440
static const optionFreeDef keySizeFlagsList[] = {
441
    { CIPHER_NAME("KEY-SIZE-SSL"), NSS_KEY_SIZE_POLICY_SSL_FLAG },
442
    { CIPHER_NAME("KEY-SIZE-SIGN"), NSS_KEY_SIZE_POLICY_SIGN_FLAG },
443
    { CIPHER_NAME("KEY-SIZE-VERIFY"), NSS_KEY_SIZE_POLICY_VERIFY_FLAG },
444
};
445
446
static const optionFreeDef freeOptList[] = {
447
448
    /* Restrictions for asymetric keys */
449
    { CIPHER_NAME("RSA-MIN"), NSS_RSA_MIN_KEY_SIZE },
450
    { CIPHER_NAME("DH-MIN"), NSS_DH_MIN_KEY_SIZE },
451
    { CIPHER_NAME("DSA-MIN"), NSS_DSA_MIN_KEY_SIZE },
452
    { CIPHER_NAME("ECC-MIN"), NSS_ECC_MIN_KEY_SIZE },
453
    /* what operations doe the key size apply to */
454
    { CIPHER_NAME("KEY-SIZE-FLAGS"), NSS_KEY_SIZE_POLICY_FLAGS },
455
    /* constraints on SSL Protocols */
456
    { CIPHER_NAME("TLS-VERSION-MIN"), NSS_TLS_VERSION_MIN_POLICY },
457
    { CIPHER_NAME("TLS-VERSION-MAX"), NSS_TLS_VERSION_MAX_POLICY },
458
    /* constraints on DTLS Protocols */
459
    { CIPHER_NAME("DTLS-VERSION-MIN"), NSS_DTLS_VERSION_MIN_POLICY },
460
    { CIPHER_NAME("DTLS-VERSION-MAX"), NSS_DTLS_VERSION_MAX_POLICY }
461
};
462
463
static const policyFlagDef policyFlagList[] = {
464
    { CIPHER_NAME("SSL"), NSS_USE_ALG_IN_SSL },
465
    { CIPHER_NAME("SSL-KEY-EXCHANGE"), NSS_USE_ALG_IN_SSL_KX },
466
    /* add other key exhanges in the future */
467
    { CIPHER_NAME("KEY-EXCHANGE"), NSS_USE_ALG_IN_SSL_KX },
468
    { CIPHER_NAME("CERT-SIGNATURE"), NSS_USE_ALG_IN_CERT_SIGNATURE },
469
    { CIPHER_NAME("CMS-SIGNATURE"), NSS_USE_ALG_IN_CMS_SIGNATURE },
470
    { CIPHER_NAME("ALL-SIGNATURE"), NSS_USE_ALG_IN_SIGNATURE },
471
    /* sign turns off all signatures, but doesn't change the
472
     * allowance for specific sigantures... for example:
473
     * disallow=sha256/all allow=sha256/signature doesn't allow
474
     * cert-sigantures, where disallow=sha256/all allow=sha256/all-signature
475
     * does.
476
     * however, disallow=sha356/signature and disallow=sha256/all-siganture are
477
     * equivalent in effect */
478
    { CIPHER_NAME("SIGNATURE"), NSS_USE_ALG_IN_ANY_SIGNATURE },
479
    /* enable/disable everything */
480
    { CIPHER_NAME("ALL"), NSS_USE_ALG_IN_SSL | NSS_USE_ALG_IN_SSL_KX |
481
                              NSS_USE_ALG_IN_SIGNATURE },
482
    { CIPHER_NAME("NONE"), 0 }
483
};
484
485
/*
486
 *  Get the next cipher on the list. point to the next one in 'next'.
487
 *  return the length;
488
 */
489
static const char *
490
secmod_ArgGetSubValue(const char *cipher, char sep1, char sep2,
491
                      int *len, const char **next)
492
0
{
493
0
    const char *start = cipher;
494
495
0
    if (start == NULL) {
496
0
        *len = 0;
497
0
        *next = NULL;
498
0
        return start;
499
0
    }
500
501
0
    for (; *cipher && *cipher != sep2; cipher++) {
502
0
        if (*cipher == sep1) {
503
0
            *next = cipher + 1;
504
0
            *len = cipher - start;
505
0
            return start;
506
0
        }
507
0
    }
508
0
    *next = NULL;
509
0
    *len = cipher - start;
510
0
    return start;
511
0
}
512
513
static PRUint32
514
secmod_parsePolicyValue(const char *policyFlags, int policyLength,
515
                        PRBool printPolicyFeedback, PRUint32 policyCheckFlags)
516
0
{
517
0
    const char *flag, *currentString;
518
0
    PRUint32 flags = 0;
519
0
    int i;
520
521
0
    for (currentString = policyFlags; currentString &&
522
0
                                      currentString < policyFlags + policyLength;) {
523
0
        int length;
524
0
        PRBool unknown = PR_TRUE;
525
0
        flag = secmod_ArgGetSubValue(currentString, ',', ':', &length,
526
0
                                     &currentString);
527
0
        if (length == 0) {
528
0
            continue;
529
0
        }
530
0
        for (i = 0; i < PR_ARRAY_SIZE(policyFlagList); i++) {
531
0
            const policyFlagDef *policy = &policyFlagList[i];
532
0
            unsigned name_size = policy->name_size;
533
0
            if ((policy->name_size == length) &&
534
0
                PORT_Strncasecmp(policy->name, flag, name_size) == 0) {
535
0
                flags |= policy->flag;
536
0
                unknown = PR_FALSE;
537
0
                break;
538
0
            }
539
0
        }
540
0
        if (unknown && printPolicyFeedback &&
541
0
            (policyCheckFlags & SECMOD_FLAG_POLICY_CHECK_VALUE)) {
542
0
            PR_SetEnv("NSS_POLICY_FAIL=1");
543
0
            fprintf(stderr, "NSS-POLICY-FAIL %.*s: unknown value: %.*s\n",
544
0
                    policyLength, policyFlags, length, flag);
545
0
        }
546
0
    }
547
0
    return flags;
548
0
}
549
550
/* allow symbolic names for values. The only ones currently defines or
551
 * SSL protocol versions. */
552
static SECStatus
553
secmod_getPolicyOptValue(const char *policyValue, int policyValueLength,
554
                         PRInt32 *result)
555
0
{
556
0
    PRInt32 val = atoi(policyValue);
557
0
    int i;
558
559
0
    if ((val != 0) || (*policyValue == '0')) {
560
0
        *result = val;
561
0
        return SECSuccess;
562
0
    }
563
    /* handle any ssl strings */
564
0
    for (i = 0; i < PR_ARRAY_SIZE(sslOptList); i++) {
565
0
        if (policyValueLength == sslOptList[i].name_size &&
566
0
            PORT_Strncasecmp(sslOptList[i].name, policyValue,
567
0
                             sslOptList[i].name_size) == 0) {
568
0
            *result = sslOptList[i].option;
569
0
            return SECSuccess;
570
0
        }
571
0
    }
572
    /* handle key_size flags. Each flag represents a bit, which
573
     * gets or'd together. They can be separated by , | or + */
574
0
    val = 0;
575
0
    while (*policyValue) {
576
0
        PRBool found = PR_FALSE;
577
0
        for (i = 0; i < PR_ARRAY_SIZE(keySizeFlagsList); i++) {
578
0
            if (PORT_Strncasecmp(keySizeFlagsList[i].name, policyValue,
579
0
                                 keySizeFlagsList[i].name_size) == 0) {
580
0
                val |= keySizeFlagsList[i].option;
581
0
                found = PR_TRUE;
582
0
                policyValue += keySizeFlagsList[i].name_size;
583
0
                break;
584
0
            }
585
0
        }
586
0
        if (!found) {
587
0
            return SECFailure;
588
0
        }
589
0
        if (*policyValue == ',' || *policyValue == '|' || *policyValue == '+') {
590
0
            policyValue++;
591
0
        }
592
0
    }
593
0
    *result = val;
594
0
    return SECSuccess;
595
0
}
596
597
/* Policy operations:
598
 *     Disallow: operation is disallowed by policy. Implies disabled.
599
 *     Allow: operation is allowed by policy (but could be disabled).
600
 *     Disable: operation is turned off by default (but could be allowed).
601
 *     Enable: operation is enabled by default. Implies allowed.
602
 */
603
typedef enum {
604
    NSS_DISALLOW,
605
    NSS_ALLOW,
606
    NSS_DISABLE,
607
    NSS_ENABLE
608
} NSSPolicyOperation;
609
610
/* apply the operator specific policy */
611
SECStatus
612
secmod_setPolicyOperation(SECOidTag oid, NSSPolicyOperation operation,
613
                          PRUint32 value)
614
0
{
615
0
    SECStatus rv = SECSuccess;
616
0
    switch (operation) {
617
0
        case NSS_DISALLOW:
618
            /* clear the requested policy bits */
619
0
            rv = NSS_SetAlgorithmPolicy(oid, 0, value);
620
0
            break;
621
0
        case NSS_ALLOW:
622
            /* set the requested policy bits */
623
0
            rv = NSS_SetAlgorithmPolicy(oid, value, 0);
624
0
            break;
625
        /* enable/disable only apply to SSL cipher suites (future S/MIME).
626
         * Enable/disable is implemented by clearing the DEFAULT_NOT_VALID
627
         * flag, then setting the NSS_USE_DEFAULT_SSL_ENABLE flag to the
628
         * correct value. The ssl policy code will then sort out what to
629
         * set based on ciphers and cipher suite values.*/
630
0
        case NSS_DISABLE:
631
0
            if (value & (NSS_USE_ALG_IN_SSL | NSS_USE_ALG_IN_SSL_KX)) {
632
                /* clear not valid and enable */
633
0
                rv = NSS_SetAlgorithmPolicy(oid, 0,
634
0
                                            NSS_USE_DEFAULT_NOT_VALID |
635
0
                                                NSS_USE_DEFAULT_SSL_ENABLE);
636
0
            }
637
0
            break;
638
0
        case NSS_ENABLE:
639
0
            if (value & (NSS_USE_ALG_IN_SSL | NSS_USE_ALG_IN_SSL_KX)) {
640
                /* set enable, clear not valid. NOTE: enable implies allow! */
641
0
                rv = NSS_SetAlgorithmPolicy(oid, value | NSS_USE_DEFAULT_SSL_ENABLE,
642
0
                                            NSS_USE_DEFAULT_NOT_VALID);
643
0
            }
644
0
            break;
645
0
        default:
646
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
647
0
            rv = SECFailure;
648
0
            break;
649
0
    }
650
0
    return rv;
651
0
}
652
653
const char *
654
secmod_getOperationString(NSSPolicyOperation operation)
655
0
{
656
0
    switch (operation) {
657
0
        case NSS_DISALLOW:
658
0
            return "disallow";
659
0
        case NSS_ALLOW:
660
0
            return "allow";
661
0
        case NSS_DISABLE:
662
0
            return "disable";
663
0
        case NSS_ENABLE:
664
0
            return "enable";
665
0
        default:
666
0
            break;
667
0
    }
668
0
    return "invalid";
669
0
}
670
671
static SECStatus
672
secmod_applyCryptoPolicy(const char *policyString, NSSPolicyOperation operation,
673
                         PRBool printPolicyFeedback, PRUint32 policyCheckFlags)
674
0
{
675
0
    const char *cipher, *currentString;
676
0
    unsigned i, j;
677
0
    SECStatus rv = SECSuccess;
678
0
    PRBool unknown;
679
680
0
    if (policyString == NULL || policyString[0] == 0) {
681
0
        return SECSuccess; /* do nothing */
682
0
    }
683
684
    /* if we change any of these, make sure it gets applied in ssl as well */
685
0
    NSS_SetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, NSS_USE_POLICY_IN_SSL, 0);
686
687
0
    for (currentString = policyString; currentString;) {
688
0
        int length;
689
0
        PRBool newValue = PR_FALSE;
690
691
0
        cipher = secmod_ArgGetSubValue(currentString, ':', 0, &length,
692
0
                                       &currentString);
693
0
        unknown = PR_TRUE;
694
0
        if (length >= 3 && cipher[3] == '/') {
695
0
            newValue = PR_TRUE;
696
0
        }
697
0
        if ((newValue || (length == 3)) && PORT_Strncasecmp(cipher, "all", 3) == 0) {
698
            /* disable or enable all options by default */
699
0
            PRUint32 value = 0;
700
0
            if (newValue) {
701
0
                value = secmod_parsePolicyValue(&cipher[3] + 1, length - 3 - 1, printPolicyFeedback, policyCheckFlags);
702
0
            }
703
0
            for (i = 0; i < PR_ARRAY_SIZE(algOptLists); i++) {
704
0
                const algListsDef *algOptList = &algOptLists[i];
705
0
                for (j = 0; j < algOptList->entries; j++) {
706
0
                    if (!newValue) {
707
0
                        value = algOptList->list[j].val;
708
0
                    }
709
0
                    secmod_setPolicyOperation(algOptList->list[j].oid, operation, value);
710
0
                }
711
0
            }
712
0
            continue;
713
0
        }
714
715
0
        for (i = 0; i < PR_ARRAY_SIZE(algOptLists); i++) {
716
0
            const algListsDef *algOptList = &algOptLists[i];
717
0
            for (j = 0; j < algOptList->entries; j++) {
718
0
                const oidValDef *algOpt = &algOptList->list[j];
719
0
                unsigned name_size = algOpt->name_size;
720
0
                PRBool newOption = PR_FALSE;
721
722
0
                if ((length >= name_size) && (cipher[name_size] == '/')) {
723
0
                    newOption = PR_TRUE;
724
0
                }
725
0
                if ((newOption || algOpt->name_size == length) &&
726
0
                    PORT_Strncasecmp(algOpt->name, cipher, name_size) == 0) {
727
0
                    PRUint32 value = algOpt->val;
728
0
                    if (newOption) {
729
0
                        value = secmod_parsePolicyValue(&cipher[name_size] + 1,
730
0
                                                        length - name_size - 1,
731
0
                                                        printPolicyFeedback,
732
0
                                                        policyCheckFlags);
733
0
                    }
734
0
                    rv = secmod_setPolicyOperation(algOptList->list[j].oid, operation, value);
735
0
                    if (rv != SECSuccess) {
736
                        /* could not enable option */
737
                        /* NSS_SetAlgorithPolicy should have set the error code */
738
0
                        return SECFailure;
739
0
                    }
740
0
                    unknown = PR_FALSE;
741
0
                    break;
742
0
                }
743
0
            }
744
0
        }
745
0
        if (!unknown) {
746
0
            continue;
747
0
        }
748
749
0
        for (i = 0; i < PR_ARRAY_SIZE(freeOptList); i++) {
750
0
            const optionFreeDef *freeOpt = &freeOptList[i];
751
0
            unsigned name_size = freeOpt->name_size;
752
753
0
            if ((length > name_size) && cipher[name_size] == '=' &&
754
0
                PORT_Strncasecmp(freeOpt->name, cipher, name_size) == 0) {
755
0
                PRInt32 val;
756
0
                const char *policyValue = &cipher[name_size + 1];
757
0
                int policyValueLength = length - name_size - 1;
758
0
                rv = secmod_getPolicyOptValue(policyValue, policyValueLength,
759
0
                                              &val);
760
0
                if (rv != SECSuccess) {
761
0
                    if (printPolicyFeedback &&
762
0
                        (policyCheckFlags & SECMOD_FLAG_POLICY_CHECK_VALUE)) {
763
0
                        PR_SetEnv("NSS_POLICY_FAIL=1");
764
0
                        fprintf(stderr, "NSS-POLICY-FAIL %.*s: unknown value: %.*s\n",
765
0
                                length, cipher, policyValueLength, policyValue);
766
0
                    }
767
0
                    return SECFailure;
768
0
                }
769
0
                rv = NSS_OptionSet(freeOpt->option, val);
770
0
                if (rv != SECSuccess) {
771
                    /* could not enable option */
772
                    /* NSS_OptionSet should have set the error code */
773
0
                    return SECFailure;
774
0
                }
775
                /* to allow the policy to expand in the future. ignore ciphers
776
                 * we don't understand */
777
0
                unknown = PR_FALSE;
778
0
                break;
779
0
            }
780
0
        }
781
782
0
        if (unknown && printPolicyFeedback &&
783
0
            (policyCheckFlags & SECMOD_FLAG_POLICY_CHECK_IDENTIFIER)) {
784
0
            PR_SetEnv("NSS_POLICY_FAIL=1");
785
0
            fprintf(stderr, "NSS-POLICY-FAIL %s: unknown identifier: %.*s\n",
786
0
                    secmod_getOperationString(operation), length, cipher);
787
0
        }
788
0
    }
789
0
    return rv;
790
0
}
791
792
static void
793
secmod_sanityCheckCryptoPolicy(void)
794
0
{
795
0
    unsigned i, j;
796
0
    SECStatus rv = SECSuccess;
797
0
    unsigned num_kx_enabled = 0;
798
0
    unsigned num_ssl_enabled = 0;
799
0
    unsigned num_sig_enabled = 0;
800
0
    unsigned enabledCount[PR_ARRAY_SIZE(algOptLists)];
801
0
    const char *sWarn = "WARN";
802
0
    const char *sInfo = "INFO";
803
0
    PRBool haveWarning = PR_FALSE;
804
805
0
    for (i = 0; i < PR_ARRAY_SIZE(algOptLists); i++) {
806
0
        const algListsDef *algOptList = &algOptLists[i];
807
0
        enabledCount[i] = 0;
808
0
        for (j = 0; j < algOptList->entries; j++) {
809
0
            const oidValDef *algOpt = &algOptList->list[j];
810
0
            PRUint32 value;
811
0
            PRBool anyEnabled = PR_FALSE;
812
0
            rv = NSS_GetAlgorithmPolicy(algOpt->oid, &value);
813
0
            if (rv != SECSuccess) {
814
0
                PR_SetEnv("NSS_POLICY_FAIL=1");
815
0
                fprintf(stderr, "NSS-POLICY-FAIL: internal failure with NSS_GetAlgorithmPolicy at %u\n", i);
816
0
                return;
817
0
            }
818
819
0
            if ((algOpt->val & NSS_USE_ALG_IN_SSL_KX) && (value & NSS_USE_ALG_IN_SSL_KX)) {
820
0
                ++num_kx_enabled;
821
0
                anyEnabled = PR_TRUE;
822
0
                fprintf(stderr, "NSS-POLICY-INFO: %s is enabled for KX\n", algOpt->name);
823
0
            }
824
0
            if ((algOpt->val & NSS_USE_ALG_IN_SSL) && (value & NSS_USE_ALG_IN_SSL)) {
825
0
                ++num_ssl_enabled;
826
0
                anyEnabled = PR_TRUE;
827
0
                fprintf(stderr, "NSS-POLICY-INFO: %s is enabled for SSL\n", algOpt->name);
828
0
            }
829
0
            if ((algOpt->val & NSS_USE_ALG_IN_CERT_SIGNATURE) &&
830
0
                ((value & NSS_USE_CERT_SIGNATURE_OK) == NSS_USE_CERT_SIGNATURE_OK)) {
831
0
                ++num_sig_enabled;
832
0
                anyEnabled = PR_TRUE;
833
0
                fprintf(stderr, "NSS-POLICY-INFO: %s is enabled for CERT-SIGNATURE\n", algOpt->name);
834
0
            }
835
0
            if (anyEnabled) {
836
0
                ++enabledCount[i];
837
0
            }
838
0
        }
839
0
    }
840
0
    fprintf(stderr, "NSS-POLICY-%s: NUMBER-OF-SSL-ALG-KX: %u\n", num_kx_enabled ? sInfo : sWarn, num_kx_enabled);
841
0
    fprintf(stderr, "NSS-POLICY-%s: NUMBER-OF-SSL-ALG: %u\n", num_ssl_enabled ? sInfo : sWarn, num_ssl_enabled);
842
0
    fprintf(stderr, "NSS-POLICY-%s: NUMBER-OF-CERT-SIG: %u\n", num_sig_enabled ? sInfo : sWarn, num_sig_enabled);
843
0
    if (!num_kx_enabled || !num_ssl_enabled || !num_sig_enabled) {
844
0
        haveWarning = PR_TRUE;
845
0
    }
846
0
    for (i = 0; i < PR_ARRAY_SIZE(algOptLists); i++) {
847
0
        const algListsDef *algOptList = &algOptLists[i];
848
0
        fprintf(stderr, "NSS-POLICY-%s: NUMBER-OF-%s: %u\n", enabledCount[i] ? sInfo : sWarn, algOptList->description, enabledCount[i]);
849
0
        if (!enabledCount[i] && !algOptList->allowEmpty) {
850
0
            haveWarning = PR_TRUE;
851
0
        }
852
0
    }
853
0
    if (haveWarning) {
854
0
        PR_SetEnv("NSS_POLICY_WARN=1");
855
0
    }
856
0
}
857
858
static SECStatus
859
secmod_parseCryptoPolicy(const char *policyConfig, PRBool printPolicyFeedback,
860
                         PRUint32 policyCheckFlags)
861
2
{
862
2
    char *args;
863
2
    SECStatus rv;
864
865
2
    if (policyConfig == NULL) {
866
2
        return SECSuccess; /* no policy given */
867
2
    }
868
    /* make sure we initialize the oid table and set all the default policy
869
     * values first so we can override them here */
870
0
    rv = SECOID_Init();
871
0
    if (rv != SECSuccess) {
872
0
        return rv;
873
0
    }
874
0
    args = NSSUTIL_ArgGetParamValue("disallow", policyConfig);
875
0
    rv = secmod_applyCryptoPolicy(args, NSS_DISALLOW, printPolicyFeedback,
876
0
                                  policyCheckFlags);
877
0
    if (args)
878
0
        PORT_Free(args);
879
0
    if (rv != SECSuccess) {
880
0
        return rv;
881
0
    }
882
0
    args = NSSUTIL_ArgGetParamValue("allow", policyConfig);
883
0
    rv = secmod_applyCryptoPolicy(args, NSS_ALLOW, printPolicyFeedback,
884
0
                                  policyCheckFlags);
885
0
    if (args)
886
0
        PORT_Free(args);
887
0
    if (rv != SECSuccess) {
888
0
        return rv;
889
0
    }
890
0
    args = NSSUTIL_ArgGetParamValue("disable", policyConfig);
891
0
    rv = secmod_applyCryptoPolicy(args, NSS_DISABLE, printPolicyFeedback,
892
0
                                  policyCheckFlags);
893
0
    if (args)
894
0
        PORT_Free(args);
895
0
    if (rv != SECSuccess) {
896
0
        return rv;
897
0
    }
898
0
    args = NSSUTIL_ArgGetParamValue("enable", policyConfig);
899
0
    rv = secmod_applyCryptoPolicy(args, NSS_ENABLE, printPolicyFeedback,
900
0
                                  policyCheckFlags);
901
0
    if (args)
902
0
        PORT_Free(args);
903
0
    if (rv != SECSuccess) {
904
0
        return rv;
905
0
    }
906
    /* this has to be last. Everything after this will be a noop */
907
0
    if (NSSUTIL_ArgHasFlag("flags", "ssl-lock", policyConfig)) {
908
0
        PRInt32 locks;
909
        /* don't overwrite other (future) lock flags */
910
0
        rv = NSS_OptionGet(NSS_DEFAULT_LOCKS, &locks);
911
0
        if (rv == SECSuccess) {
912
0
            rv = NSS_OptionSet(NSS_DEFAULT_LOCKS, locks | NSS_DEFAULT_SSL_LOCK);
913
0
        }
914
0
        if (rv != SECSuccess) {
915
0
            return rv;
916
0
        }
917
0
    }
918
0
    if (NSSUTIL_ArgHasFlag("flags", "policy-lock", policyConfig)) {
919
0
        NSS_LockPolicy();
920
0
    }
921
0
    if (printPolicyFeedback) {
922
        /* This helps to distinguish configurations that don't contain any
923
         * policy config= statement. */
924
0
        PR_SetEnv("NSS_POLICY_LOADED=1");
925
0
        fprintf(stderr, "NSS-POLICY-INFO: LOADED-SUCCESSFULLY\n");
926
0
        secmod_sanityCheckCryptoPolicy();
927
0
    }
928
0
    return rv;
929
0
}
930
931
static PRUint32
932
secmod_parsePolicyCheckFlags(const char *nss)
933
4
{
934
4
    PRUint32 policyCheckFlags = 0;
935
936
4
    if (NSSUTIL_ArgHasFlag("flags", "policyCheckIdentifier", nss)) {
937
0
        policyCheckFlags |= SECMOD_FLAG_POLICY_CHECK_IDENTIFIER;
938
0
    }
939
940
4
    if (NSSUTIL_ArgHasFlag("flags", "policyCheckValue", nss)) {
941
0
        policyCheckFlags |= SECMOD_FLAG_POLICY_CHECK_VALUE;
942
0
    }
943
944
4
    return policyCheckFlags;
945
4
}
946
947
/*
948
 * for 3.4 we continue to use the old SECMODModule structure
949
 */
950
SECMODModule *
951
SECMOD_CreateModuleEx(const char *library, const char *moduleName,
952
                      const char *parameters, const char *nss,
953
                      const char *config)
954
2
{
955
2
    SECMODModule *mod;
956
2
    SECStatus rv;
957
2
    char *slotParams, *ciphers;
958
2
    PRBool printPolicyFeedback = NSSUTIL_ArgHasFlag("flags", "printPolicyFeedback", nss);
959
2
    PRUint32 policyCheckFlags = secmod_parsePolicyCheckFlags(nss);
960
961
2
    rv = secmod_parseCryptoPolicy(config, printPolicyFeedback, policyCheckFlags);
962
963
    /* do not load the module if policy parsing fails */
964
2
    if (rv != SECSuccess) {
965
0
        if (printPolicyFeedback) {
966
0
            PR_SetEnv("NSS_POLICY_FAIL=1");
967
0
            fprintf(stderr, "NSS-POLICY-FAIL: policy config parsing failed, not loading module %s\n", moduleName);
968
0
        }
969
0
        return NULL;
970
0
    }
971
972
2
    mod = secmod_NewModule();
973
2
    if (mod == NULL)
974
0
        return NULL;
975
976
2
    mod->commonName = PORT_ArenaStrdup(mod->arena, moduleName ? moduleName : "");
977
2
    if (library) {
978
0
        mod->dllName = PORT_ArenaStrdup(mod->arena, library);
979
0
    }
980
    /* new field */
981
2
    if (parameters) {
982
2
        mod->libraryParams = PORT_ArenaStrdup(mod->arena, parameters);
983
2
    }
984
985
2
    mod->internal = NSSUTIL_ArgHasFlag("flags", "internal", nss);
986
2
    mod->isFIPS = NSSUTIL_ArgHasFlag("flags", "FIPS", nss);
987
    /* if the system FIPS mode is enabled, force FIPS to be on */
988
2
    if (SECMOD_GetSystemFIPSEnabled()) {
989
0
        mod->isFIPS = PR_TRUE;
990
0
    }
991
2
    mod->isCritical = NSSUTIL_ArgHasFlag("flags", "critical", nss);
992
2
    slotParams = NSSUTIL_ArgGetParamValue("slotParams", nss);
993
2
    mod->slotInfo = NSSUTIL_ArgParseSlotInfo(mod->arena, slotParams,
994
2
                                             &mod->slotInfoCount);
995
2
    if (slotParams)
996
1
        PORT_Free(slotParams);
997
    /* new field */
998
2
    mod->trustOrder = NSSUTIL_ArgReadLong("trustOrder", nss,
999
2
                                          NSSUTIL_DEFAULT_TRUST_ORDER, NULL);
1000
    /* new field */
1001
2
    mod->cipherOrder = NSSUTIL_ArgReadLong("cipherOrder", nss,
1002
2
                                           NSSUTIL_DEFAULT_CIPHER_ORDER, NULL);
1003
    /* new field */
1004
2
    mod->isModuleDB = NSSUTIL_ArgHasFlag("flags", "moduleDB", nss);
1005
2
    mod->moduleDBOnly = NSSUTIL_ArgHasFlag("flags", "moduleDBOnly", nss);
1006
2
    if (mod->moduleDBOnly)
1007
1
        mod->isModuleDB = PR_TRUE;
1008
1009
    /* we need more bits, but we also want to preserve binary compatibility
1010
     * so we overload the isModuleDB PRBool with additional flags.
1011
     * These flags are only valid if mod->isModuleDB is already set.
1012
     * NOTE: this depends on the fact that PRBool is at least a char on
1013
     * all platforms. These flags are only valid if moduleDB is set, so
1014
     * code checking if (mod->isModuleDB) will continue to work correctly. */
1015
2
    if (mod->isModuleDB) {
1016
1
        char flags = SECMOD_FLAG_MODULE_DB_IS_MODULE_DB;
1017
1
        if (NSSUTIL_ArgHasFlag("flags", "skipFirst", nss)) {
1018
0
            flags |= SECMOD_FLAG_MODULE_DB_SKIP_FIRST;
1019
0
        }
1020
1
        if (NSSUTIL_ArgHasFlag("flags", "defaultModDB", nss)) {
1021
1
            flags |= SECMOD_FLAG_MODULE_DB_DEFAULT_MODDB;
1022
1
        }
1023
1
        if (NSSUTIL_ArgHasFlag("flags", "policyOnly", nss)) {
1024
0
            flags |= SECMOD_FLAG_MODULE_DB_POLICY_ONLY;
1025
0
        }
1026
        /* additional moduleDB flags could be added here in the future */
1027
1
        mod->isModuleDB = (PRBool)flags;
1028
1
    }
1029
1030
2
    if (mod->internal) {
1031
2
        char flags = SECMOD_FLAG_INTERNAL_IS_INTERNAL;
1032
1033
2
        if (NSSUTIL_ArgHasFlag("flags", "internalKeySlot", nss)) {
1034
1
            flags |= SECMOD_FLAG_INTERNAL_KEY_SLOT;
1035
1
        }
1036
2
        mod->internal = (PRBool)flags;
1037
2
    }
1038
1039
2
    ciphers = NSSUTIL_ArgGetParamValue("ciphers", nss);
1040
2
    NSSUTIL_ArgParseCipherFlags(&mod->ssl[0], ciphers);
1041
2
    if (ciphers)
1042
0
        PORT_Free(ciphers);
1043
1044
2
    secmod_PrivateModuleCount++;
1045
1046
2
    return mod;
1047
2
}
1048
1049
PRBool
1050
SECMOD_GetSkipFirstFlag(SECMODModule *mod)
1051
1
{
1052
1
    char flags = (char)mod->isModuleDB;
1053
1054
1
    return (flags & SECMOD_FLAG_MODULE_DB_SKIP_FIRST) ? PR_TRUE : PR_FALSE;
1055
1
}
1056
1057
PRBool
1058
SECMOD_GetDefaultModDBFlag(SECMODModule *mod)
1059
0
{
1060
0
    char flags = (char)mod->isModuleDB;
1061
1062
0
    return (flags & SECMOD_FLAG_MODULE_DB_DEFAULT_MODDB) ? PR_TRUE : PR_FALSE;
1063
0
}
1064
1065
PRBool
1066
secmod_PolicyOnly(SECMODModule *mod)
1067
2
{
1068
2
    char flags = (char)mod->isModuleDB;
1069
1070
2
    return (flags & SECMOD_FLAG_MODULE_DB_POLICY_ONLY) ? PR_TRUE : PR_FALSE;
1071
2
}
1072
1073
PRBool
1074
secmod_IsInternalKeySlot(SECMODModule *mod)
1075
3
{
1076
3
    char flags = (char)mod->internal;
1077
1078
3
    return (flags & SECMOD_FLAG_INTERNAL_KEY_SLOT) ? PR_TRUE : PR_FALSE;
1079
3
}
1080
1081
void
1082
secmod_SetInternalKeySlotFlag(SECMODModule *mod, PRBool val)
1083
0
{
1084
0
    char flags = (char)mod->internal;
1085
1086
0
    if (val) {
1087
0
        flags |= SECMOD_FLAG_INTERNAL_KEY_SLOT;
1088
0
    } else {
1089
0
        flags &= ~SECMOD_FLAG_INTERNAL_KEY_SLOT;
1090
0
    }
1091
0
    mod->internal = flags;
1092
0
}
1093
1094
/*
1095
 * copy desc and value into target. Target is known to be big enough to
1096
 * hold desc +2 +value, which is good because the result of this will be
1097
 * *desc"*value". We may, however, have to add some escapes for special
1098
 * characters imbedded into value (rare). This string potentially comes from
1099
 * a user, so we don't want the user overflowing the target buffer by using
1100
 * excessive escapes. To prevent this we count the escapes we need to add and
1101
 * try to expand the buffer with Realloc.
1102
 */
1103
static char *
1104
secmod_doDescCopy(char *target, char **base, int *baseLen,
1105
                  const char *desc, int descLen, char *value)
1106
0
{
1107
0
    int diff, esc_len;
1108
1109
0
    esc_len = NSSUTIL_EscapeSize(value, '\"') - 1;
1110
0
    diff = esc_len - strlen(value);
1111
0
    if (diff > 0) {
1112
        /* we need to escape... expand newSpecPtr as well to make sure
1113
         * we don't overflow it */
1114
0
        int offset = target - *base;
1115
0
        char *newPtr = PORT_Realloc(*base, *baseLen + diff);
1116
0
        if (!newPtr) {
1117
0
            return target; /* not enough space, just drop the whole copy */
1118
0
        }
1119
0
        *baseLen += diff;
1120
0
        target = newPtr + offset;
1121
0
        *base = newPtr;
1122
0
        value = NSSUTIL_Escape(value, '\"');
1123
0
        if (value == NULL) {
1124
0
            return target; /* couldn't escape value, just drop the copy */
1125
0
        }
1126
0
    }
1127
0
    PORT_Memcpy(target, desc, descLen);
1128
0
    target += descLen;
1129
0
    *target++ = '\"';
1130
0
    PORT_Memcpy(target, value, esc_len);
1131
0
    target += esc_len;
1132
0
    *target++ = '\"';
1133
0
    if (diff > 0) {
1134
0
        PORT_Free(value);
1135
0
    }
1136
0
    return target;
1137
0
}
1138
1139
#define SECMOD_SPEC_COPY(new, start, end) \
1140
0
    if (end > start) {                    \
1141
0
        int _cnt = end - start;           \
1142
0
        PORT_Memcpy(new, start, _cnt);    \
1143
0
        new += _cnt;                      \
1144
0
    }
1145
#define SECMOD_TOKEN_DESCRIPTION "tokenDescription="
1146
#define SECMOD_SLOT_DESCRIPTION "slotDescription="
1147
1148
/*
1149
 * Find any tokens= values in the module spec.
1150
 * Always return a new spec which does not have any tokens= arguments.
1151
 * If tokens= arguments are found, Split the the various tokens defined into
1152
 * an array of child specs to return.
1153
 *
1154
 * Caller is responsible for freeing the child spec and the new token
1155
 * spec.
1156
 */
1157
char *
1158
secmod_ParseModuleSpecForTokens(PRBool convert, PRBool isFIPS,
1159
                                const char *moduleSpec, char ***children,
1160
                                CK_SLOT_ID **ids)
1161
0
{
1162
0
    int newSpecLen = PORT_Strlen(moduleSpec) + 2;
1163
0
    char *newSpec = PORT_Alloc(newSpecLen);
1164
0
    char *newSpecPtr = newSpec;
1165
0
    const char *modulePrev = moduleSpec;
1166
0
    char *target = NULL;
1167
0
    char *tmp = NULL;
1168
0
    char **childArray = NULL;
1169
0
    const char *tokenIndex;
1170
0
    CK_SLOT_ID *idArray = NULL;
1171
0
    int tokenCount = 0;
1172
0
    int i;
1173
1174
0
    if (newSpec == NULL) {
1175
0
        return NULL;
1176
0
    }
1177
1178
0
    *children = NULL;
1179
0
    if (ids) {
1180
0
        *ids = NULL;
1181
0
    }
1182
0
    moduleSpec = NSSUTIL_ArgStrip(moduleSpec);
1183
0
    SECMOD_SPEC_COPY(newSpecPtr, modulePrev, moduleSpec);
1184
1185
    /* Notes on 'convert' and 'isFIPS' flags: The base parameters for opening
1186
     * a new softoken module takes the following parameters to name the
1187
     * various tokens:
1188
     *
1189
     *  cryptoTokenDescription: name of the non-fips crypto token.
1190
     *  cryptoSlotDescription: name of the non-fips crypto slot.
1191
     *  dbTokenDescription: name of the non-fips db token.
1192
     *  dbSlotDescription: name of the non-fips db slot.
1193
     *  FIPSTokenDescription: name of the fips db/crypto token.
1194
     *  FIPSSlotDescription: name of the fips db/crypto slot.
1195
     *
1196
     * if we are opening a new slot, we need to have the following
1197
     * parameters:
1198
     *  tokenDescription: name of the token.
1199
     *  slotDescription: name of the slot.
1200
     *
1201
     *
1202
     * The convert flag tells us to drop the unnecessary *TokenDescription
1203
     * and *SlotDescription arguments and convert the appropriate pair
1204
     * (either db or FIPS based on the isFIPS flag) to tokenDescription and
1205
     * slotDescription).
1206
     */
1207
    /*
1208
     * walk down the list. if we find a tokens= argument, save it,
1209
     * otherise copy the argument.
1210
     */
1211
0
    while (*moduleSpec) {
1212
0
        int next;
1213
0
        modulePrev = moduleSpec;
1214
0
        NSSUTIL_HANDLE_STRING_ARG(moduleSpec, target, "tokens=",
1215
0
                                  modulePrev = moduleSpec;
1216
0
                                  /* skip copying */)
1217
0
        NSSUTIL_HANDLE_STRING_ARG(
1218
0
            moduleSpec, tmp, "cryptoTokenDescription=",
1219
0
            if (convert) { modulePrev = moduleSpec; })
1220
0
        NSSUTIL_HANDLE_STRING_ARG(
1221
0
            moduleSpec, tmp, "cryptoSlotDescription=",
1222
0
            if (convert) { modulePrev = moduleSpec; })
1223
0
        NSSUTIL_HANDLE_STRING_ARG(
1224
0
            moduleSpec, tmp, "dbTokenDescription=",
1225
0
            if (convert) {
1226
0
                modulePrev = moduleSpec;
1227
0
                if (!isFIPS) {
1228
0
                    newSpecPtr = secmod_doDescCopy(newSpecPtr,
1229
0
                                                   &newSpec, &newSpecLen,
1230
0
                                                   SECMOD_TOKEN_DESCRIPTION,
1231
0
                                                   sizeof(SECMOD_TOKEN_DESCRIPTION) - 1,
1232
0
                                                   tmp);
1233
0
                }
1234
0
            })
1235
0
        NSSUTIL_HANDLE_STRING_ARG(
1236
0
            moduleSpec, tmp, "dbSlotDescription=",
1237
0
            if (convert) {
1238
0
                modulePrev = moduleSpec; /* skip copying */
1239
0
                if (!isFIPS) {
1240
0
                    newSpecPtr = secmod_doDescCopy(newSpecPtr,
1241
0
                                                   &newSpec, &newSpecLen,
1242
0
                                                   SECMOD_SLOT_DESCRIPTION,
1243
0
                                                   sizeof(SECMOD_SLOT_DESCRIPTION) - 1,
1244
0
                                                   tmp);
1245
0
                }
1246
0
            })
1247
0
        NSSUTIL_HANDLE_STRING_ARG(
1248
0
            moduleSpec, tmp, "FIPSTokenDescription=",
1249
0
            if (convert) {
1250
0
                modulePrev = moduleSpec; /* skip copying */
1251
0
                if (isFIPS) {
1252
0
                    newSpecPtr = secmod_doDescCopy(newSpecPtr,
1253
0
                                                   &newSpec, &newSpecLen,
1254
0
                                                   SECMOD_TOKEN_DESCRIPTION,
1255
0
                                                   sizeof(SECMOD_TOKEN_DESCRIPTION) - 1,
1256
0
                                                   tmp);
1257
0
                }
1258
0
            })
1259
0
        NSSUTIL_HANDLE_STRING_ARG(
1260
0
            moduleSpec, tmp, "FIPSSlotDescription=",
1261
0
            if (convert) {
1262
0
                modulePrev = moduleSpec; /* skip copying */
1263
0
                if (isFIPS) {
1264
0
                    newSpecPtr = secmod_doDescCopy(newSpecPtr,
1265
0
                                                   &newSpec, &newSpecLen,
1266
0
                                                   SECMOD_SLOT_DESCRIPTION,
1267
0
                                                   sizeof(SECMOD_SLOT_DESCRIPTION) - 1,
1268
0
                                                   tmp);
1269
0
                }
1270
0
            })
1271
0
        NSSUTIL_HANDLE_FINAL_ARG(moduleSpec)
1272
0
        SECMOD_SPEC_COPY(newSpecPtr, modulePrev, moduleSpec);
1273
0
    }
1274
0
    if (tmp) {
1275
0
        PORT_Free(tmp);
1276
0
        tmp = NULL;
1277
0
    }
1278
0
    *newSpecPtr = 0;
1279
1280
    /* no target found, return the newSpec */
1281
0
    if (target == NULL) {
1282
0
        return newSpec;
1283
0
    }
1284
1285
    /* now build the child array from target */
1286
    /*first count them */
1287
0
    for (tokenIndex = NSSUTIL_ArgStrip(target); *tokenIndex;
1288
0
         tokenIndex = NSSUTIL_ArgStrip(NSSUTIL_ArgSkipParameter(tokenIndex))) {
1289
0
        tokenCount++;
1290
0
    }
1291
1292
0
    childArray = PORT_NewArray(char *, tokenCount + 1);
1293
0
    if (childArray == NULL) {
1294
        /* just return the spec as is then */
1295
0
        PORT_Free(target);
1296
0
        return newSpec;
1297
0
    }
1298
0
    if (ids) {
1299
0
        idArray = PORT_NewArray(CK_SLOT_ID, tokenCount + 1);
1300
0
        if (idArray == NULL) {
1301
0
            PORT_Free(childArray);
1302
0
            PORT_Free(target);
1303
0
            return newSpec;
1304
0
        }
1305
0
    }
1306
1307
    /* now fill them in */
1308
0
    for (tokenIndex = NSSUTIL_ArgStrip(target), i = 0;
1309
0
         *tokenIndex && (i < tokenCount);
1310
0
         tokenIndex = NSSUTIL_ArgStrip(tokenIndex)) {
1311
0
        int next;
1312
0
        char *name = NSSUTIL_ArgGetLabel(tokenIndex, &next);
1313
0
        tokenIndex += next;
1314
1315
0
        if (idArray) {
1316
0
            idArray[i] = NSSUTIL_ArgDecodeNumber(name);
1317
0
        }
1318
1319
0
        PORT_Free(name); /* drop the explicit number */
1320
1321
        /* if anything is left, copy the args to the child array */
1322
0
        if (!NSSUTIL_ArgIsBlank(*tokenIndex)) {
1323
0
            childArray[i++] = NSSUTIL_ArgFetchValue(tokenIndex, &next);
1324
0
            tokenIndex += next;
1325
0
        }
1326
0
    }
1327
1328
0
    PORT_Free(target);
1329
0
    childArray[i] = 0;
1330
0
    if (idArray) {
1331
0
        idArray[i] = 0;
1332
0
    }
1333
1334
    /* return it */
1335
0
    *children = childArray;
1336
0
    if (ids) {
1337
0
        *ids = idArray;
1338
0
    }
1339
0
    return newSpec;
1340
0
}
1341
1342
/* get the database and flags from the spec */
1343
static char *
1344
secmod_getConfigDir(const char *spec, char **certPrefix, char **keyPrefix,
1345
                    PRBool *readOnly)
1346
0
{
1347
0
    char *config = NULL;
1348
1349
0
    *certPrefix = NULL;
1350
0
    *keyPrefix = NULL;
1351
0
    *readOnly = NSSUTIL_ArgHasFlag("flags", "readOnly", spec);
1352
0
    if (NSSUTIL_ArgHasFlag("flags", "nocertdb", spec) ||
1353
0
        NSSUTIL_ArgHasFlag("flags", "nokeydb", spec)) {
1354
0
        return NULL;
1355
0
    }
1356
1357
0
    spec = NSSUTIL_ArgStrip(spec);
1358
0
    while (*spec) {
1359
0
        int next;
1360
0
        NSSUTIL_HANDLE_STRING_ARG(spec, config, "configdir=", ;)
1361
0
        NSSUTIL_HANDLE_STRING_ARG(spec, *certPrefix, "certPrefix=", ;)
1362
0
        NSSUTIL_HANDLE_STRING_ARG(spec, *keyPrefix, "keyPrefix=", ;)
1363
0
        NSSUTIL_HANDLE_FINAL_ARG(spec)
1364
0
    }
1365
0
    return config;
1366
0
}
1367
1368
struct SECMODConfigListStr {
1369
    char *config;
1370
    char *certPrefix;
1371
    char *keyPrefix;
1372
    PRBool isReadOnly;
1373
};
1374
1375
/*
1376
 * return an array of already openned databases from a spec list.
1377
 */
1378
SECMODConfigList *
1379
secmod_GetConfigList(PRBool isFIPS, char *spec, int *count)
1380
0
{
1381
0
    char **children;
1382
0
    CK_SLOT_ID *ids;
1383
0
    char *strippedSpec;
1384
0
    int childCount;
1385
0
    SECMODConfigList *conflist = NULL;
1386
0
    int i;
1387
1388
0
    strippedSpec = secmod_ParseModuleSpecForTokens(PR_TRUE, isFIPS,
1389
0
                                                   spec, &children, &ids);
1390
0
    if (strippedSpec == NULL) {
1391
0
        return NULL;
1392
0
    }
1393
1394
0
    for (childCount = 0; children && children[childCount]; childCount++)
1395
0
        ;
1396
0
    *count = childCount + 1; /* include strippedSpec */
1397
0
    conflist = PORT_NewArray(SECMODConfigList, *count);
1398
0
    if (conflist == NULL) {
1399
0
        *count = 0;
1400
0
        goto loser;
1401
0
    }
1402
1403
0
    conflist[0].config = secmod_getConfigDir(strippedSpec,
1404
0
                                             &conflist[0].certPrefix,
1405
0
                                             &conflist[0].keyPrefix,
1406
0
                                             &conflist[0].isReadOnly);
1407
0
    for (i = 0; i < childCount; i++) {
1408
0
        conflist[i + 1].config = secmod_getConfigDir(children[i],
1409
0
                                                     &conflist[i + 1].certPrefix,
1410
0
                                                     &conflist[i + 1].keyPrefix,
1411
0
                                                     &conflist[i + 1].isReadOnly);
1412
0
    }
1413
1414
0
loser:
1415
0
    secmod_FreeChildren(children, ids);
1416
0
    PORT_Free(strippedSpec);
1417
0
    return conflist;
1418
0
}
1419
1420
/*
1421
 * determine if we are trying to open an old dbm database. For this test
1422
 * RDB databases should return PR_FALSE.
1423
 */
1424
static PRBool
1425
secmod_configIsDBM(char *configDir)
1426
0
{
1427
0
    char *env;
1428
1429
    /* explicit dbm open */
1430
0
    if (strncmp(configDir, "dbm:", 4) == 0) {
1431
0
        return PR_TRUE;
1432
0
    }
1433
    /* explicit open of a non-dbm database */
1434
0
    if ((strncmp(configDir, "sql:", 4) == 0) ||
1435
0
        (strncmp(configDir, "rdb:", 4) == 0) ||
1436
0
        (strncmp(configDir, "extern:", 7) == 0)) {
1437
0
        return PR_FALSE;
1438
0
    }
1439
0
    env = PR_GetEnvSecure("NSS_DEFAULT_DB_TYPE");
1440
    /* implicit dbm open */
1441
0
    if ((env == NULL) || (strcmp(env, "dbm") == 0)) {
1442
0
        return PR_TRUE;
1443
0
    }
1444
    /* implicit non-dbm open */
1445
0
    return PR_FALSE;
1446
0
}
1447
1448
/*
1449
 * match two prefixes. prefix may be NULL. NULL patches '\0'
1450
 */
1451
static PRBool
1452
secmod_matchPrefix(char *prefix1, char *prefix2)
1453
0
{
1454
0
    if ((prefix1 == NULL) || (*prefix1 == 0)) {
1455
0
        if ((prefix2 == NULL) || (*prefix2 == 0)) {
1456
0
            return PR_TRUE;
1457
0
        }
1458
0
        return PR_FALSE;
1459
0
    }
1460
0
    if (strcmp(prefix1, prefix2) == 0) {
1461
0
        return PR_TRUE;
1462
0
    }
1463
0
    return PR_FALSE;
1464
0
}
1465
1466
/* do two config paramters match? Not all callers are compariing
1467
 * SECMODConfigLists directly, so this function breaks them out to their
1468
 * components. */
1469
static PRBool
1470
secmod_matchConfig(char *configDir1, char *configDir2,
1471
                   char *certPrefix1, char *certPrefix2,
1472
                   char *keyPrefix1, char *keyPrefix2,
1473
                   PRBool isReadOnly1, PRBool isReadOnly2)
1474
0
{
1475
    /* TODO: Document the answer to the question:
1476
     *       "Why not allow them to match if they are both NULL?"
1477
     * See: https://bugzilla.mozilla.org/show_bug.cgi?id=1318633#c1
1478
     */
1479
0
    if ((configDir1 == NULL) || (configDir2 == NULL)) {
1480
0
        return PR_FALSE;
1481
0
    }
1482
0
    if (strcmp(configDir1, configDir2) != 0) {
1483
0
        return PR_FALSE;
1484
0
    }
1485
0
    if (!secmod_matchPrefix(certPrefix1, certPrefix2)) {
1486
0
        return PR_FALSE;
1487
0
    }
1488
0
    if (!secmod_matchPrefix(keyPrefix1, keyPrefix2)) {
1489
0
        return PR_FALSE;
1490
0
    }
1491
    /* these last test -- if we just need the DB open read only,
1492
     * than any open will suffice, but if we requested it read/write
1493
     * and it's only open read only, we need to open it again */
1494
0
    if (isReadOnly1) {
1495
0
        return PR_TRUE;
1496
0
    }
1497
0
    if (isReadOnly2) { /* isReadonly1 == PR_FALSE */
1498
0
        return PR_FALSE;
1499
0
    }
1500
0
    return PR_TRUE;
1501
0
}
1502
1503
/*
1504
 * return true if we are requesting a database that is already openned.
1505
 */
1506
PRBool
1507
secmod_MatchConfigList(const char *spec, SECMODConfigList *conflist, int count)
1508
0
{
1509
0
    char *config;
1510
0
    char *certPrefix;
1511
0
    char *keyPrefix;
1512
0
    PRBool isReadOnly;
1513
0
    PRBool ret = PR_FALSE;
1514
0
    int i;
1515
1516
0
    config = secmod_getConfigDir(spec, &certPrefix, &keyPrefix, &isReadOnly);
1517
0
    if (!config) {
1518
0
        goto done;
1519
0
    }
1520
1521
    /* NOTE: we dbm isn't multiple open safe. If we open the same database
1522
     * twice from two different locations, then we can corrupt our database
1523
     * (the cache will be inconsistent). Protect against this by claiming
1524
     * for comparison only that we are always openning dbm databases read only.
1525
     */
1526
0
    if (secmod_configIsDBM(config)) {
1527
0
        isReadOnly = 1;
1528
0
    }
1529
0
    for (i = 0; i < count; i++) {
1530
0
        if (secmod_matchConfig(config, conflist[i].config, certPrefix,
1531
0
                               conflist[i].certPrefix, keyPrefix,
1532
0
                               conflist[i].keyPrefix, isReadOnly,
1533
0
                               conflist[i].isReadOnly)) {
1534
0
            ret = PR_TRUE;
1535
0
            goto done;
1536
0
        }
1537
0
    }
1538
1539
0
    ret = PR_FALSE;
1540
0
done:
1541
0
    PORT_Free(config);
1542
0
    PORT_Free(certPrefix);
1543
0
    PORT_Free(keyPrefix);
1544
0
    return ret;
1545
0
}
1546
1547
/*
1548
 * Find the slot id from the module spec. If the slot is the database slot, we
1549
 * can get the slot id from the default database slot.
1550
 */
1551
CK_SLOT_ID
1552
secmod_GetSlotIDFromModuleSpec(const char *moduleSpec, SECMODModule *module)
1553
0
{
1554
0
    char *tmp_spec = NULL;
1555
0
    char **children, **thisChild;
1556
0
    CK_SLOT_ID *ids, *thisID, slotID = -1;
1557
0
    char *inConfig = NULL, *thisConfig = NULL;
1558
0
    char *inCertPrefix = NULL, *thisCertPrefix = NULL;
1559
0
    char *inKeyPrefix = NULL, *thisKeyPrefix = NULL;
1560
0
    PRBool inReadOnly, thisReadOnly;
1561
1562
0
    inConfig = secmod_getConfigDir(moduleSpec, &inCertPrefix, &inKeyPrefix,
1563
0
                                   &inReadOnly);
1564
0
    if (!inConfig) {
1565
0
        goto done;
1566
0
    }
1567
1568
0
    if (secmod_configIsDBM(inConfig)) {
1569
0
        inReadOnly = 1;
1570
0
    }
1571
1572
0
    tmp_spec = secmod_ParseModuleSpecForTokens(PR_TRUE, module->isFIPS,
1573
0
                                               module->libraryParams, &children, &ids);
1574
0
    if (tmp_spec == NULL) {
1575
0
        goto done;
1576
0
    }
1577
1578
    /* first check to see if the parent is the database */
1579
0
    thisConfig = secmod_getConfigDir(tmp_spec, &thisCertPrefix, &thisKeyPrefix,
1580
0
                                     &thisReadOnly);
1581
0
    if (!thisConfig) {
1582
0
        goto done;
1583
0
    }
1584
0
    if (secmod_matchConfig(inConfig, thisConfig, inCertPrefix, thisCertPrefix,
1585
0
                           inKeyPrefix, thisKeyPrefix, inReadOnly, thisReadOnly)) {
1586
        /* yup it's the default key slot, get the id for it */
1587
0
        PK11SlotInfo *slot = PK11_GetInternalKeySlot();
1588
0
        if (slot) {
1589
0
            slotID = slot->slotID;
1590
0
            PK11_FreeSlot(slot);
1591
0
        }
1592
0
        goto done;
1593
0
    }
1594
1595
    /* find id of the token */
1596
0
    for (thisChild = children, thisID = ids; thisChild && *thisChild; thisChild++, thisID++) {
1597
0
        PORT_Free(thisConfig);
1598
0
        PORT_Free(thisCertPrefix);
1599
0
        PORT_Free(thisKeyPrefix);
1600
0
        thisConfig = secmod_getConfigDir(*thisChild, &thisCertPrefix,
1601
0
                                         &thisKeyPrefix, &thisReadOnly);
1602
0
        if (thisConfig == NULL) {
1603
0
            continue;
1604
0
        }
1605
0
        if (secmod_matchConfig(inConfig, thisConfig, inCertPrefix, thisCertPrefix,
1606
0
                               inKeyPrefix, thisKeyPrefix, inReadOnly, thisReadOnly)) {
1607
0
            slotID = *thisID;
1608
0
            break;
1609
0
        }
1610
0
    }
1611
1612
0
done:
1613
0
    PORT_Free(inConfig);
1614
0
    PORT_Free(inCertPrefix);
1615
0
    PORT_Free(inKeyPrefix);
1616
0
    PORT_Free(thisConfig);
1617
0
    PORT_Free(thisCertPrefix);
1618
0
    PORT_Free(thisKeyPrefix);
1619
0
    if (tmp_spec) {
1620
0
        secmod_FreeChildren(children, ids);
1621
0
        PORT_Free(tmp_spec);
1622
0
    }
1623
0
    return slotID;
1624
0
}
1625
1626
void
1627
secmod_FreeConfigList(SECMODConfigList *conflist, int count)
1628
0
{
1629
0
    int i;
1630
0
    for (i = 0; i < count; i++) {
1631
0
        PORT_Free(conflist[i].config);
1632
0
        PORT_Free(conflist[i].certPrefix);
1633
0
        PORT_Free(conflist[i].keyPrefix);
1634
0
    }
1635
0
    PORT_Free(conflist);
1636
0
}
1637
1638
void
1639
secmod_FreeChildren(char **children, CK_SLOT_ID *ids)
1640
0
{
1641
0
    char **thisChild;
1642
1643
0
    if (!children) {
1644
0
        return;
1645
0
    }
1646
1647
0
    for (thisChild = children; thisChild && *thisChild; thisChild++) {
1648
0
        PORT_Free(*thisChild);
1649
0
    }
1650
0
    PORT_Free(children);
1651
0
    if (ids) {
1652
0
        PORT_Free(ids);
1653
0
    }
1654
0
    return;
1655
0
}
1656
1657
/*
1658
 * caclulate the length of each child record:
1659
 * " 0x{id}=<{escaped_child}>"
1660
 */
1661
static int
1662
secmod_getChildLength(char *child, CK_SLOT_ID id)
1663
0
{
1664
0
    int length = NSSUTIL_DoubleEscapeSize(child, '>', ']');
1665
0
    if (id == 0) {
1666
0
        length++;
1667
0
    }
1668
0
    while (id) {
1669
0
        length++;
1670
0
        id = id >> 4;
1671
0
    }
1672
0
    length += 6; /* {sp}0x[id]=<{child}> */
1673
0
    return length;
1674
0
}
1675
1676
/*
1677
 * Build a child record:
1678
 * " 0x{id}=<{escaped_child}>"
1679
 */
1680
static SECStatus
1681
secmod_mkTokenChild(char **next, int *length, char *child, CK_SLOT_ID id)
1682
0
{
1683
0
    int len;
1684
0
    char *escSpec;
1685
1686
0
    len = PR_snprintf(*next, *length, " 0x%x=<", id);
1687
0
    if (len < 0) {
1688
0
        return SECFailure;
1689
0
    }
1690
0
    *next += len;
1691
0
    *length -= len;
1692
0
    escSpec = NSSUTIL_DoubleEscape(child, '>', ']');
1693
0
    if (escSpec == NULL) {
1694
0
        return SECFailure;
1695
0
    }
1696
0
    if (*child && (*escSpec == 0)) {
1697
0
        PORT_Free(escSpec);
1698
0
        return SECFailure;
1699
0
    }
1700
0
    len = strlen(escSpec);
1701
0
    if (len + 1 > *length) {
1702
0
        PORT_Free(escSpec);
1703
0
        return SECFailure;
1704
0
    }
1705
0
    PORT_Memcpy(*next, escSpec, len);
1706
0
    *next += len;
1707
0
    *length -= len;
1708
0
    PORT_Free(escSpec);
1709
0
    **next = '>';
1710
0
    (*next)++;
1711
0
    (*length)--;
1712
0
    return SECSuccess;
1713
0
}
1714
1715
0
#define TOKEN_STRING " tokens=["
1716
1717
char *
1718
secmod_MkAppendTokensList(PLArenaPool *arena, char *oldParam, char *newToken,
1719
                          CK_SLOT_ID newID, char **children, CK_SLOT_ID *ids)
1720
0
{
1721
0
    char *rawParam = NULL;  /* oldParam with tokens stripped off */
1722
0
    char *newParam = NULL;  /* space for the return parameter */
1723
0
    char *nextParam = NULL; /* current end of the new parameter */
1724
0
    char **oldChildren = NULL;
1725
0
    CK_SLOT_ID *oldIds = NULL;
1726
0
    void *mark = NULL; /* mark the arena pool in case we need
1727
                        * to release it */
1728
0
    int length, i, tmpLen;
1729
0
    SECStatus rv;
1730
1731
    /* first strip out and save the old tokenlist */
1732
0
    rawParam = secmod_ParseModuleSpecForTokens(PR_FALSE, PR_FALSE,
1733
0
                                               oldParam, &oldChildren, &oldIds);
1734
0
    if (!rawParam) {
1735
0
        goto loser;
1736
0
    }
1737
1738
    /* now calculate the total length of the new buffer */
1739
    /* First the 'fixed stuff', length of rawparam (does not include a NULL),
1740
     * length of the token string (does include the NULL), closing bracket */
1741
0
    length = strlen(rawParam) + sizeof(TOKEN_STRING) + 1;
1742
    /* now add then length of all the old children */
1743
0
    for (i = 0; oldChildren && oldChildren[i]; i++) {
1744
0
        length += secmod_getChildLength(oldChildren[i], oldIds[i]);
1745
0
    }
1746
1747
    /* add the new token */
1748
0
    length += secmod_getChildLength(newToken, newID);
1749
1750
    /* and it's new children */
1751
0
    for (i = 0; children && children[i]; i++) {
1752
0
        if (ids[i] == -1) {
1753
0
            continue;
1754
0
        }
1755
0
        length += secmod_getChildLength(children[i], ids[i]);
1756
0
    }
1757
1758
    /* now allocate and build the string */
1759
0
    mark = PORT_ArenaMark(arena);
1760
0
    if (!mark) {
1761
0
        goto loser;
1762
0
    }
1763
0
    newParam = PORT_ArenaAlloc(arena, length);
1764
0
    if (!newParam) {
1765
0
        goto loser;
1766
0
    }
1767
1768
0
    PORT_Strcpy(newParam, oldParam);
1769
0
    tmpLen = strlen(oldParam);
1770
0
    nextParam = newParam + tmpLen;
1771
0
    length -= tmpLen;
1772
0
    PORT_Memcpy(nextParam, TOKEN_STRING, sizeof(TOKEN_STRING) - 1);
1773
0
    nextParam += sizeof(TOKEN_STRING) - 1;
1774
0
    length -= sizeof(TOKEN_STRING) - 1;
1775
1776
0
    for (i = 0; oldChildren && oldChildren[i]; i++) {
1777
0
        rv = secmod_mkTokenChild(&nextParam, &length, oldChildren[i], oldIds[i]);
1778
0
        if (rv != SECSuccess) {
1779
0
            goto loser;
1780
0
        }
1781
0
    }
1782
1783
0
    rv = secmod_mkTokenChild(&nextParam, &length, newToken, newID);
1784
0
    if (rv != SECSuccess) {
1785
0
        goto loser;
1786
0
    }
1787
1788
0
    for (i = 0; children && children[i]; i++) {
1789
0
        if (ids[i] == -1) {
1790
0
            continue;
1791
0
        }
1792
0
        rv = secmod_mkTokenChild(&nextParam, &length, children[i], ids[i]);
1793
0
        if (rv != SECSuccess) {
1794
0
            goto loser;
1795
0
        }
1796
0
    }
1797
1798
0
    if (length < 2) {
1799
0
        goto loser;
1800
0
    }
1801
1802
0
    *nextParam++ = ']';
1803
0
    *nextParam++ = 0;
1804
1805
    /* we are going to return newParam now, don't release the mark */
1806
0
    PORT_ArenaUnmark(arena, mark);
1807
0
    mark = NULL;
1808
1809
0
loser:
1810
0
    if (mark) {
1811
0
        PORT_ArenaRelease(arena, mark);
1812
0
        newParam = NULL; /* if the mark is still active,
1813
                          * don't return the param */
1814
0
    }
1815
0
    if (rawParam) {
1816
0
        PORT_Free(rawParam);
1817
0
    }
1818
0
    if (oldChildren) {
1819
0
        secmod_FreeChildren(oldChildren, oldIds);
1820
0
    }
1821
0
    return newParam;
1822
0
}
1823
1824
static char *
1825
secmod_mkModuleSpec(SECMODModule *module)
1826
0
{
1827
0
    char *nss = NULL, *modSpec = NULL, **slotStrings = NULL;
1828
0
    int slotCount, i, si;
1829
0
    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
1830
1831
    /* allocate target slot info strings */
1832
0
    slotCount = 0;
1833
1834
0
    SECMOD_GetReadLock(moduleLock);
1835
0
    if (module->slotCount) {
1836
0
        for (i = 0; i < module->slotCount; i++) {
1837
0
            if (module->slots[i]->defaultFlags != 0) {
1838
0
                slotCount++;
1839
0
            }
1840
0
        }
1841
0
    } else {
1842
0
        slotCount = module->slotInfoCount;
1843
0
    }
1844
1845
0
    slotStrings = (char **)PORT_ZAlloc(slotCount * sizeof(char *));
1846
0
    if (slotStrings == NULL) {
1847
0
        SECMOD_ReleaseReadLock(moduleLock);
1848
0
        goto loser;
1849
0
    }
1850
1851
    /* build the slot info strings */
1852
0
    if (module->slotCount) {
1853
0
        for (i = 0, si = 0; i < module->slotCount; i++) {
1854
0
            if (module->slots[i]->defaultFlags) {
1855
0
                PORT_Assert(si < slotCount);
1856
0
                if (si >= slotCount)
1857
0
                    break;
1858
0
                slotStrings[si] = NSSUTIL_MkSlotString(module->slots[i]->slotID,
1859
0
                                                       module->slots[i]->defaultFlags,
1860
0
                                                       module->slots[i]->timeout,
1861
0
                                                       module->slots[i]->askpw,
1862
0
                                                       module->slots[i]->hasRootCerts,
1863
0
                                                       module->slots[i]->hasRootTrust);
1864
0
                si++;
1865
0
            }
1866
0
        }
1867
0
    } else {
1868
0
        for (i = 0; i < slotCount; i++) {
1869
0
            slotStrings[i] = NSSUTIL_MkSlotString(
1870
0
                module->slotInfo[i].slotID,
1871
0
                module->slotInfo[i].defaultFlags,
1872
0
                module->slotInfo[i].timeout,
1873
0
                module->slotInfo[i].askpw,
1874
0
                module->slotInfo[i].hasRootCerts,
1875
0
                module->slotInfo[i].hasRootTrust);
1876
0
        }
1877
0
    }
1878
1879
0
    SECMOD_ReleaseReadLock(moduleLock);
1880
0
    nss = NSSUTIL_MkNSSString(slotStrings, slotCount, module->internal,
1881
0
                              module->isFIPS, module->isModuleDB,
1882
0
                              module->moduleDBOnly, module->isCritical,
1883
0
                              module->trustOrder, module->cipherOrder,
1884
0
                              module->ssl[0], module->ssl[1]);
1885
0
    modSpec = NSSUTIL_MkModuleSpec(module->dllName, module->commonName,
1886
0
                                   module->libraryParams, nss);
1887
0
    PORT_Free(slotStrings);
1888
0
    PR_smprintf_free(nss);
1889
0
loser:
1890
0
    return (modSpec);
1891
0
}
1892
1893
char **
1894
SECMOD_GetModuleSpecList(SECMODModule *module)
1895
1
{
1896
1
    SECMODModuleDBFunc func = (SECMODModuleDBFunc)module->moduleDBFunc;
1897
1
    if (func) {
1898
1
        return (*func)(SECMOD_MODULE_DB_FUNCTION_FIND,
1899
1
                       module->libraryParams, NULL);
1900
1
    }
1901
0
    return NULL;
1902
1
}
1903
1904
SECStatus
1905
SECMOD_AddPermDB(SECMODModule *module)
1906
0
{
1907
0
    SECMODModuleDBFunc func;
1908
0
    char *moduleSpec;
1909
0
    char **retString;
1910
1911
0
    if (module->parent == NULL)
1912
0
        return SECFailure;
1913
1914
0
    func = (SECMODModuleDBFunc)module->parent->moduleDBFunc;
1915
0
    if (func) {
1916
0
        moduleSpec = secmod_mkModuleSpec(module);
1917
0
        retString = (*func)(SECMOD_MODULE_DB_FUNCTION_ADD,
1918
0
                            module->parent->libraryParams, moduleSpec);
1919
0
        PORT_Free(moduleSpec);
1920
0
        if (retString != NULL)
1921
0
            return SECSuccess;
1922
0
    }
1923
0
    return SECFailure;
1924
0
}
1925
1926
SECStatus
1927
SECMOD_DeletePermDB(SECMODModule *module)
1928
0
{
1929
0
    SECMODModuleDBFunc func;
1930
0
    char *moduleSpec;
1931
0
    char **retString;
1932
1933
0
    if (module->parent == NULL)
1934
0
        return SECFailure;
1935
1936
0
    func = (SECMODModuleDBFunc)module->parent->moduleDBFunc;
1937
0
    if (func) {
1938
0
        moduleSpec = secmod_mkModuleSpec(module);
1939
0
        retString = (*func)(SECMOD_MODULE_DB_FUNCTION_DEL,
1940
0
                            module->parent->libraryParams, moduleSpec);
1941
0
        PORT_Free(moduleSpec);
1942
0
        if (retString != NULL)
1943
0
            return SECSuccess;
1944
0
    }
1945
0
    return SECFailure;
1946
0
}
1947
1948
SECStatus
1949
SECMOD_FreeModuleSpecList(SECMODModule *module, char **moduleSpecList)
1950
1
{
1951
1
    SECMODModuleDBFunc func = (SECMODModuleDBFunc)module->moduleDBFunc;
1952
1
    char **retString;
1953
1
    if (func) {
1954
1
        retString = (*func)(SECMOD_MODULE_DB_FUNCTION_RELEASE,
1955
1
                            module->libraryParams, moduleSpecList);
1956
1
        if (retString != NULL)
1957
1
            return SECSuccess;
1958
1
    }
1959
0
    return SECFailure;
1960
1
}
1961
1962
/*
1963
 * load a PKCS#11 module but do not add it to the default NSS trust domain
1964
 */
1965
SECMODModule *
1966
SECMOD_LoadModule(char *modulespec, SECMODModule *parent, PRBool recurse)
1967
2
{
1968
2
    char *library = NULL, *moduleName = NULL, *parameters = NULL, *nss = NULL;
1969
2
    char *config = NULL;
1970
2
    SECStatus status;
1971
2
    SECMODModule *module = NULL;
1972
2
    SECMODModule *oldModule = NULL;
1973
2
    SECStatus rv;
1974
2
    PRBool forwardPolicyFeedback = PR_FALSE;
1975
2
    PRUint32 forwardPolicyCheckFlags;
1976
1977
    /* initialize the underlying module structures */
1978
2
    SECMOD_Init();
1979
1980
2
    status = NSSUTIL_ArgParseModuleSpecEx(modulespec, &library, &moduleName,
1981
2
                                          &parameters, &nss,
1982
2
                                          &config);
1983
2
    if (status != SECSuccess) {
1984
0
        goto loser;
1985
0
    }
1986
1987
2
    module = SECMOD_CreateModuleEx(library, moduleName, parameters, nss, config);
1988
2
    forwardPolicyFeedback = NSSUTIL_ArgHasFlag("flags", "printPolicyFeedback", nss);
1989
2
    forwardPolicyCheckFlags = secmod_parsePolicyCheckFlags(nss);
1990
1991
2
    if (library)
1992
0
        PORT_Free(library);
1993
2
    if (moduleName)
1994
2
        PORT_Free(moduleName);
1995
2
    if (parameters)
1996
2
        PORT_Free(parameters);
1997
2
    if (nss)
1998
2
        PORT_Free(nss);
1999
2
    if (config)
2000
0
        PORT_Free(config);
2001
2
    if (!module) {
2002
0
        goto loser;
2003
0
    }
2004
2005
    /* a policy only stanza doesn't actually get 'loaded'. policy has already
2006
     * been parsed as a side effect of the CreateModuleEx call */
2007
2
    if (secmod_PolicyOnly(module)) {
2008
0
        return module;
2009
0
    }
2010
2
    if (parent) {
2011
1
        module->parent = SECMOD_ReferenceModule(parent);
2012
1
        if (module->internal && secmod_IsInternalKeySlot(parent)) {
2013
1
            module->internal = parent->internal;
2014
1
        }
2015
1
    }
2016
2017
    /* load it */
2018
2
    rv = secmod_LoadPKCS11Module(module, &oldModule);
2019
2
    if (rv != SECSuccess) {
2020
0
        goto loser;
2021
0
    }
2022
2023
    /* if we just reload an old module, no need to add it to any lists.
2024
     * we simple release all our references */
2025
2
    if (oldModule) {
2026
        /* This module already exists, don't link it anywhere. This
2027
         * will probably destroy this module */
2028
0
        SECMOD_DestroyModule(module);
2029
0
        return oldModule;
2030
0
    }
2031
2032
2
    if (recurse && module->isModuleDB) {
2033
1
        char **moduleSpecList;
2034
1
        PORT_SetError(0);
2035
2036
1
        moduleSpecList = SECMOD_GetModuleSpecList(module);
2037
1
        if (moduleSpecList) {
2038
1
            char **index;
2039
2040
1
            index = moduleSpecList;
2041
1
            if (*index && SECMOD_GetSkipFirstFlag(module)) {
2042
0
                index++;
2043
0
            }
2044
2045
2
            for (; *index; index++) {
2046
1
                SECMODModule *child;
2047
1
                if (0 == PORT_Strcmp(*index, modulespec)) {
2048
                    /* avoid trivial infinite recursion */
2049
0
                    PORT_SetError(SEC_ERROR_NO_MODULE);
2050
0
                    rv = SECFailure;
2051
0
                    break;
2052
0
                }
2053
1
                if (!forwardPolicyFeedback) {
2054
1
                    child = SECMOD_LoadModule(*index, module, PR_TRUE);
2055
1
                } else {
2056
                    /* Add printPolicyFeedback to the nss flags */
2057
0
                    char *specWithForwards =
2058
0
                        NSSUTIL_AddNSSFlagToModuleSpec(*index, "printPolicyFeedback");
2059
0
                    char *tmp;
2060
0
                    if (forwardPolicyCheckFlags & SECMOD_FLAG_POLICY_CHECK_IDENTIFIER) {
2061
0
                        tmp = NSSUTIL_AddNSSFlagToModuleSpec(specWithForwards, "policyCheckIdentifier");
2062
0
                        PORT_Free(specWithForwards);
2063
0
                        specWithForwards = tmp;
2064
0
                    }
2065
0
                    if (forwardPolicyCheckFlags & SECMOD_FLAG_POLICY_CHECK_VALUE) {
2066
0
                        tmp = NSSUTIL_AddNSSFlagToModuleSpec(specWithForwards, "policyCheckValue");
2067
0
                        PORT_Free(specWithForwards);
2068
0
                        specWithForwards = tmp;
2069
0
                    }
2070
0
                    child = SECMOD_LoadModule(specWithForwards, module, PR_TRUE);
2071
0
                    PORT_Free(specWithForwards);
2072
0
                }
2073
1
                if (!child)
2074
0
                    break;
2075
1
                if (child->isCritical && !child->loaded) {
2076
0
                    int err = PORT_GetError();
2077
0
                    if (!err)
2078
0
                        err = SEC_ERROR_NO_MODULE;
2079
0
                    SECMOD_DestroyModule(child);
2080
0
                    PORT_SetError(err);
2081
0
                    rv = SECFailure;
2082
0
                    break;
2083
0
                }
2084
1
                SECMOD_DestroyModule(child);
2085
1
            }
2086
1
            SECMOD_FreeModuleSpecList(module, moduleSpecList);
2087
1
        } else {
2088
0
            if (!PORT_GetError())
2089
0
                PORT_SetError(SEC_ERROR_NO_MODULE);
2090
0
            rv = SECFailure;
2091
0
        }
2092
1
    }
2093
2094
2
    if (rv != SECSuccess) {
2095
0
        goto loser;
2096
0
    }
2097
2098
    /* inherit the reference */
2099
2
    if (!module->moduleDBOnly) {
2100
1
        SECMOD_AddModuleToList(module);
2101
1
    } else {
2102
1
        SECMOD_AddModuleToDBOnlyList(module);
2103
1
    }
2104
2105
    /* handle any additional work here */
2106
2
    return module;
2107
2108
0
loser:
2109
0
    if (module) {
2110
0
        if (module->loaded) {
2111
0
            SECMOD_UnloadModule(module);
2112
0
        }
2113
0
        SECMOD_AddModuleToUnloadList(module);
2114
0
    }
2115
0
    return module;
2116
2
}
2117
2118
/*
2119
 * load a PKCS#11 module and add it to the default NSS trust domain
2120
 */
2121
SECMODModule *
2122
SECMOD_LoadUserModule(char *modulespec, SECMODModule *parent, PRBool recurse)
2123
0
{
2124
0
    SECStatus rv = SECSuccess;
2125
0
    SECMODModule *newmod = SECMOD_LoadModule(modulespec, parent, recurse);
2126
0
    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
2127
2128
0
    if (newmod) {
2129
0
        SECMOD_GetReadLock(moduleLock);
2130
0
        rv = STAN_AddModuleToDefaultTrustDomain(newmod);
2131
0
        SECMOD_ReleaseReadLock(moduleLock);
2132
0
        if (SECSuccess != rv) {
2133
0
            SECMOD_DestroyModule(newmod);
2134
0
            return NULL;
2135
0
        }
2136
0
    }
2137
0
    return newmod;
2138
0
}
2139
2140
/*
2141
 * remove the PKCS#11 module from the default NSS trust domain, call
2142
 * C_Finalize, and destroy the module structure
2143
 */
2144
SECStatus
2145
SECMOD_UnloadUserModule(SECMODModule *mod)
2146
0
{
2147
0
    SECStatus rv = SECSuccess;
2148
0
    int atype = 0;
2149
0
    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
2150
0
    if (!mod) {
2151
0
        return SECFailure;
2152
0
    }
2153
2154
0
    SECMOD_GetReadLock(moduleLock);
2155
0
    rv = STAN_RemoveModuleFromDefaultTrustDomain(mod);
2156
0
    SECMOD_ReleaseReadLock(moduleLock);
2157
0
    if (SECSuccess != rv) {
2158
0
        return SECFailure;
2159
0
    }
2160
0
    return SECMOD_DeleteModuleEx(NULL, mod, &atype, PR_FALSE);
2161
0
}