-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautomation-CommonServer.yml
1973 lines (1801 loc) · 70.2 KB
/
automation-CommonServer.yml
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
commonfields:
id: CommonServer
version: -1
name: CommonServer
script: |-
// Common functions script
// =======================
// This script will be appended to each server script before being executed.
// Place here all common functions you'd like to share between server scripts.
// ============= Fix vault credentials =============
// =================================================
try {
if(params && typeof params === 'object'){
for(var key in params){
param = params[key];
if(typeof param === 'object' && 'credentials' in param && param.credentials.vaultInstanceId){
param.identifier = param.credentials.user;
}
}
}
}
catch (e) {}
// =================================================
/**
* Returns true if string starts with search string
* @param {String} search - The string to be searched
* @param {Integer} pos - The position in this string at which to begin searching for search string; defaults to 0.
* @return {Boolean} true if string starts with <search> string
*/
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
};
}
/**
* Returns true if string ends with search string
* @param {String} search - The string to be searched
* @param {Integer} this_len - Optional. If provided it is used as the length of search string. If omitted, the default value is the length of the string.
* @return {Boolean} true if string ends with <search> string
*/
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
/**
* Removes the final slash / from the given url. This function should be used to prevent double slash situations such as https://192.12.12.3:8443//api/
*
* @param {String} url - e.g https://some_url.com:8080/ or https://some_url.com:8080
* @return {String} url without slash in the end - e.g https://some_url.com:8080
*/
function fixUrl(url) {
if (url.endsWith('/')) {
return url.slice(0, -1);
}
return url;
}
/**
* Removes the final slash / from the given url. This function should be used to prevent double slash situations such as https://192.12.12.3:8443//api/
*
* @param {String} url - e.g https://some_url.com:8080/ or https://some_url.com:8080
* @return {String} url without slash in the end - e.g https://some_url.com:8080
*/
var removeLastSlash = fixUrl;
/**
* Formats a string in place
* @return {String} The formatted string
*/
String.prototype.format = function() {
var content = this;
for (var i=0; i < arguments.length; i++)
{
var replacement = '{' + i + '}';
content = content.replace(replacement, arguments[i]);
}
return content;
}
cleanSingleObject = function(contents) {
var cleanContents = {};
var keys = Object.keys(contents);
for (var i = 0; i < keys.length; i++) {
if (contents[keys[i]] || contents[keys[i]] === false) {
cleanContents[keys[i]] = contents[keys[i]];
}
}
return cleanContents;
}
/**
* Clean an object from empty fields
* @param {Object} obj - The object to be cleaned
* @return {Object} The cleaned object
*/
var cleanObject = function(obj) {
if (obj instanceof Array) {
var res = [];
for (var j in obj) {
res.push(cleanObject(obj[j]));
}
return res;
}
return cleanSingleObject(obj);
}
/**
* Merge a list of objects into a single object.
* Note: to avoid loss of data, use only on objects with foreign properties.
* @param {Array} objs - An array of arrays to be merged
* @return {Object} the merged array
*/
function mergeForeignObjects(objs) {
var merged = {};
for (var i in objs) {
for (var j in objs[i]) {
merged[j] = objs[i][j];
}
}
return merged;
}
/**
* Creates a string from an object
* @param {JSON | String} o - The object to create the string from
* @param {String} [delimiter] - The delimiter of the string representation of arrays
* @return {String} A string which represents the object
*/
function objToStr(o, delimiter) {
if(!delimiter || typeof(delimiter) !== 'string') {
delimiter = ',';
}
if (Array.isArray(o)) {
return o.map(function(v) {
return objToStr(v);
}).join(delimiter);
} else if (typeof(o) === 'string') {
return o;
} else if (typeof(o) === 'number') {
return '' + o;
} else {
return JSON.stringify(o);
}
}
MARKDOWN_CHARS = "\\`*_{}[]()#+-!|"
/**
* Escapes markdown characters in a string
* @param {String} st - The string to fix
* @param {Boolean} [replaceNewlines] - Should newlines be replaced with '<br>'
* @return {String} A string with the markdown characters escaped
*/
var stringEscapeMD = function(st, replaceNewlines, minimal_escaping) {
if (typeof(st) != 'string') {
return st;
}
if (replaceNewlines) {
st = st.replace(/\r\n/g, '<br>');
st = st.replace(/\n/g, '<br>');
st = st.replace(/\r/g, '<br>');
}
var escapedSt = '';
if (minimal_escaping) {
escapedSt = st.replace(/\|/g, '\\|');
} else {
for (var i = 0; i < st.length; i++) {
if (MARKDOWN_CHARS.indexOf(st[i]) > -1) {
escapedSt += '\\';
}
escapedSt += st[i];
}
}
return escapedSt;
};
var HTML_ENTITY_MAP = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
/**
* Escapes html characters in a string
* @param {String} st - The string to fix
* @return {String} A string with the html characters escaped
*/
var stringEscapeHTML = function(st) {
return String(st).replace(/[&<>"'`=\/]/g, function (s) {
return HTML_ENTITY_MAP[s];
});
}
/**
* Converts textual keys to pascal format (e.g. "Threat Score" -> "ThreatScore")
* @param {Object} dict - The object to be converted
* @return {Object} The converted object
*/
var convertKeysToPascalCase = function(dict) {
var pascalDict = {};
for (var key in dict) {
var pascalCaseKey = key.replace(/\w+/g, function(w) { return w[0].toUpperCase() + w.slice(1).toLowerCase(); }).replace(/ /g, '');
pascalDict[pascalCaseKey] = dict[key];
}
return pascalDict;
}
/**
* Gets a parameter that can be either an array, a JSON array or a string list separated by ',' and returns an array
* @param {Object} [arg] - The object to be converted
* @return {Array} An array representing the given object
*/
function argToList(arg) {
if (!arg) {
return [];
}
if (Array.isArray(arg)) {
return arg;
}
if (typeof(arg) === 'string') {
if (arg[0] === '[' && arg[arg.length - 1] === ']') {
return JSON.parse(arg);
}
return arg.split(',');
}
return arg;
}
/**
* Converts a JSON demisto table to a Markdown table
* @param {String} name - The name of the table
* @param {Object} t - the JSON table - Array of objects with the same keys
* @param {Array|String} [headers] - The output markdown table will show only these headers (by order). Use a single string in case of a value type array (Optional).
* @param {String} [cellDelimiter] - The delimiter of the string representation of arrays (Optional).
* @param {Function} [headerTransform] - A transformation function for the header keys in the markdown table (Optional).
* @return {String} A string representing the markdown table
*/
function tableToMarkdown(name, t, headers, cellDelimiter, headerTransform) {
if (t && !(t instanceof Array)){
t = [t];
}
if(headers && !(headers instanceof Array) && typeof(headers) !== 'object'){
headers = [headers];
}
//in case of headers was not provided (backward compatibility)
if ((!(headers) || !(headers instanceof Array) || headers.length === 0) && t && t.length > 0 && typeof(t[0]) === 'object') {
headers = GetAllObjectsProperties(t);
}
if(!headers || !(headers instanceof Array) || headers.length === 0) {
return 'No data returned\n';
}
var mdResults = '';
if (name) {
mdResults = '### ' + name + '\n';
}
if (t && t.length) {
var newHeaders = [];
if(!headerTransform){
headerTransform = function(string){return string;};
}
for(var i=0; i<headers.length; i++){
newHeaders.push(headerTransform(headers[i]));
}
if (newHeaders.length > 1) {
mdResults += newHeaders.join('|') + '\n';
} else {
mdResults += newHeaders[0] + '|' + '\n';
}
var sep = [];
headers.forEach(function(h){
sep.push('---');
});
if (sep.length === 1) {
sep[0] = sep[0]+'|';
}
mdResults += sep.join('|') + '\n';
t.forEach(function(entry){
var vals = [];
if(typeof(entry) !== 'object' && !(entry instanceof Array)){
var obj = {};
obj[headers[0]] = entry;
entry = obj;
}
headers.forEach(function(h){
if(entry[h] === null || entry[h] === undefined) {
vals.push(' ');
} else {
vals.push(stringEscapeMD(formatCell(entry[h], cellDelimiter), true, true) || ' ');
}
});
if (vals.length === 1) {
vals[0] = vals[0]+'|';
}
mdResults += vals.join('|') + '\n';
});
} else{
mdResults += 'No data returned\n';
}
return mdResults;
}
var tblToMd = tableToMarkdown;
/**
* Converts an array of stings to markdown table
* @param {Array} arr - from strings
* @param {String} [header] - The output markdown table will show only these headers (by order) (Optional).
* @return {String} A markdown string of tables. If input array was empty, will return "No results" instead.
*/
function arrayToMarkdownTable(arr, header) {
if (!arr) {
return 'No results';
}
if (!Array.isArray(arr)) {
throw arr + ' is not an array';
}
if (arr.length === 0) {
return 'No results';
}
if (typeof arr[0] === 'object') {
throw 'arrayToMarkdownTable should receive arr which contain objects but simple types like string, int, bool'
}
if (!header) {
throw 'header is required for arrayToMarkdownTable';
}
var md = '|' + header + '|\n-';
arr.forEach(function(item) {
md += '\n|' + item + '|';
});
return md;
}
/**
* Converts underscore case strings to camel case
* @param {String} string - The string to be converted - i.e. hello_world
* @return {String} - The converted string - i.e. HelloWorld
*/
var underscoreToCamelCase = function(string) {
var ret_string = '_'+string;
return ret_string.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
};
/**
* Converts dots into spaces and capitalizes
* @param {String} string - The string to be converted - i.e. hello.world
* @return {String} - The converted string - i.e. Hello World
*/
var dotToSpace = function(string) {
var ret_string = '.'+string;
return ret_string.replace(/\.([a-z,A-Z])/g, function (g) { return ' '+g[1].toUpperCase(); });
};
/**
* Converts pascal strings to human readable (e.g. "ThreatScore" -> "Threat Score")
* @param {String} string - The string to be converted
* @return {String} - The converted string
*/
var pascalToSpace = function(string) {
return string.replace(/([a-z][A-Z])/g, function (g) { return g[0] + ' ' + g.slice(1); });
};
function mapObjFunction(mapFields, filter) {
var transformSingleObj= function(obj) {
var res = {};
mapFields.forEach(function(f) {
if(!filter || filter(f)){
res[f.to] = dq(obj, f.from);
}
});
return res;
};
return function(obj) {
if (obj instanceof Array) {
var res = [];
for (var j=0; j < obj.length; j++) {
var current = transformSingleObj(obj[j]);
if (current) {
res.push(current);
}
}
return res;
}
return transformSingleObj(obj);
};
}
function createContext(data, id) {
var createContextSingle = function(obj) {
var res = {};
var keys = Object.keys(obj);
keys.forEach(function(k) {
var values = k.split('.');
var current = res;
for (var j = 0; j<values.length - 1; j++) {
if (!current[values[j]]) {
current[values[j]] = {};
}
current = current[values[j]];
}
current[values[j]] = obj[k];
});
if (!res.ID && id) {
res.ID = id;
}
return res;
};
if (data instanceof Array) {
var res = [];
for (var j=0; j < data.length; j++) {
res.push(createContextSingle(data[j]));
}
return res;
}
return createContextSingle(data);
}
var isFunction = function(functionToCheck) {
return functionToCheck && typeof functionToCheck === 'function';
}
/**
* Creates a dq query string. Used by easyDQ.
* @param {string} path - the path to be parsed
* @param {function | string} filter - filter string (e.g. 'val.id===<some id>'') or filter function (e.g. function(obj){return obj.name === 'name';} )
* @param {function | string} returnValue - string or function that defines returned data format (e.g. '{Name : val.name}' or function(val){return {Name:val.name};} )
* @return {string} - the query string to pass to dq function
*/
var dqQueryBuilder = function(path, filter, returnValue){
var query = path;
if(!filter){
filter = 'true';
}
if(isFunction(filter)){
filter = filter.toString() + '(val)';
}
if(typeof filter !== 'string'){
throw 'dqQueryBuilder: Filter type is neither a function nor a string';
}
query += '('+filter+')';
if(returnValue){
if(isFunction(returnValue)){
returnValue = returnValue.toString() + '(val)';
}
if(typeof returnValue !== 'string'){
throw 'dqQueryBuilder: return value for DQ is neither a function nor a string';
}
query += '='+returnValue;
}
return query;
};
/**
* Creates a dq query from arguments and calls dq
* @param {Object} data - The raw data object
* @param {String} path - The path to be parsed
* @param {Function | String} filter - A filter string (e.g. 'val.id===<some id>'') or a filter function (e.g. function(obj){return obj.name === 'name';} )
* @param {Function | String} returnValue - string or function that defines the returned data format (e.g. '{Name : val.name}' or function(val){return {Name:val.name};} )
* @return {Object} - The value returned from the dq function
*/
easyDQ = function(data, path, filter, returnValue){
return dq(data, dqQueryBuilder(path, filter, returnValue));
};
/* creates array from obj, if obj is not already an array */
var toArray = function(obj){
if(obj && !Array.isArray(obj))
return [obj];
return obj;
};
/**
* Creates a war room entry
* @param {Object} result - The raw result to be parsed
* @param {Object} translator - Maps raw data to the war room output. Should be of the following format:
* ```
* {
* contextPath: <context-path>,
* title: <war-room-title>,
* data: [
* {to: <dest-key>, from: <orig-key>, (optional) humanReadable: <true/false>},
* {to: <dest-key>, from: <orig-key>, (optional) humanReadable: <true/false>},
* ...
* ]
* }
* ```
* - dest-key/orig-key should be sparated with '.' (e.g. 'File.Malicious')
* - dest-key is also used for war room table headers
* - humanReadable states whether field should appear in war room table. Default is true.
* @param {function} [MDfilter] - (optional) filters out fields that shouldn't be displayed in warroom (returns true/false). Default uses humanReadable field.
* @param {function} [headerTransform] - transform mark down headers to readable format.
* @return {Object} - the war room entry
*/
var createEntry = function(result, translator, MDfilter, headerTransform) {
/* filters out all fields where humanReadable is false */
var filter = function(obj) {
if(obj.humanReadable !== false) {
return true;
}
return false;
};
if (MDfilter) {
filter = MDfilter;
}
var entry = {
Type: entryTypes.note,
Contents: result,
ContentsFormat: formats.json,
ReadableContentsFormat: formats.markdown
};
var content = translator.innerPath ? dq(result, translator.innerPath) : result;
var translatedContext = mapObjFunction(translator.data) (content);
var translatedMD = mapObjFunction(translator.data, filter) (content);
entry.HumanReadable = tableToMarkdown(translator.title, translatedMD, undefined, undefined, headerTransform || dotToSpace);
entry.EntryContext = {};
var context = createContext(translatedContext);
entry.EntryContext[translator.contextPath] = context;
return entry;
};
/**
* Converts a demisto table in JSON form to a HTML table
* @param {String} name - the name of the table
* @param {Object} t - the JSON table - Array of objects with the same keys
* @param {Array} [headers] - optional, the output markdown table will show only these headers (by order)
* @param {String} [cellDelimiter] - The delimiter of the string representation of arrays (Optional).
* @return {String} A string representation of the html result
*/
function tableToHTML(name, t, headers, cellDelimiter) {
if (t && !(t instanceof Array)){
t = [t];
}
//in case of headers was not provided (backward compatibility)
if ((!headers || !headers instanceof Array || headers.length === 0) && t && t.length > 0){
headers = GetAllObjectsProperties(t);
}
if(!headers || !headers instanceof Array || headers.length === 0) {
return 'No data returned<br/>';
}
var htmlResults = '';
if (name) {
htmlResults = '<h3>' + name + '</h3><br/>';
}
if (t && t.length) {
htmlResults += '<table><tr>' + headers.reduce(function(acc, v) {return acc + '<th>' + v + '</th>';}, '') + '</tr>';
t.forEach(function(entry){
var vals = [];
headers.forEach(function(h){
vals.push((!!entry[h] || entry[h]==0) ? stringEscapeHTML(formatCell(entry[h], cellDelimiter)) : ' ');
});
htmlResults += '<tr>' + vals.reduce(function(acc, v) {return acc + '<td>' + v + '</td>';}, '') + '</tr>';
});
htmlResults += '</table>';
} else{
htmlResults += 'No data returned<br/>';
}
return htmlResults;
}
/**
* Verifies that the given fields exists in the content and verifies its value
* @param {String} fieldName - the name of the field (dq format)
* @param {Object} expectedValue - the value to verify
* @param {String} [comparisonType] - 'stringContains' or 'stringEquals'. Default is 'stringEquals'
* @return {Object} Returns the value if value at the field matches, throws an error an exeption otherwise
*/
function verifyContextField(fieldName, expectedValue, comparisonType) {
value = dq(invContext, fieldName);
if (value === undefined) {
throw 'Field does not exist: {0}.'.format(fieldName);
}
if (expectedValue !== undefined) {
if (comparisonType == 'stringContains') {
if (value.indexOf(expectedValue) == -1) {
throw 'Field {0} does not contain the expected string. Value: {1}, expected: {2}.'.format(fieldName, value, expectedValue);
}
} else {
if (value != expectedValue) {
throw 'Field {0} does not match. Value: {1}, expected: {2}.'.format(fieldName, value, expectedValue);
}
}
}
return value;
}
/**
* Get all properties of objects in an array.
* @param {Array} t - Array of elements
* @return {Array} - Array of object properties
*/
function GetAllObjectsProperties(t) {
var properties = {};
t.forEach(function (element) {
for(var prop in element) {
properties[prop] ='';
}
});
return Object.keys(properties).sort();
}
/**
* Checks if the given string represents a valid IPv4 address
* @deprecated please use isValidIP which really checks IP for validity
* @param {String} ip - the string to check
* @return {Boolean} true if valid IPv4 address
*/
function isIp(ip) {
var d = ip.split('.'), i = d.length;
if (i !== 4) {
return false;
}
var ok = true;
while (i-- && ok) {
ok = d[i].length !== 0 && !isNaN(parseInt(d[i])) && d[i] > -1 && d[i] < 256;
}
return ok;
}
var entryTypes = {note: 1, downloadAgent: 2, file: 3, error: 4, pinned: 5, userManagement: 6, image: 7, plagroundError: 8, entryInfoFile: 9, map: 15, playgroundError: 8};
var formats = {html: 'html', table: 'table', json: 'json', text: 'text', dbotResponse: 'dbotCommandResponse', markdown: 'markdown'};
var dbotscores = {critical : 4, high: 3, medium: 2, low: 1, informational: 0.5, unknown: 0};
/**
* Returns the name of the file as stored in our investigation artifacts on disk.
* This should be used when sending files to d2 scripts as you can see in StaticAnalyze.
* @param {String} entryId - The entry ID containing the file
* @return {String} The name of the file in our artifact repository
*/
function fileNameFromEntry(entryId) {
var parts = entryId.split('@');
if (parts.length !== 2) {
return null;
}
var res = executeCommand('getEntry', {id: entryId});
if (res && Array.isArray(res) && res.length === 1) {
return parts[1] + '_' + res[0].FileID;
}
return null;
}
/**
* Closes the current investigation
* @param {Object} args - Closing details (what happened, damage, etc.)
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function closeInvestigation(args) {
return executeCommand('closeInvestigation', args);
}
/**
* Sets severity an incident. The incident must be related to current investigation.
* @param {Object} arg - Has 2 keys, 'id' - the incident id, 'severity' - the new severity value (Critical, High, Medium etc.).
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setSeverity(arg) {
return executeCommand('setSeverity', arg);
}
/**
* Sets fields of the incident. The incident must be related to current investigation and be the only incident in it.
* @param {Object} args - Has 5 optional keys: type, severity, details, name and systems of the incident.
* systems should follow this string template: '1.1.1.1,10.10.10.10'
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setIncident(args) {
return executeCommand('setIncident', args);
}
/**
* Create a new incident with the fields specified, only if an incident with the same name does not exist as an active incident.
* If an active incident with the same name exists, ignore the request.
* @param {Object} args - Has 5 optional keys: type, severity, details, name and system of the incident.
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function createNewIncident(args) {
return executeCommand('createNewIncident', args);
}
/**
* Sets playbook according to type.
* @param {String} type - The incident type, according to which the playbook is chosen
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setPlaybookAccordingToType(type) {
return executeCommand('setPlaybookAccordingToType', {type: type});
}
/**
* Sets Owner to an incident. The incident must be related to current investigation.
* @param {Object} name - The user name of the owner
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setOwner(name) {
return executeCommand('setOwner', { owner: name });
}
/**
* Assigns a playbook task to a user.
* @param {Object} arg - Has 2 keys, 'id' - the task id, 'assignee' - the user name of the assignee.
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function taskAssign(arg) {
return executeCommand('taskAssign', arg);
}
/**
* Sets task due date.
* @param {Object} arg - Has 2 keys, 'id' - the task id, 'dueDate' - time string in UTC format (To get current time use: 'new Date().toUTCString()').
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setTaskDueDate(arg) {
return executeCommand('setTaskDueDate', arg);
}
/**
* Sets investigation playbook
* @param {String} name - The playbook name.
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function setPlaybook(name) {
return executeCommand('setPlaybook', { name: name });
}
/**
* Adds task to Workplan
* @param {Object} arg - has 5 keys:
* - 'name' - (mandatory) The new task's name.
* - 'description' - (optional) The new task's description.
* - 'script' - (optional) Name of script to be run by task.
* - 'addBefore' - (optional, refers to task id) Insert new task before specified task (when using this argument do not use afterTask)
* - 'addAfter' - (optional, refers to task id) Insert new task after specified task (when using this argument do not use beforeTask)
* @return {Array} An array with an error entry if an error occurred, an empty array otherwise
*/
function addTask(arg) {
return executeCommand('addTask', arg);
}
/**
* Encode json object to URL. Supports multiple arguments of the same value if input is an array.
* @param {Object} args - The object to encode.
* @return {String} in case of error will be empty. In Case of success will return the URL string.
*/
function encodeToURLQuery(args) {
var query = '';
if (args) {
var keys = Object.keys(args);
if (keys.length > 0) {
query = '?';
for (var i = 0; i<keys.length; i++) {
if (i !== 0) {
query += '&';
}
if (Array.isArray(args[keys[i]])) {
for (var j=0; j<args[keys[i]].length; j++) {
if (j !== 0) {
query += '&';
}
query += encodeURIComponent(keys[i]) + '=' + encodeURIComponent(args[keys[i]][j]);
}
} else {
query += encodeURIComponent(keys[i]) + '=' + encodeURIComponent(args[keys[i]]);
}
}
}
}
return query;
}
/**
* Translate ThreatConnect rating to score
* @param {rating} TC rating as int
* @return {score} Int (between 0 and 3)
*/
function threatConnectRatingToScore(rating) {
var tcScore = 0;
if (rating == 2 || rating == 1) {
tcScore = 2;
}
if (rating > 2) {
tcScore = 3;
}
return tcScore;
}
/**
* Check the list of available modules to see whether a command is currently available to be run.
* @param {Object} cmd - The command to check.
* @return {bool} True if command is available, false otherwise
*/
function isCommandAvailable(cmd) {
var all = getAllSupportedCommands();
var modules = Object.keys(all);
for(var i = 0; i < modules.length ; i++) {
var modCmds = all[modules[i]];
if (modCmds) {
for(var j = 0; j < modCmds.length ; j++) {
if (modCmds[j].name === cmd) {
return true;
}
}
}
}
return false;
}
/**
* Check if the given entry is an error entry
* @param {Object} entry - The entry to check
* @return {Boolean} True if this is an error entry, false otherwise
*/
function isError(entry) {
return entry && typeof entry === 'object' && entry.Type === entryTypes.error;
}
/**
* Check if the given result entry is an array and is not an error
* @param {Array} res - The result from the execute to check
* @return {Boolean} True if this is a valid result
*/
function isValidRes(res) {
return res && Array.isArray(res) && res.length && !isError(res[0]);
}
/**
* If the given value exists, return it. Otherwise, return default and if not provided 'Unknown'
* @param {Object} v - Value that can be anything
* @param {Object} [def] - Default value. If not provided will be 'Unknown'
* @return {Object} Value if exists, default otherwise
*/
function nvl(v, def) {
return v ? v : def ? def : 'Unknown';
}
/**
* Flatten the fields into a map of dot notation key and value
* @param {Object} obj - The object to iterate on
* @param {String} [path] - (optional) The path so far in dot notation
* @param {Object} flat - The collected object result
* @return {Object} An object with keys that are dot notation and values
*/
function flattenFields(obj, path, flat) {
if (obj) {
if (typeof obj === 'object') {
var keys = Object.keys(obj);
for (var f=0; f<keys.length; f++) {
flattenFields(obj[keys[f]], !!path ? path + '.' + keys[f] : keys[f], flat);
}
} else if (Array.isArray(obj)) {
for (var i=0; i<obj.length; i++) {
flattenFields(obj[i], !!path ? path + '.' + i : '' + i, flat);
}
} else {
flat[path] = obj.toString();
}
}
}
var formatCell = objToStr;
/**
* Convert a given object to md while descending multiple levels
* @param {Object} o - The object to convert - can be an array as well
* @return {String} - The converted markdown string
*/
function objToMd(o) {
var flat = {};
flattenFields(o, '', flat);
var keys = Object.keys(flat);
keys.sort();
var md = 'Key | Value\n- | -\n';
for (var i=0; i<keys.length; i++) {
md += keys[i] + ' | ' + flat[keys[i]] + '\n';
}
return md;
}
/**
* Convert a given object to md list (-) while each value is converted to a simple string
* @param {Object} o - The object to convert
* @param {String} t - The title of the list
* @return {String} The markdown string
*/
function objToList(o, t) {
var md = '';
if (o) {
md += '### ' + t + '\n';
var keys = Object.keys(o);
for (var i=0; i<keys.length; i++) {
md += '- ' + keys[i] + ': ' + objToStr(o[keys[i]]) + '\n';
}
}
return md;
}
/**
* Converts the given timestamp to a string
* @param {int} timestamp - The timestamp in UNIX format
* @return {String} A string representing the time - e.g. 'Thu, 11 May 2017 11:18:56 UTC'
*/
function convertTimestampToString(timestamp) {
return (new Date(parseInt(timestamp))).toISOString();
}
/**
* Converts the given number (uint32) to an IP address string
* @param {int} num - The number to convert
* @return {String} A string representing the IP address - e.g. '192.168.2.1'
*/
var numToIp = function(num) {
var ip = num % 256;
for (var i = 3; i > 0; i--) {
num = Math.floor(num / 256);
ip = num % 256 + '.' + ip;
}
return ip;
}
/**
* Convert a given array to a markdown table
* @param {Array} arr - The array to convert
* @return {String} - The converted markdown string
*/
function arrToMd(arr) {
if (!arr || arr.length === 0) {
return '';
}
return tableToMarkdown('', arr);
}
/**
* Query the given object with the given path and retrive it
* @deprecated please use dq which has the full functionality
* @param {Object} obj - The object to query
* @param {String} path - The path to retrieve from the object
* @return {Object} The value of the path if the path exists, null otherwise
*/
function jq(obj, path) {
if (!obj || !path || (typeof obj !== 'object' && !Array.isArray(obj))) {
return null;
}
var parts = path.split('.');
for (var i=0; i<parts.length; i++) {
// First, handle array option
var part = parts[i].match(/([a-zA-Z0-9_]*)(\[([0-9]+)\])?/);
if (part[3]) {
// If array of property and not top array
if (part[1]) {
if (obj.hasOwnProperty(part[1]) && Array.isArray(obj[part[1]])) {
obj = obj[part[1]][parseInt(part[3])];
} else {
return null;
}
} else {
if (Array.isArray(obj)) {
obj = obj[parseInt(part[3])];
} else {
return null;
}
}
} else {
// Not an array
if (obj.hasOwnProperty(part[1])) {
obj = obj[part[1]];
} else {