Repository navigation
Expand file tree
/
Copy pathwiseService.js
More file actions
1644 lines (1492 loc) · 58.9 KB
/
Copy pathwiseService.js
File metadata and controls
1644 lines (1492 loc) · 58.9 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************/
/* wiseService.js -- Server requests between Arkime and various intel services
* and files
*
* Copyright 2012-2016 AOL Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const express = require('express');
const fs = require('fs');
const glob = require('glob');
const async = require('async');
const sprintf = require('./sprintf.js').sprintf;
const iptrie = require('iptrie');
const User = require('../common/user');
const Auth = require('../common/auth');
const ArkimeUtil = require('../common/arkimeUtil');
const WISESource = require('./wiseSource.js');
const cluster = require('cluster');
const cryptoLib = require('crypto');
const favicon = require('serve-favicon');
const uuid = require('uuid').v4;
const helmet = require('helmet');
const jsonParser = ArkimeUtil.jsonParser;
const chalk = require('chalk');
const version = require('../common/version');
const path = require('path');
const ArkimeCache = require('../common/arkimeCache');
const ArkimeConfig = require('../common/arkimeConfig');
const RE2 = require('re2');
const dayMs = 60000 * 60 * 24;
require('console-stamp')(console, '[HH:MM:ss.l]');
const internals = {
fieldsTS: 0,
fields: [],
fieldsSize: 0,
sources: new Map(),
configDefs: {
wiseService: {
description: 'General settings that apply to WISE and all wise sources',
singleton: true,
service: true,
fields: [
{ name: 'port', required: false, regex: '^[0-9]+$', help: 'Port that the wiseService runs on. Defaults to 8081' },
{ name: 'keyFile', required: false, help: 'Path to PEM encoded key file' },
{ name: 'certFile', required: false, help: 'Path to PEM encoded cert file' },
{ name: 'caTrustFile', required: false, help: 'Path to PEM encoded CA file' },
{ name: 'authMode', required: true, help: 'How should auth be done: anonymous - no auth, basic - basic auth, digest - digest auth, header - http header auth, oidc - oidc auth, form - form auth', regex: '(anonymous|basic|digest|header|oidc|form|basic\\+oidc|basic\\+form|header\\+basic|header\\+digest|headerOnly|)' },
{ name: 'userNameHeader', required: true, help: 'the http header to use for username', ifField: 'authMode', ifValue: 'header' },
{ name: 'httpRealm', ifField: 'authMode', ifValue: 'digest', required: false, help: 'The realm to use for digest requests. Must be the same as viewer is using. Default Moloch' },
{ name: 'passwordSecret', ifField: 'authMode', ifValue: 'digest', required: false, password: true, help: 'The secret used to encrypted password hashes. Must be the same as viewer is using. Default password' },
{ name: 'usersElasticsearch', required: false, help: 'The URL to connect to OpenSearch/Elasticsearch. Default http://localhost:9200' },
{ name: 'usersElasticsearchAPIKey', required: false, help: 'OpenSearch/Elastisearch API key for users DB access', password: true },
{ name: 'usersElasticsearchBasicAuth', required: false, help: 'OpenSearch/Elastisearch Basic Auth', password: true },
{ name: 'userAuthIps', required: false, help: 'Comma separated list of CIDRs to allow authed requests from' },
{ name: 'usersPrefix', required: false, help: 'The prefix used with db.pl --prefix for users OpenSearch/Elasticsearch, if empty arkime_ is used' },
{ name: 'sourcePath', required: false, help: 'Where to look for the source files. Defaults to "./"' }
]
},
cache: {
description: 'Specify how WISE should cache results from sources that support it. Using a redis setup is especially useful when there are multiple WISE servers or large amount of results to cache.',
singleton: true,
service: true,
fields: [
{ name: 'type', required: false, regex: '^(memory|redis|memcached|lmdb)$', help: 'Where to cache results: memory (default), redis, memcached, lmdb' },
{ name: 'cacheSize', required: false, help: 'How many elements to cache in memory. Defaults to 100000' },
{ name: 'redisURL', password: true, required: false, ifField: 'type', ifValue: 'redis', help: 'Format is redis://[:password@]host:port/db-number, redis-sentinel://[[sentinelPassword]:[password]@]host[:port]/redis-name/db-number, or redis-cluster://[:password@]host:port/db-number' },
{ name: 'redisFormat', required: false, ifField: 'type', ifValue: 'redis', help: 'Use 2 (default) if WISE 2.x & WISE 3.x in use or 3 if just WISE 3.x', regex: '[23]' },
{ name: 'memcachedURL', password: true, required: false, ifField: 'type', ifValue: 'memcached', help: 'Format is memcached://[user:pass@]server1[:11211],[user:pass@]server2[:11211],...' },
{ name: 'lmdbDir', password: false, required: false, ifField: 'type', ifValue: 'lmdb', help: 'Directory for lmdb cache' }
]
}
},
types: new Map(),
views: new Map(),
fieldActions: new Map(),
valueActions: new Map(),
workers: 1,
webconfig: false,
configCode: cryptoLib.randomBytes(20).toString('base64').replace(/[=+/]/g, '').substr(0, 6),
startTime: Date.now()
};
internals.type2Name = ['ip', 'domain', 'md5', 'email', 'url', 'tuple', 'ja3', 'sha256'];
// ----------------------------------------------------------------------------
// Command Line Parsing
// ----------------------------------------------------------------------------
function processArgs (argv) {
for (let i = 0, ilen = argv.length; i < ilen; i++) {
if (process.argv[i] === '-o') {
i++;
const equal = process.argv[i].indexOf('=');
if (equal === -1) {
console.log('Missing equal sign in', process.argv[i]);
process.exit(1);
}
ArkimeConfig.setOverride(process.argv[i].slice(0, equal), process.argv[i].slice(equal + 1));
} else if (argv[i] === '--webcode') {
i++;
internals.configCode = argv[i];
} else if (argv[i] === '--webconfig') {
internals.webconfig = true;
console.log(chalk.cyan(
`${chalk.bgCyan.black('IMPORTANT')} - Config pin code is: ${internals.configCode}`
));
} else if (argv[i] === '--workers') {
i++;
internals.workers = +argv[i];
} else if (argv[i] === '--help') {
console.log('wiseService.js [<options>]');
console.log('');
console.log('Options:');
console.log(' -c, --config <file|url> Where to fetch the config file from');
console.log(' -o <section>.<key>=<value> Override the config file');
console.log(' --debug Increase debug level, multiple are supported');
console.log(' --webconfig Allow the config to be edited from web page');
console.log(' --workers <b> Number of worker processes to create');
console.log(' --insecure Disable certificate verification for https calls');
process.exit(0);
}
}
}
processArgs(process.argv);
if (internals.workers > 1) {
if (cluster.isMaster) {
for (let i = 0; i < internals.workers; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log('worker ' + worker.process.pid + ' died, restarting new worker');
cluster.fork();
});
}
}
// ----------------------------------------------------------------------------
const app = express();
const timeout = require('connect-timeout');
// super secret
app.use(helmet.hidePoweredBy());
app.use(helmet.xssFilter());
app.use(helmet.hsts({
maxAge: 31536000,
includeSubDomains: true
}));
// calculate nonce
app.use((req, res, next) => {
res.locals.nonce = Buffer.from(uuid()).toString('base64');
next();
});
// define csp headers
const cspDirectives = {
defaultSrc: ["'self'"],
// unsafe-inline required for json editor (https://github.com/dirkliu/vue-json-editor)
styleSrc: ["'self'", "'unsafe-inline'"],
// need unsafe-eval for vue full build: https://vuejs.org/v2/guide/installation.html#CSP-environments
scriptSrc: ["'self'", "'unsafe-eval'", (req, res) => `'nonce-${res.locals.nonce}'`],
objectSrc: ["'none'"],
imgSrc: ["'self'", 'data:'],
// web worker required for json editor (https://github.com/dirkliu/vue-json-editor)
workerSrc: ["'self'", 'blob:']
};
const cspHeader = helmet.contentSecurityPolicy({
directives: cspDirectives
});
// Explicit sigint handler for running under docker
// See https://github.com/nodejs/node/issues/4182
process.on('SIGINT', function () {
process.exit();
});
// ----------------------------------------------------------------------------
function setupAuth () {
Auth.initialize({
appAdminRole: 'wiseAdmin',
passwordSecretSection: 'wiseService'
});
if (Auth.mode === 'anonymous') {
return;
}
const es = ArkimeConfig.get('usersElasticsearch', 'http://localhost:9200');
User.initialize({
insecure: ArkimeConfig.insecure,
node: es,
caTrustFile: ArkimeConfig.get('caTrustFile'),
prefix: ArkimeConfig.get('usersPrefix'),
apiKey: ArkimeConfig.get('usersElasticsearchAPIKey'),
basicAuth: ArkimeConfig.get('usersElasticsearchBasicAuth')
});
}
// ----------------------------------------------------------------------------
function checkConfigCode (req, res, next) {
console.log(req.body);
if (req.body !== undefined && req.body.configCode !== undefined && req.body.configCode === internals.configCode) {
return next();
} else {
console.log(`Incorrect pin code used - Config pin code is: ${internals.configCode}`);
return res.send(JSON.stringify({ success: false, text: 'Not authorized, check log file' })); // not specific error
}
}
// ----------------------------------------------------------------------------
// Sources
// ----------------------------------------------------------------------------
function newFieldsTS () {
const now = Math.floor(Date.now() / 1000);
if (now <= internals.fieldsTS) {
internals.fieldsTS++;
} else {
internals.fieldsTS = now;
}
}
// ----------------------------------------------------------------------------
/**
* When sources are created they get an api object to interact with the wise service.
*/
class WISESourceAPI {
/**
* Current debug level of wiseService
* @type {integer}
*/
debug = ArkimeConfig.debug;
/**
* Is wiseService running in insecure mode
* @type {boolean}
*/
insecure = ArkimeConfig.insecure;
app = app;
/**
* Get from the config section a value or default
*
* @param {string} section - The section in the config file the key is in
* @param {string} sectionKey - The key to get from the section
* @param {string} [default] - the default value to return if key is not found in section
* @returns {string} - The value found or the default value
*/
getConfig = ArkimeConfig.getFull;
// ----------------------------------------------------------------------------
/**
* Get a list of all the sections in the config file
*
* @returns {string|Array} - A list of all the sections in the config file
*/
getConfigSections = ArkimeConfig.getSections;
// ----------------------------------------------------------------------------
/**
* Get the full config for a section
*
* @param {string} section - The section of the config file to return
* @returns {object} - A list of all the sections in the config file
*/
getConfigSection = ArkimeConfig.getSection;
// ----------------------------------------------------------------------------
/**
* Add a field
*
* @param {string} field - An encoded field definition
*/
addField (field) {
let match = field.match(/field:([^;]+)/);
const fieldName = match[1];
let db;
if ((match = field.match(/db:([^;]+)/))) {
db = match[1];
}
let friendly;
if ((match = field.match(/friendly:([^;]+)/))) {
friendly = match[1];
}
if (WISESource.field2Pos.has(fieldName)) {
return WISESource.field2Pos.get(fieldName);
}
if (ArkimeConfig.debug > 1) {
console.log(`Adding field name:${fieldName} db:${db} friendly:${friendly} from '${field}'`);
}
const pos = internals.fields.length;
newFieldsTS();
internals.fields.push(field);
internals.fieldsSize += field.length + 10;
let offset;
// Create version 0 of fields buf
if (internals.fields.length < 256) {
internals.fieldsBuf0 = Buffer.alloc(internals.fieldsSize + 9);
internals.fieldsBuf0.writeUInt32BE(internals.fieldsTS, 0);
internals.fieldsBuf0.writeUInt32BE(0, 4);
internals.fieldsBuf0.writeUInt8(internals.fields.length, 8);
offset = 9;
for (let i = 0; i < internals.fields.length; i++) {
const len = internals.fieldsBuf0.write(internals.fields[i], offset + 2);
internals.fieldsBuf0.writeUInt16BE(len + 1, offset);
internals.fieldsBuf0.writeUInt8(0, offset + 2 + len);
offset += 3 + len;
}
internals.fieldsBuf0 = internals.fieldsBuf0.slice(0, offset);
}
// Create version 1 of fields buf
internals.fieldsBuf1 = Buffer.alloc(internals.fieldsSize + 9);
internals.fieldsBuf1.writeUInt32BE(internals.fieldsTS, 0);
internals.fieldsBuf1.writeUInt32BE(1, 4);
internals.fieldsBuf1.writeUInt16BE(internals.fields.length, 8);
offset = 10;
for (let i = 0; i < internals.fields.length; i++) {
const len = internals.fieldsBuf1.write(internals.fields[i], offset + 2);
internals.fieldsBuf1.writeUInt16BE(len + 1, offset);
internals.fieldsBuf1.writeUInt8(0, offset + 2 + len);
offset += 3 + len;
}
internals.fieldsBuf1 = internals.fieldsBuf1.slice(0, offset);
internals.fieldsMd5 = cryptoLib.createHash('md5').update(internals.fieldsBuf1.slice(8)).digest('hex');
WISESource.pos2Field.set(pos, fieldName);
WISESource.field2Pos.set(fieldName, pos);
WISESource.field2Info.set(fieldName, { pos, friendly, db });
return pos;
}
// ----------------------------------------------------------------------------
/**
* Add a view
*
* @param {string} viewName - Name of the new view
* @param {string} view - An encoded view definition
*/
addView (viewName, view) {
if (view.includes('require:')) {
let match = view.match(/require:([^;]+)/);
const req = match[1];
match = view.match(/title:([^;]+)/);
if (!match) {
console.log(`ERROR - ${viewName} view is missing 'title:' ${view}`);
return;
}
const title = match[1];
match = view.match(/fields:([^;]+)/);
if (!match) {
console.log(`ERROR - ${viewName} view is missing 'fields:' ${view}`);
return;
}
const fields = match[1];
// Can override the name in the view
match = view.match(/section:([^;]+)/);
if (match) {
viewName = match[1];
}
const parts = req.split('.');
let output = 'if (';
for (let i = 0; i < parts.length; i++) {
if (i > 0) {
output += ' && ';
}
output += 'session';
for (let j = 0; j <= i; j++) {
output += `.${parts[j]}`;
}
}
output += ')\n';
output += ` div.sessionDetailMeta.bold ${title}\n dl.sessionDetailMeta\n`;
for (const field of fields.split(',')) {
const info = WISESource.field2Info.get(field);
if (!info) {
continue;
}
if (!info.db) {
console.log(`ERROR - missing db information for ${field}`);
return;
}
const pos = info.db.lastIndexOf('.');
if (pos === -1) {
output += ` +arrayList(session, '${info.db}', '${info.friendly}', '${field}')\n`;
} else {
output += ` +arrayList(session.${info.db.slice(0, pos)}, '${info.db.slice(pos + 1)}', '${info.friendly}', '${field}')\n`;
}
}
internals.views.set(viewName, output);
} else {
internals.views.set(viewName, view);
}
}
// ----------------------------------------------------------------------------
/**
* Activate a section of a source. Must be called if you want wise to query the source.
* A section is an instance of a source, some sources can have multiple sections.
*
* @param {string} section - The section name
* @param {WISESource} src - A WISESource object
* @param {string|Array} types - An array of the types that this source supports
*/
addSource (section, src, types) {
if (section === undefined || src === undefined || types === undefined) {
console.log(`ERROR - bad call to addSource for ${section}`);
return;
}
src.types = types;
internals.sources.set(section, src);
for (let i = 0; i < types.length; i++) {
addType(types[i], src);
}
}
// ----------------------------------------------------------------------------
/**
* Define all configuration for a field for a source
* @typedef {Object} WISESourceAPI~SourceConfigField
* @property {string} name - The name of the field
* @property {boolean} [required=false] - Must the config value be filled out
* @property {boolean} [password=false] - Is it a password type field that should be hidden
* @property {string} [multiline] - If set this should be split using the value and shown in the UI as a text area
* @property {string} help - The help text to show the user about the field
* @property {string} [ifField] - Only show the field if the 'ifValue' field is set and is equal to 'ifValue'
* @property {string} [ifValue] - Only show the field if the 'ifValue' field is set and is equal to 'ifValue'
* @property {string} [regex] - The value must match the regex to be considered valid
*/
/**
* Define all the configuration for a source.
* This is used by the UI to generate what to display to the admin.
* @typedef {Object} WISESourceAPI~SourceConfig
* @property {string} name - The name of the source
* @property {boolean} singleton - Can there multiple instances of this source
* @property {string} description - Friendly text about the source
* @property {string|Array} types - List of WISE types the source supports
* @property {boolean} [cacheable=true] - Can the source be cached by WISE
* @property {WISESourceAPI~SourceConfigField|Array} fields - The fields for the source
*/
/**
* Add for each source config definition for the UI to use.
*
* @param {string} sourceName - The source name
* @param {WISESourceAPI~SourceConfig} config - The configuration of this source type
*/
addSourceConfigDef (sourceName, configDef) {
if (internals.configDefs[sourceName] === undefined) {
// ALW - should really merge all the types somehow here instead of type2Name
const types = configDef.types || internals.type2Name;
for (let i = 0; i < types.length; i++) {
const type = types[i];
let excludeName;
if (type === 'url') {
excludeName = 'excludeURLs';
} else if (type === 'ip') {
configDef.fields = configDef.fields.concat([
{ name: 'excludeIPs', required: false, multiline: ';', help: 'List of IPs or CIDRs to exclude in WISE lookups' },
{ name: 'onlyIPs', required: false, multiline: ';', help: 'If set, only IPs that match the list of IPs or CIDRs will be looked up by WISE' }
]);
if (configDef.singleton === false && types.length > 0) {
Object.assign(configDef.fields[configDef.fields.length - 2], { ifField: 'type', ifValue: type });
Object.assign(configDef.fields[configDef.fields.length - 1], { ifField: 'type', ifValue: type });
}
continue;
} else {
excludeName = 'exclude' + type[0].toUpperCase() + type.slice(1) + 's';
}
configDef.fields = configDef.fields.concat(
[{ name: excludeName, required: false, multiline: ';', help: 'List of modified glob patterns to exclude in WISE lookups' }]
);
if (configDef.singleton === false && types.length > 0) {
Object.assign(configDef.fields[configDef.fields.length - 1], { ifField: 'type', ifValue: type });
}
}
if (configDef.cacheable !== false) {
configDef.fields = configDef.fields.concat(
[{ name: 'cacheAgeMin', required: false, help: 'Minutes to cache items from previous lookup. (defaults to 60)', regex: '^[0-9]+$' }]
);
}
if (configDef.singleton === false && types.length > 0) {
configDef.fields = configDef.fields.concat([
{ name: 'fields', required: false, multiline: '\\n', help: 'Create a list of fields in Arkime, this may also be defined in the input file. See the Tagger Format docs for more information. In general they look like field:[EXPRESSION];db:[ES FIELD NAME];kind:[FIELD TYPE];friendly:[UI NAME];help:[HELP TEXT];shortcut:[JSON FIELD PATH or CSV column number]' },
{ name: 'view', required: false, multiline: '\\n', help: 'The view to show in session detail when opening up a session with unique fields, this also may be done in the input file. The value for view can either be written in simplified format or in more powerful pug format. For the pug format see Tagger Format in the docs for more information. Simple format looks like require:[toplevel db name];title:[title string];fields:[field1],[field2],[fieldN]' }
]);
}
internals.configDefs[sourceName] = configDef;
}
}
// ----------------------------------------------------------------------------
/**
* Define all configuration for a field for a source
* @typedef {Object} WISESourceAPI~ValueAction
* @property {string} key - The key must be unique and is also used as the right click menu name if the name field is missing
* @property {string} name - The name of the value action to show the user
* @property {string} [url] - The url to send the user, supports special subsitutions, must set url or func
* @property {string} [func] - A javascript function body to call, will be passed the name and value and must return the value, must set url or func
* @property {string} [actionType] - If set to 'fetch' this will replace the menu option with the results of url or func
* @property {string} [category] - Which category of fields should the value action be shown for, must set fields or category. <a href="settings#right-click">View available categories</a>
* @property {string} [fields] - Which fields to show the value action for, must set fields or category
* @property {string} [regex] - When set replaces %REGEX% in the url with the match
* @property {string} [users] - A comma separated list of user names that can see the right click item. If not set then all users can see the right click item.
* @property {string} [notUsers] - (Since 3.0) A comma separated list of user names that can NOT see the right click item. This setting is applied before the users setting above.
*/
/**
* Add a value action set
* @params {string} actionName - The globally unique name of this action, not shown to user
* @params {WISESourceAPI~ValueAction} action - The action
*/
addValueAction (actionName, action) {
internals.valueActions.set(actionName, action);
}
/**
* Add a field action set
* @params {string} actionName - The globally unique name of this action, not shown to user
* @params {WISESourceAPI~ValueAction} action - The action
*/
addFieldAction (actionName, action) {
internals.fieldActions.set(actionName, action);
}
isWebConfig () {
return internals.webconfig;
}
funcName (typeName) {
return funcName(typeName);
}
}
// ----------------------------------------------------------------------------
function loadSources () {
glob(ArkimeConfig.get('sourcePath', path.join(__dirname, '/')) + 'source.*.js', (err, files) => {
files.forEach((file) => {
try {
const src = require(file);
src.initSource(internals.sourceApi);
} catch (err) {
console.log(`WARNING - Couldn't load ${file}\n`, err);
}
});
});
// ALW - should really merge all the types somehow here instead of type2Name
for (let i = 0; i < internals.type2Name.length; i++) {
const type = internals.type2Name[i];
let excludeName;
if (type === 'url') {
excludeName = 'excludeURLs';
} else if (type === 'ip') {
internals.configDefs.wiseService.fields = internals.configDefs.wiseService.fields.concat(
[{ name: 'excludeIPs', required: false, multiline: ';', help: 'List of IPs or CIDRs to exclude in lookups across ALL WISE sources' }]
);
continue;
} else {
excludeName = 'exclude' + type[0].toUpperCase() + type.slice(1) + 's';
}
internals.configDefs.wiseService.fields = internals.configDefs.wiseService.fields.concat(
[{ name: excludeName, required: false, multiline: ';', help: 'List of modified glob patterns to exclude in lookups across ALL WISE sources' }]
);
}
}
// ----------------------------------------------------------------------------
// APIs
// ----------------------------------------------------------------------------
ArkimeUtil.logger(app);
app.use(timeout(5 * 1000));
// client static files --------------------------------------------------------
app.use(favicon(path.join(__dirname, '/favicon.ico')));
// using fallthrough: false because there is no 404 endpoint (client router
// handles 404s) and sending index.html is confusing
app.use('/font-awesome', express.static(
path.join(__dirname, '/../node_modules/font-awesome'),
{ maxAge: dayMs, fallthrough: false }
), ArkimeUtil.missingResource);
app.use('/assets', express.static(
path.join(__dirname, '/../assets'),
{ maxAge: dayMs, fallthrough: false }
), ArkimeUtil.missingResource);
// expose vue bundles (prod) - need to be here because of wildcard endpoint matches
app.use('/static', express.static(
path.join(__dirname, '/vueapp/dist/static'),
{ maxAge: dayMs, fallthrough: false }
), ArkimeUtil.missingResource);
// expose vue bundle (dev)
app.use(['/app.js', '/vueapp/app.js'], express.static(
path.join(__dirname, '/vueapp/dist/app.js'),
{ fallthrough: false }
), ArkimeUtil.missingResource);
app.use(['/app.js.map', '/vueapp/app.js.map'], express.static(
path.join(__dirname, '/vueapp/dist/app.js.map'),
{ fallthrough: false }
), ArkimeUtil.missingResource);
// ----------------------------------------------------------------------------
if (ArkimeConfig.regressionTests) {
app.post('/regressionTests/shutdown', (req, res) => {
process.exit(0);
});
app.post('/regressionTests/checkCode', [jsonParser, checkConfigCode], (req, res) => {
return res.send(JSON.stringify({ success: true, text: 'Authorized' }));
});
}
// ----------------------------------------------------------------------------
/**
* GET - Health check URL
*
* @name "/_ns_/nstest.html"
*/
app.get('/_ns_/nstest.html', [ArkimeUtil.noCacheJson], (req, res) => {
res.end();
});
// ----------------------------------------------------------------------------
/**
* GET - Used by capture to retrieve all the fields created by wise sources
*
* @name "/fields"
* @param {integer} [ver=0] - Version of the encoded binary to return
* @returns {binary}
*/
app.get('/fields', [ArkimeUtil.noCacheJson], (req, res) => {
if (req.query.ver === undefined || req.query.ver === '0') {
if (internals.fields.length < 256) {
res.send(internals.fieldsBuf0);
} else {
console.log("ERROR - This wise server has more then 255 fields, it can't be used with older moloch");
return res.status(404).end();
}
} else {
res.send(internals.fieldsBuf1);
}
});
// ----------------------------------------------------------------------------
/**
* GET - Used by viewer to retrieve all the views being created by wise sources
*
* @name "/views"
* @returns {object} All the views
*/
app.get('/views', [ArkimeUtil.noCacheJson], function (req, res) {
res.send(Object.fromEntries(internals.views));
});
// ----------------------------------------------------------------------------
/**
* GET - Used by viewer to retrieve all the field value actions created by wise sources
*
* @name "/valueActions"
* @returns {object|array} All the actions
*/
app.get(['/rightClicks', '/valueActions'], [ArkimeUtil.noCacheJson], function (req, res) {
res.send(Object.fromEntries(internals.valueActions));
});
// ----------------------------------------------------------------------------
/**
* GET - Used by viewer to retrieve all the field actions created by wise sources
*
* @name "/fieldActions"
* @returns {object|array} All the field actions
*/
app.get('/fieldActions', [ArkimeUtil.noCacheJson], function (req, res) {
res.send(Object.fromEntries(internals.fieldActions));
});
// ----------------------------------------------------------------------------
function globalAllowed (value) {
for (let i = 0; i < this.excludes.length; i++) {
if (value.match(this.excludes[i])) {
if (ArkimeConfig.debug > 0) {
console.log('Found in Global %s Exclude', this.name, value);
}
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------
function globalIPAllowed (value) {
if (this.excludes.find(value)) {
if (ArkimeConfig.debug > 0) {
console.log('Found in Global IP Exclude', value);
}
return false;
}
return true;
}
// ----------------------------------------------------------------------------
function sourceAllowed (src, value) {
const excludes = src[this.excludeName] || [];
for (let i = 0; i < excludes.length; i++) {
if (value.match(excludes[i])) {
if (ArkimeConfig.debug > 0) {
console.log('Found in', src.section, this.name, 'exclude', value);
}
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------
function sourceIPAllowed (src, value) {
if (src.excludeIPs.find(value)) {
if (ArkimeConfig.debug > 0) {
console.log('Found in', src.section, 'IP Exclude', value);
}
return false;
}
if (src.onlyIPs && !src.onlyIPs.find(value)) {
return false;
}
return true;
}
// ----------------------------------------------------------------------------
function funcName (typeName) {
if (typeName === 'url') {
return 'getURL';
}
return 'get' + typeName[0].toUpperCase() + typeName.slice(1);
}
// ----------------------------------------------------------------------------
// This function adds a new type to the internals.types map of types.
// If newSrc is defined will add it to already defined types as src to query.
function addType (type, newSrc) {
let typeInfo = internals.types.get(type);
if (!typeInfo) {
typeInfo = {
name: type,
excludeName: 'exclude' + type[0].toUpperCase() + type.slice(1) + 's',
funcName: funcName(type),
sources: [],
requestStats: 0,
foundStats: 0,
cacheHitStats: 0,
cacheSrcHitStats: 0,
cacheSrcMissStats: 0,
cacheSrcRefreshStats: 0,
excludes: [],
globalAllowed,
sourceAllowed
};
internals.types.set(type, typeInfo);
if (type === 'url') {
typeInfo.excludeName = 'excludeURLs';
}
if (type === 'ip') {
typeInfo.excludeName = 'excludeIPs';
typeInfo.globalAllowed = globalIPAllowed;
typeInfo.sourceAllowed = sourceIPAllowed;
}
for (const src of internals.sources.keys()) {
const source = internals.sources.get(src);
if (source[typeInfo.funcName]) {
typeInfo.sources.push(source);
source.srcInProgress[type] = new Map();
}
}
const items = ArkimeConfig.get(typeInfo.excludeName, '');
if (type === 'ip') {
typeInfo.excludes = new iptrie.IPTrie();
items.split(';').map(item => item.trim()).filter(item => item !== '').forEach((item) => {
const parts = item.split('/');
try {
typeInfo.excludes.add(parts[0], +parts[1] || (parts[0].includes(':') ? 128 : 32), true);
} catch (e) {
console.log(`Error for '${item}'`, e);
process.exit();
}
});
} else {
typeInfo.excludes = items.split(';').map(item => item.trim()).filter(item => item !== '').map(item => RegExp.fromWildExp(item, 'ailop'));
}
} else if (newSrc !== undefined) {
typeInfo.sources.push(newSrc);
newSrc.srcInProgress[type] = new Map();
}
return typeInfo;
}
// ----------------------------------------------------------------------------
function processQuery (req, query, cb) {
if (query.typeName === '__proto__') {
return cb('__proto__ invalid type name');
}
let typeInfo = internals.types.get(query.typeName);
// First time we've seen this typeName
if (!typeInfo) {
typeInfo = addType(query.typeName);
}
typeInfo.requestStats++;
// md5/sha256 have content type
if (query.typeName === 'md5' || query.typeName === 'sha256') {
const parts = query.value.split(';');
query.value = parts[0];
query.contentType = parts[1];
}
// Check if globally allowed
try {
if (!typeInfo.globalAllowed(query.value)) {
return cb(null, WISESource.emptyResult);
}
} catch (e) {
console.log('ERROR', query.typeName, query.value, e);
}
// Fetch the cache for this query
internals.cache.get(query.typeName + '-' + query.value, (err, cacheResult) => {
if (req.timedout) {
return cb('Timed out ' + query.typeName + ' ' + query.value);
}
const now = Math.floor(Date.now() / 1000);
let cacheChanged = false;
if (cacheResult === undefined) {
cacheResult = {};
} else {
typeInfo.cacheHitStats++;
}
async.map(query.sources || typeInfo.sources, (src, mapCb) => {
if (!typeInfo.sourceAllowed(src, query.value)) {
// This source isn't allowed for query
return setImmediate(mapCb, undefined);
}
if (typeof src[typeInfo.funcName] !== 'function') {
return setImmediate(mapCb, undefined);
}
src.requestStat++;
if (cacheResult[src.section] === undefined || cacheResult[src.section].ts + src.cacheTimeout < now) {
if (src.cacheTimeout === -1) {
// Don't count as hit or miss
} else if (cacheResult[src.section] === undefined) {
src.cacheMissStat++;
typeInfo.cacheSrcMissStats++;
} else {
src.cacheRefreshStat++;
typeInfo.cacheSrcRefreshStats++;
}
// Can't use the cache or there is no cache for this source
delete cacheResult[src.section];
// If already in progress then add to the list and return, cb called later;
if (src.srcInProgress[query.typeName] && src.srcInProgress[query.typeName].has(query.value)) {
src.srcInProgress[query.typeName].get(query.value).push(mapCb);
return;
}
// First query for this value
src.srcInProgress[query.typeName].set(query.value, [mapCb]);
const startTime = Date.now();
src[typeInfo.funcName](src.fullQuery === true ? query : query.value, (err, result) => {
src.recentAverageMS = (999.0 * src.recentAverageMS + (Date.now() - startTime)) / 1000.0;
if (!err && result !== undefined) {
src.directHitStat++;
if (src.cacheTimeout !== -1) { // If err or cacheTimeout is -1 then don't cache
cacheResult[src.section] = { ts: now, result };
cacheChanged = true;
}
}
if (err === 'dropped') {
src.requestDroppedStat++;
err = null;
result = undefined;
}
const srcInProgress = src.srcInProgress[query.typeName].get(query.value);
src.srcInProgress[query.typeName].delete(query.value);
for (let i = 0, l = srcInProgress.length; i < l; i++) {
srcInProgress[i](err, result);
}
});
} else {
src.cacheHitStat++;
typeInfo.cacheSrcHitStats++;
// Woot, we can use the cache
setImmediate(mapCb, null, cacheResult[src.section].result);
}
}, (err, results) => {
// Combine all the results together
if (err) {
return cb(err);
}
if (ArkimeConfig.debug > 2) {
console.log('RESULT', typeInfo.funcName, query.value, WISESource.result2JSON(WISESource.combineResults(results)));
}
if (req.timedout) {
cb('Timed out ' + query.typeName + ' ' + query.value);
} else {
cb(null, WISESource.combineResults(results));
}
// Need to update the cache
if (cacheChanged) {
internals.cache.set(query.typeName + '-' + query.value, cacheResult);
}
});
});
}
// ----------------------------------------------------------------------------
function processQueryResponse0 (req, res, queries, results) {
const buf = Buffer.allocUnsafe(8);
buf.writeUInt32BE(internals.fieldsTS, 0);
buf.writeUInt32BE(0, 4);
res.write(buf);
for (let r = 0; r < results.length; r++) {
if (results[r][0] > 0) {
internals.types.get(queries[r].typeName).foundStats++;
}
res.write(results[r]);
}
res.end();
}
// ----------------------------------------------------------------------------
// pos len value
// 0 4 flags
// 4 2 2
// 8 32 md5 of fields
// 40 2 length of fields info if md5 unknown
// 42 L fields info
function processQueryResponse2 (req, res, queries, results) {
const hashes = (req.query.hashes || '').split(',');
const sendFields = !hashes.includes(internals.fieldsMd5);
const buf = Buffer.allocUnsafe(42);
buf.writeUInt32BE(0, 0);
buf.writeUInt32BE(2, 4);
buf.write(internals.fieldsMd5, 8);
if (sendFields) {
// Send all the fields
res.write(buf.slice(0, 40));
res.write(internals.fieldsBuf1.slice(8));
} else {
// Don't send the fields
buf.writeUInt16BE(0, 40);
res.write(buf);
}
// Send the results
for (let r = 0; r < results.length; r++) {
if (results[r][0] > 0) {
internals.types.get(queries[r].typeName).foundStats++;
}
res.write(results[r]);
}
res.end();
}
// ----------------------------------------------------------------------------
/**
* POST - Used by capture to lookup all the wise items
*