Coverage Report

Created: 2024-11-21 07:03

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