-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathconfig.js
More file actions
452 lines (425 loc) · 14 KB
/
Copy pathconfig.js
File metadata and controls
452 lines (425 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
'use strict';
const convict = require('convict');
const crypto = require('crypto');
const packageJson = require('../../package.json');
// Generate the default session secret
// This runs synchronously, but only once at startup
// Using the default session secret will limit the session cookies to one run of the server
// - Restarting the server will force the users to login again
// - Sessions cannot be shared across server instances
// Setting the SESSION_SECRET environment variable will override this generated value
function generateSecret() {
const stringBase = 'base64';
const byteLength = 48;
const buffer = crypto.randomBytes(byteLength);
const secret = buffer.toString(stringBase);
return secret;
}
const defaultSessionSecret = generateSecret();
const defaultTokenSigningSecret = generateSecret();
const defaultMongoStoreCryptoSecret = generateSecret();
const userAuthnMechanismValues = ['anonymous', 'oidc'];
convict.addFormat(enumFormat('user-authn-mechanism', userAuthnMechanismValues, true));
const serviceRoleValues = ['read-only', 'collection-manager', 'stix-export'];
convict.addFormat(enumFormat('service-role', serviceRoleValues, true));
// Creates a new convict format for a list of enumerated values
function enumFormat(name, values, coerceLower) {
return {
name,
validate: function (val) {
if (!values.includes(val)) {
throw new Error(`Invalid ${name} value`);
}
},
coerce: function (val) {
if (coerceLower) {
return val.toLowerCase();
} else {
return val;
}
},
};
}
function arrayFormat(name) {
return {
name,
validate: function (entries, schema) {
if (!Array.isArray(entries)) {
throw new Error('Property must be of type Array');
}
for (const entry of entries) {
convict(schema.children).load(entry).validate();
}
},
};
}
convict.addFormat(arrayFormat('oidc-client'));
convict.addFormat(arrayFormat('service-account'));
/**
* Validates an array of strings representing domains or FQDNs.
* Allows the wildcard character `*` to indicate all origins.
* Supports the value `disable` to explicitly disable CORS.
* Allows localhost and local network IPs for development environments.
*
* A valid origin must be one of:
* - Special values: '*' or 'disable'
* - localhost (with optional port)
* - Local network IP (with optional port)
* - Valid FQDN (with optional port) that:
* - Contains only alphanumeric characters, hyphens, and dots
* - Has at least one dot separating the domain levels
* - Ends with a valid top-level domain (e.g., `.com`, `.org`)
*
* @param {string[]} values - Array of origins to validate
* @throws {Error} If any origin in the list is invalid
*/
convict.addFormat({
name: 'domains',
validate: function (val) {
const values = Array.isArray(val) ? val : val.split(',').map((v) => v.trim());
// Handle special cases
if (values.length === 1 && (values[0] === '*' || values[0] === 'disable')) {
return;
}
const patterns = {
// Matches standard hostnames per RFC 952/1123
hostname:
/^(?:https?:\/\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}(?::\d{1,5})?$/,
// Matches 'localhost'
localhost: /^(?:https?:\/\/)?localhost(?::\d{1,5})?$/,
// Matches private network IPv4 addresses
privateIPv4:
/^(?:https?:\/\/)?((?:127\.|10\.|172\.(?:1[6-9]|2[0-9]|3[0-1])|192\.168\.)[0-9.]+)(?::\d{1,5})?$/,
// IPv6 localhost
ipv6: /^(?:https?:\/\/)?\[::1\](?::\d{1,5})?$/,
};
for (const origin of values) {
if (!origin) {
throw new Error('Empty domain is not allowed');
}
// Check localhost and IPv6 first
if (patterns.localhost.test(origin) || patterns.ipv6.test(origin)) {
continue;
}
// Then check private network IPs
if (patterns.privateIPv4.test(origin)) {
const octets = origin.split('.').map(Number);
if (octets.some((octet) => octet > 255)) {
throw new Error('Invalid IP address format');
}
continue;
}
// Finally check hostname
if (!patterns.hostname.test(origin)) {
throw new Error('Invalid domain format');
}
}
},
coerce: function (value) {
if (Array.isArray(value)) {
return value;
}
return value.split(',').map((v) => v.trim());
},
});
function loadConfig() {
const config = convict({
server: {
port: {
doc: 'Port the HTTP server should listen on',
format: 'int',
default: 3000,
env: 'PORT',
},
corsAllowedOrigins: {
doc: 'Comma-separated list of origins allowed to access the REST API endpoints. Use * to allow any origin.',
format: 'domains',
default: '*',
env: 'CORS_ALLOWED_ORIGINS',
},
},
app: {
name: {
default: 'attack-workbench-rest-api',
},
env: {
default: 'development',
env: 'NODE_ENV',
},
version: {
default: packageJson.version,
},
attackSpecVersion: {
default: packageJson.attackSpecVersion,
},
},
database: {
url: {
doc: 'URL of the MongoDB server',
default: '',
env: 'DATABASE_URL',
},
migration: {
enable: {
doc: 'Enable automatic database migration when starting the server',
format: Boolean,
default: true,
env: 'WB_REST_DATABASE_MIGRATION_ENABLE',
},
},
},
logging: {
logLevel: {
doc: 'Level of logging messages to write to console (error, warn, http, info, verbose, debug)',
default: 'info',
env: 'LOG_LEVEL',
},
},
openApi: {
specPath: {
default: './app/api/definitions/openapi.yml',
},
},
validateRequests: {
withAttackDataModel: {
doc: 'Enable validation of POST and PUT request bodies using the ATT&CK Data Model',
format: Boolean,
default: true,
env: 'VALIDATE_WITH_ADM_SCHEMAS',
},
withOpenApi: {
doc: 'Enable validation of POST and PUT request bodies using the legacy OpenAPI YAML-based validation schemas',
format: Boolean,
default: true,
env: 'VALIDATE_WITH_LEGACY_SCHEMAS',
},
},
collectionIndex: {
defaultInterval: {
doc: 'How often collection indexes should check for updates (in seconds). Only applies to new indexes added to the REST API, does not affect existing collection indexes',
default: 300,
env: 'DEFAULT_INTERVAL',
},
},
configurationFiles: {
allowedValues: {
doc: 'Location of the allowed values configuration file',
default: './app/config/allowed-values.json',
env: 'ALLOWED_VALUES_PATH',
},
jsonConfigFile: {
doc: 'Location of a JSON file containing configuration values',
default: '',
env: 'JSON_CONFIG_PATH',
},
staticMarkingDefinitionsPath: {
doc: 'Location of a directory containing one or more JSON files with the static marking definitions to load into the system',
default: './app/lib/default-static-marking-definitions/',
env: 'WB_REST_STATIC_MARKING_DEFS_PATH',
},
staticBypassRulesPath: {
doc: 'Location of a JSON file containing default validation bypass rules to load at startup',
default: './app/lib/default-bypass-rules.json',
env: 'WB_REST_STATIC_BYPASS_RULES_PATH',
},
},
scheduler: {
syncCollectionIndexesCron: {
doc: 'Sets the interval in seconds for starting the scheduler.',
default: '* * * * *', // every minute
env: 'SYNC_COLLECTION_INDEXES_CRON',
},
checkWipAttackIdsCron: {
doc: 'Cron pattern for checking WIP objects with ATT&CK IDs (e.g., "0 * * * *" for hourly).',
default: '0 * * * *', // every hour
env: 'CHECK_WIP_ATTACK_IDS_CRON',
},
validateObjectsCron: {
doc: 'Cron pattern for re-validating all STIX objects against the ADM (e.g., "0 3 * * *" for daily at 3 AM).',
default: '0 3 * * *', // daily at 3 AM
env: 'VALIDATE_OBJECTS_CRON',
},
enableScheduler: {
format: Boolean,
default: true,
env: 'ENABLE_SCHEDULER',
},
},
session: {
secret: {
doc: 'Secret used to sign the session ID cookie',
default: defaultSessionSecret,
env: 'SESSION_SECRET',
},
mongoStoreCryptoSecret: {
doc: 'Secret used to encrypt session data in MongoDB',
default: defaultMongoStoreCryptoSecret,
env: 'MONGOSTORE_CRYPTO_SECRET',
},
},
userAuthn: {
mechanism: {
doc: 'Authentication mechanism to use for user log in',
format: 'user-authn-mechanism',
default: 'anonymous',
env: 'AUTHN_MECHANISM',
},
oidc: {
issuerUrl: {
doc: 'OIDC Issuer URL',
format: String,
default: '',
env: 'AUTHN_OIDC_ISSUER_URL',
},
clientId: {
doc: 'OIDC Client ID',
format: String,
default: '',
env: 'AUTHN_OIDC_CLIENT_ID',
},
clientSecret: {
doc: 'OIDC Client Secret',
format: String,
default: '',
env: 'AUTHN_OIDC_CLIENT_SECRET',
},
redirectOrigin: {
doc: 'Origin (protocol and host) to use in building the OIDC redirect URI',
format: String,
default: 'http://localhost:3000',
env: 'AUTHN_OIDC_REDIRECT_ORIGIN',
},
},
},
serviceAuthn: {
oidcClientCredentials: {
enable: {
doc: 'Enable OIDC Client Credentials Flow for service accounts',
format: Boolean,
default: false,
env: 'SERVICE_ACCOUNT_OIDC_ENABLE',
},
jwksUri: {
doc: 'JWKS URI for obtaining the public key from the OIDC identity provider',
format: String,
default: '',
env: 'JWKS_URI',
},
clients: {
doc: 'Services (OIDC clients) that may access the REST API',
format: 'oidc-client',
default: [],
children: {
clientId: {
doc: 'clientId for the service',
format: String,
default: null,
},
serviceRole: {
doc: 'The role determines which endpoints the service is permitted to access',
format: 'service-role',
default: 'read-only',
},
},
},
},
challengeApikey: {
enable: {
doc: 'Enable apikey authentication for service accounts (challenge)',
format: Boolean,
default: false,
env: 'WB_REST_SERVICE_ACCOUNT_CHALLENGE_APIKEY_ENABLE',
},
secret: {
doc: 'Secret used to sign the tokens issued to service accounts',
default: defaultTokenSigningSecret,
env: 'WB_REST_TOKEN_SIGNING_SECRET',
},
tokenTimeout: {
doc: 'Access token timeout in seconds',
format: 'int',
default: 300,
env: 'WB_REST_TOKEN_TIMEOUT',
},
serviceAccounts: {
doc: 'Services accounts that may access the REST API (with challenge)',
format: 'service-account',
default: [],
children: {
name: {
doc: 'Name of the service account',
format: String,
default: null,
},
apikey: {
doc: 'apikey of the service account (shared secret)',
format: String,
default: null,
},
serviceRole: {
doc: 'The role determines which endpoints the service is permitted to access',
format: 'service-role',
default: 'read-only',
},
},
},
},
basicApikey: {
enable: {
doc: 'Enable apikey authentication for service accounts (no challenge)',
format: Boolean,
default: false,
env: 'WB_REST_SERVICE_ACCOUNT_BASIC_APIKEY_ENABLE',
},
serviceAccounts: {
doc: 'Services accounts that may access the REST API using basic apikey',
format: 'service-account',
default: [],
children: {
name: {
doc: 'Name of the service account',
format: String,
default: null,
},
apikey: {
doc: 'apikey of the service account (shared secret)',
format: String,
default: null,
},
serviceRole: {
doc: 'The role determines which endpoints the service is permitted to access',
format: 'service-role',
default: 'read-only',
},
},
},
},
},
attackSourceNames: {
doc: 'Valid source_name values used in MITRE ATT&CK external_references',
default: ['mitre-attack', 'mitre-mobile-attack', 'mobile-attack', 'mitre-ics-attack'],
},
domainToKillChainMap: {
doc: 'Map the built-in domain names to the corresponding kill-chain-phase names',
default: {
'enterprise-attack': 'mitre-attack',
'mobile-attack': 'mitre-mobile-attack',
'ics-attack': 'mitre-ics-attack',
},
},
});
// Load configuration values from a JSON file if the JSON_CONFIG_PATH environment variable is set
if (config.get('configurationFiles.jsonConfigFile')) {
config.loadFile(config.get('configurationFiles.jsonConfigFile'));
}
config.validate({ allowed: 'strict' });
return config.getProperties();
}
// Load the configuration and extract the configuration properties to simplify access
const configurationObject = loadConfig();
// Add a function to reload the configuration properties
configurationObject.reloadConfig = function () {
const newConfigProperties = loadConfig();
Object.assign(configurationObject, newConfigProperties);
};
module.exports = configurationObject;