CybereasonAPI.psm1

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
<#
.SYNOPSIS
This cmdlet is used to authenticate to the Cybereason API. Once this is done a global $CybereasonSession variable is created that will be used for all other cmdlets in this module.
 
 
.DESCRIPTION
This cmdlet creates a $CybereasonSession variable that will be used with all the other cmdlets in this module to authenticate requests made to the Cybereason API.
 
 
.PARAMETER Server
This parameter defines the server IP address or domain name your Cybereason server is running on
 
.PARAMETER Port
This parameter is used to define the port your Cybereason server is on. This is usually 443 or 8443. The default value is 443.
 
.PARAMETER Username
This is the email address you use to sign into Cybereason
 
.PARAMETER Passwd
This is the password you use to sign into your Cybereason account. The session history gets cleared to attempt preventing the password from appearing in the session logs. This does not clear the events logs. I suggest only letting administrators view the PowerShell event logs.
 
.PARAMETER Authenticator
This parameter is for NON-API Cybereason users to authenticate to Cyberason using Two Factor Authentication (TFA). When used, the only cmdlet in this module that will work is Get-CybereasonThreatIntel
 
 
.EXAMPLE
Connect-CybereasonAPI -Server 123.45.67.78 -Port 8443 -Username api-user@cyberason.com -Passwd "Password123!" -ClearHistory
# This example authenticates to the Cybereason API and creates a $CybereasonSession variable to be used by other cmdlets. This also clears the PowerShell command history of the current session as well as the HistorySavePath file value.
 
.EXAMPLE
Connect-CybereasonAPI -Server 123.45.67.78 -Port 443 -Username admin-user@cyberason.com -Passwd "Password123!" -Authenticator 123123 -ClearHistory
# IMPORTANT: Only non-api users are able to use Two Factor Authentication (TFA). This prevents organization level cmdlets from working. Only Get-CybereasonThreatIntel works after authenticating with a non-API user
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Connect-CybereasonAPI {
    [CmdletBinding()]
        param(
            [Parameter(
                Position=0,
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the email you wish to sign in with `n[E] EXAMPLE: admin.user@domain.com")]  # End Parameter
            [ValidateNotNullOrEmpty()]
            [String]$Username,

            [Parameter(
                Position=1,
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateNotNullOrEmpty()]
            [String]$Passwd,

            [Parameter(
                Position=2,
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the IP address or hostname of your Cybereason server. DO NOT include the port `n[E] EXAMPLE: 10.0.0.1`n[E] EXAMPLE: asdf.cybereason.com")]
            [ValidateNotNullOrEmpty()]
            [String]$Server,

            [Parameter(
                Position=3,
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateRange(1,65535)]
            [String]$Port = "443",

            [Parameter(
                Position=4,
                Mandatory=$False,
                ValueFromPipeline=$False,  # End Parameter
                HelpMessage="`n[H] Enter the code from your authenticator app `n[E] EXAMPLE: 123456")]
            [String]$Authenticator,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$ClearHistory
        )  # End param

    Write-Verbose "Validating username parameter is in email address format"
    Try
    {

        $Null = [MailAddress]$Username

    }  # End Try
    Catch
    {

        Throw "[x] The username you defined is not a valid email address."

    }  # End Catch


    $Uri = "https://" + $Server + ":" + $Port + "/login.html"

    Write-Verbose "Ensuring TLS 1.2 is being used"
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    $Body = @{
        username="$Username"
        password="$Passwd"
    }  # End Body
    $Results = Invoke-WebRequest -Method POST -Uri $Uri -ContentType "application/x-www-form-urlencoded" -Body $Body -SessionVariable 'CybereasonSession'

    If ($Authenticator.Length -gt 0)
    {

        $TfaBody = @{
            totpCode="$Authenticator"
            submit="Login"
        }  # End Body
        $Results = Invoke-WebRequest -Method POST -Uri $Uri -ContentType "application/x-www-form-urlencoded" -Body $TfaBody -SessionVariable 'CybereasonSession'

    }  # End If


    Write-Verbose "Sending request to $Uri"
    If ($Results.StatusCode -eq '200')
    {

        Write-Output "[*] Successfully created an authenticated session to the Cybereason API."

    }  # End If
    Else
    {

        Write-Warning "[!] Status code returned was not a value of 200. Value received is below"
        $Results.StatusCode
        $Results

    }  # End Else

    $Global:CybereasonSession = $CybereasonSession
    $Global:Server = $Server
    $Global:Port = $Port

    If ($ClearHistory.IsPresent)
    {

        Write-Output "[*] Using the Clear-History command to clear the current PowerShell sessions command history"
        Clear-History

        Write-Output "[*] Deleing the PowerShell HistorySavePath file which stores a copy of the previous command history"
        Remove-Item (Get-PSReadlineOption).HistorySavePath

        Write-Warning "This PowerShells session history has just been cleared to prevent the clear text password from appearing in log files. This does not clear the PowerShell Event log. Only allow administrators to view that log."

    }  # End If
    Else
    {

        Write-Warning "The -ClearHistory parameter was not specified. If you wish to remove the clear text password from this session command history you will need to manually issue the command Clear-History"

    }  # End Else

}  # End Function Connect-CybereasonAPI


<#
.SYNOPSIS
This cmdlet was created to quickly and easily perform all Threat Intelligence tasks that the Cybereason API allows such as looking up a domain or IP address.
 
 
.DESCRIPTION
Easily and quickly communicate with the Cyberason API to discover threat intel on an IP address, domain, product, process, file extension or check for database updates avaialable in those categories.
 
 
.PARAMETER Md5Hash
This parameter accepts an MD5 hash of a file to check the reputation of the files signature against the Cybereason database. The -FileToHash parameter can be used if you do not already have the hash value available
 
.PARAMETER FileToHash
This parameter defines a file that you want to check against the cybereason reputation database. If you do not have the hash of the file this will automtically get the hash for you and check it's reputation
 
.PARAMETER Domain
This parameter defines a domain to check against the malicious domain database and discover info such as when the domain was first registered
 
.PARAMETER IPAddress
This parameter defines the IP address to be checked against the Cyberason malicious IP address database
 
.PARAMETER ProductClassification
This switch parameter indicates you wish to retrieve product classification information
 
.PARAMETER ProcessClassification
This switch parameter indicates you wish to retrieve process classification information
 
.PARAMETER ProcessHierarchy
This switch parameter indicates you wish to retrieve process hierarchy information
 
.PARAMETER FileExtension
This switch parameter indicates you wish to retrieve file extension information
 
.PARAMETER PortInfo
This switch parameter indicates you wish to retrieve port information
 
.PARAMETER CollectionInfo
This switch parameter indicates you wish to retrieve collection information
 
.PARAMETER IPReputation
This switch parameter indicates you wish to retrieve a list of IP address reputations
 
.PARAMETER DomainRep
This switch parameter indicates you wish to retrieve a list of domain reputations
 
.PARAMETER DbUpdateCheck
This switch parameter indicates you wish to check for database updates
 
 
.EXAMPLE
Get-CybereasonThreatIntel -Md5Hash 'D7AB69FAD18D4A643D84A271DFC0DBDF'
# This example returns details on a file’s reputation based on the Cybereason threat intelligence service using the MD5 hash. If you do not already have the hash, use the -FileToHash parameter to have it obtained automtacilly for you.
 
.EXAMPLE
Get-CybereasonThreatIntel -Md5Hash 'D7AB69FAD18D4A643D84A271DFC0DBDF','5D997A651DA137B68B15EAC157A4FC42'
# This example returns details on two file reputations based on the Cybereason threat intelligence service using the MD5 hash. If you do not already have the hash, use the -FileToHash parameter to have it obtained automtacilly for you.
 
.EXAMPLE
Get-CybereasonThreatIntel -Md5Hash (Get-FileHash -Algorithm MD5 -Path C:\Users\Public\Desktop\AlwaysInstallElevatedCheck.htm).Hash
# This example gets the file hash of a file on the OS and determines if it is malicious or not
 
.EXAMPLE
Get-CybereasonThreatIntel -FileToHash C:\Windows\System32\cmd.exe
# This example returns details on the file C:\Windows\System32\cmd.exe's reputation based on the Cybereason threat intelligence service. This determines the MD5 hash automatically of the file you define. If you already have the hash enter it using the -Md5Hash parameter instead of this one.
 
.EXAMPLE
Get-CybereasonThreatIntel -FileToHash 'C:\Windows\System32\cmd.exe','C:\Windows\Sysmon.exe'
# This example returns details on the file C:\Windows\System32\cmd.exe and C:\WIndows\Sysmon.exe's reputation based on the Cybereason threat intelligence service. This determines the MD5 hash automatically of the file you define. If you already have the hash enter it using the -Md5Hash parameter instead of this one.
 
.EXAMPLE
Get-CybereasonThreatIntel -Domain www.cybereason.com
# This example returns details on domain reputations for www.cybereason.com based on the Cybereason threat intelligence service.
 
.EXAMPLE
Get-CybereasonThreatIntel -Domain 'www.cybereason.com',cybereason.net'
# This example returns details on domain reputations for www.cybereason.com and cybereason.net based on the Cybereason threat intelligence service.
 
.EXAMPLE
Get-CybereasonThreatIntel -IPAddress 1.1.1.1
# This example returns details on IP address reputations for 1.1.1.1 based on the Cybereason threat intelligence service.
 
.EXAMPLE
Get-CybereasonThreatIntel -IPAddress '1.1.1.1','208.67.222.222'
# This example returns details on IP address reputations for 1.1.1.1 and 208.67.222.222 based on the Cybereason threat intelligence service.
 
.EXAMPLE
Get-CybereasonThreatIntel -ProductClassification
# This example retrieves product classification information
 
.EXAMPLE
Get-CybereasonThreatIntel -ProcessClassification
# This example retrieves process classification information
 
.EXAMPLE
Get-CybereasonThreatIntel -ProcessHierarchy
# This example retrieves process hierarchy information
 
.EXAMPLE
Get-CybereasonThreatIntel -FileExtension
# This example retrieves file extension information
 
.EXAMPLE
Get-CybereasonThreatIntel -PortInfo
# This example returns information on all ports
 
.EXAMPLE
Get-CybereasonThreatIntel -CollectionInfo
# This example returns information on collection information used by the Cybereason platform
 
.EXAMPLE
Get-CybereasonThreatIntel -IPReputation
# This example returns a list of IP Address reputations
 
.EXAMPLE
Get-CybereasonThreatIntel -DomainReputation
# This example returns a list of Domain reputations
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI const
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for collection information
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI domain_reputation
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for domain reputations
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI file_extension
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for file extensions
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI ip_reputation
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for IP Address reputations
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI process_classification
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for process classifications
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI process_hierarchy
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for process hierarchy information
 
.EXAMPLE
Get-CybereasonThreatIntel -DbUpdateCheck -ReputationAPI product_classification
# The -DbUpdateCheck switch parameter checks fro Cybereason sensor updates that are available for product classification information
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonThreatIntel {
    [CmdletBinding()]
        param(
            [Parameter(
                ParameterSetName='Md5Hash',
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [Alias('Hash','MD5')]
            [ValidateScript({$_.Length -eq 32})]
            [String[]]$Md5Hash,

            [Parameter(
                ParameterSetName='FileToHash',
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [Alias('Path','FilePath','f')]
            [ValidateScript({Test-Path -Path $_})]
            [String[]]$FileToHash,

            [Parameter(
                ParameterSetName='Domain',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define a domain to look up threat information on`n[E] EXAMPLE: www.cybereason.com")]  # End Parameter
            [Alias('d')]
            [ValidateScript({$_ -Like "*.*"})]
            [String[]]$Domain,

            [Parameter(
                ParameterSetName='IPAddress',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define an IP Address to look up threat information on`n[E] EXAMPLE: 1.1.1.1")]  # End Parameter
            [Alias('ip')]
            [String[]]$IPAddress,

            [Parameter(
                ParameterSetName='ProductClassification')]  # End Parameter
            [Switch][Bool]$ProductClassification,

            [Parameter(
                ParameterSetName='ProcessClassification')]  # End Parameter
            [Switch][Bool]$ProcessClassification,

            [Parameter(
                ParameterSetName='ProcessHierarchy')]  # End Parameter
            [Switch][Bool]$ProcessHierarchy,

            [Parameter(
                ParameterSetName='FileExtension')]  # End Parameter
            [Switch][Bool]$FileExtension,

            [Parameter(
                ParameterSetName='PortInfo')]  # End Parameter
            [Switch][Bool]$PortInfo,

            [Parameter(
                ParameterSetName='CollectionInfo')]  # End Parameter
            [Switch][Bool]$CollectionInfo,

            [Parameter(
                ParameterSetName='IPReputation')]  # End Parameter
            [Switch][Bool]$IPReputation,

            [Parameter(
                ParameterSetName='DomainReputation')]  # End Parameter
            [Switch][Bool]$DomainReputation,

            [Parameter(
                ParameterSetName='DbUpdateCheck')]  # End Parameter
            [Switch][Bool]$DbUpdateCheck,

            [Parameter(
                ParameterSetName='DbUpdateCheck',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the reputaion API value to be added to the query of the API's URI. This goes here in the URI, /download_v1/<HERE>/service `n[E] EXMAPLE: process_classification")]  # End Parameter
            [ValidateSet("ip_reputation","domain_reputation","process_classification","file_extension","process_hierarchy","process_hierarchy","product_classification","const")]
            [String]$ReputationAPI

        )  # End param

    $Obj = @()
    $Site = 'https://sage.cybereason.com/rest/'

    Switch ($PSBoundParameters.Keys)
    {

        'Md5Hash' {

            $Uri = $Site + 'classification_v1/file_batch'

            ForEach ($MD in $Md5Hash)
            {

                $JsonData = '{"requestData": [{"requestKey": {"md5": "' + $MD + '"} }] }'

                Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

                $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "classificationResponses"
                $MD5 = ($Results.requestKey.md5 | Out-String).Trim()
                $SHA1 = ($Results.requestKey.sha1 | Out-String).Trim()
                $MaliciousScore = $Results.aggregatedResult.maliciousClassification
                $ProductType = ($Results.aggregatedResult.productClassification.productType | Out-String).Trim()
                $Type = ($Results.aggregatedResult.productClassification.Type | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{md5="$MD5"; sha1="$SHA1"; MaliciousScore="$MaliciousScore"; ProductType="$ProductType"; Type="$Type"}

            }  # End ForEach

            $Obj

        }  # End Switch FileRep

        'FileToHash' {

            $Uri = $Site + 'classification_v1/file_batch'

            ForEach ($FilesMD5 in $FileToHash)
            {

                $FileHash = (Get-FileHash -Algorithm MD5 -Path $FilesMD5).Hash
                $JsonData = '{"requestData": [{"requestKey": {"md5": "' + $FileHash + '"} }] }'

                Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

                $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "classificationResponses"
                $MD5 = ($Results.requestKey.md5 | Out-String).Trim()
                $SHA1 = ($Results.requestKey.sha1 | Out-String).Trim()
                If ($SHA1.Length -ne 40) { $SHA1 = (Get-FileHash -Algorithm SHA1 -Path $FilesMD5).Hash}
                $MaliciousScore = $Results.aggregatedResult.maliciousClassification
                $ProductType = ($Results.aggregatedResult.productClassification.productType | Out-String).Trim()
                $Type = ($Results.aggregatedResult.productClassification.Type | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{md5="$MD5"; sha1="$SHA1"; MaliciousScore="$MaliciousScore"; ProductType="$ProductType"; Type="$Type"}

                Clear-Variable -Name FileHash,JsonData,Results,MD5,SHA1,MaliciousScore,ProductType,Type

            }  # End ForEach

            $Obj

        }  # End Switch FileRep

        'IPAddress' {

            $Uri = $Site + 'classification_v1/ip_batch'
            $IPv4Regex = '(((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))'

            ForEach ($IPAddr in $IPAddress)
            {

                Write-Verbose "Chekcing $IPAddr"
                If ($IPAddr -Match $IPv4Regex)
                {

                    $IPType = 'Ipv4'

                }  # End If
                Else
                {

                    $IPType = 'Ipv6'

                }  # End Else

                $JsonData = '{"requestData": [{"requestKey": {"ipAddress": "' + $IPAddr + '","addressType": "' + $IPType + '"} }] }'

                Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

                $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "classificationResponses"
                $IPA = ($Results.requestKey.ipAddress | Out-String).Trim()
                $AddressType = ($Results.requestKey.addressType | Out-String).Trim()
                $MaliciousScore = $Results.aggregatedResult.maliciousClassification
                $FirstSeen = Get-Date ($Results.aggregatedResult.firstSeen)
                $AllowFurther = ($Results.allowFurtherClassification | Out-String).Trim()
                $CPID = ($Results.cpId | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{IP=$IPA; Type=$AddressType; MaliciousScore=$MaliciousScore; FirstSeen=$FirstSeen; AllowFurtherClassification=$AllowFurther; CPID=$CPID}

            }  # End ForEach

            $Obj

        }  # End Switch IPBat

        'Domain' {

            $Uri = $Site + 'classification_v1/domain_batch'

            ForEach ($Dom in $Domain)
            {

                Write-Verbose "Testing $Dom"

                $JsonData = '{"requestData": [{"requestKey": {"domain": "' + $Dom + '"} }] }'

                Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

                $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "classificationResponses"

                $Doma = ($Results.requestKey.domain | Out-String).Trim()
                $Source = ($Results.aggregatedResult.maliciousClassification.source | Out-String).Trim()
                $MaliciousScore = $Results.aggregatedResult.maliciousClassification
                $FirstSeen = Get-Date -Date ($Results.aggregatedResult.firstSeen)
                $AllowFurther = ($Results.allowFurtherClassification | Out-String).Trim()
                $CPID = ($Results.cpId | Out-String).Trim()
                $CPType = ($Results.cpType | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Domain=$Doma; Source=$Source; MaliciousScore=$MaliciousScore; FirstSeen=$FirstSeen; AllowFurtherClassification=$AllowFurther; CPID=$CPID; CPType=$CPType}

            }  # End ForEach

            $Obj

        }  # End Switch DomainBatch

        'ProductClassification' {

            $Uri = $Site + 'download_v1/productClassifications'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | `
            ForEach-Object {
                $Name = ($_.Key.name | Out-String).Trim()
                $Signer = ($_.Value.signer | Out-String).Trim()
                $Type = ($_.Value.type | Out-String).Trim()
                $Title = ($_.Value.title | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Name="$Name"; Signer=$Signer; Type=$Type; Title="$Title"}

            }  # End For

            $Obj

        }  # End Switch ProductClassification

        'ProcessClassification' {

            $Uri = $Site + 'download_v1/process_classification'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | `
            ForEach-Object {
                $ProcessName = ($_.Key.name | Out-String).Trim()
                $Title = ($_.Value.title | Out-String).Trim()
                $ProductName = ($_.Value.productName | Out-String).Trim()
                $CompanyName = ($_.Value.companyName | Out-String).Trim()
                $fileDescription = ($_.Value.fileDescription | Out-String).Trim()
                $filePath = ($_.Value.path | Out-String).Trim()


                $Obj += New-Object -TypeName PSObject -Property @{ProcessName="$ProcessName"; Title="$Title"; ProductName=$ProductName; CompanyName=$CompanyName; FileDescription=$fileDescription; FilePath=$FilePath}

            }  # End For

            $Obj

        }  # End Switch ProcessClassification

        'ProcessHierarchy' {

            $Uri = $Site + 'download_v1/process_hierarchy'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | `
            ForEach-Object {

                $Parent = ($_.Value.parent | Out-String).Trim()
                $ProcessName = ($_.Key.name | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Parent="$Parent"; ProcessName="$ProcessName"}

            }  # End For

            $Obj

        }  # End Switch ProcessHierarchy

        'FileExtension' {

            $Uri = $Site + 'download_v1/file_extension'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Obj = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | Select-Object -ExpandProperty "Value" | Select-Object -Property Description,Type

            $Obj

        }  # End Switch FileExtension

        'PortInfo' {

            $Uri = $Site + 'download_v1/port'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | `
            ForEach-Object {

                $Port = ($_.Key.port | Out-String).Trim()
                $Protocol = ($_.Key.protocol | Out-String).Trim()
                $Type = ($_.Value.type | Out-String).Trim()
                $ShortDescription = ($_.Value.shortDescription | Out-String).Trim()
                $Source = ($_.Value.sources | Out-String).Trim()
                $LongDescr = ($_.Value.longDescription | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Port="$Port"; Protocol="$Protocol"; Type=$Type; ShortDescription=$ShortDescription; Source=$Source; LongDescription=$LongDescr}

            }  # End ForEach-Object

            $Obj

        }  # End Switch PortInfo

        'CollectionInfo' {

            $Uri = $Site + 'download_v1/const'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty "recordList" | `
            ForEach-Object {
                $Name = ($_.Key.name | Out-String).Trim()
                $Data = ($_.Value.data | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Name="$Name"; Data="$Data"}

            }  # End For

            $Obj

        }  # End Switch CollectionInfo

        'IPReputation' {

            $Uri = $Site + 'download_v1/ip_reputation'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json
            For ($i = 0; $i -le $Results.ipReputationResponseList.Count; $i++)
            {

                $IPAddress = ($Results.ipReputationResponseList.requestkey.ipaddress[$i] | Out-String).Trim()
                $AddressType = ($Results.ipReputationResponseList.requestkey.addressType[$i] | Out-String).Trim()
                $ReputationSource = ($Results.ipReputationResponseList.aggregatedResult.reputationSource[$i] | Out-String).Trim()
                $ReputationScore = ($Results.ipReputationResponseList.aggregatedResult.reputationScore[$i] | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{IPAddress="$IPAddress"; AddressType="$AddressType"; ReputationSource="$ReputationSource"; ReputationScore="$ReputationScore"}

            }  # End For

            $Obj

        }  # End IPReputation Switch

        'DomainReputation' {

            $Uri = $Site + 'download_v1/domain_reputation'
            $JsonData = "{}"

            Write-Verbose "Sending Threat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Results = $Response.Content | ConvertFrom-Json
            For ($i = 0; $i -le ($Results.domainReputationResponseList).Count; $i++)
            {

                $Domain = ($Results.domainReputationResponseList.requestkey[$i] | Out-String).Trim()
                $ReputationSource = ($Results.domainReputationResponseList.aggregatedResult.reputationSource[$i] | Out-String).Trim()
                $ReputationScore = ($Results.domainReputationResponseList.aggregatedResult.reputationScore[$i] | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Domain="$Domain"; ReputationSource="$ReputationSource"; ReputationScore="$ReputationScore"}

            }  # End For

            $Obj

        }  #End Switch DomainReputation

        'DbUpdateCheck' {

            $Uri = $Site + 'download_v1/' + $ReputationAPI + '/service'
            $JsonData = "{}"

            Write-Verbose "Sending THreat Intel JSON data to Cybereason's API"
            $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData

            $Obj = $Response.Content | ConvertFrom-Json

            $Obj

        }  # End Switch DbUpdateCheck

    }  # End Switch

}  # End Function Get-CybereasonThreatIntel


<#
.SYNOPSIS
Returns a CSV list of custom reputations for files, IP addresses, and domain names. These reputations are specific to your organization.
 
 
.DESCRIPTION
This cmdlet is used to download a CSV list of custom reputations for files, IP addresses, and domains that were manually set up in your environment.
 
 
.PARAMETER Path
This parameter defines the path and filename to save the CSV results.
 
 
.EXAMPLE
Get-CybereasonReputation -Path C:\Windows\Temp\CybereasonRepuations.csv
# This example gets the current repuations of files, IP addresses, and domains configured in your environment and returns CSV related results.
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
System.String
The CSV list is sent to the file designated in the Path parameter.
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/get-reputation#getreputations
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonReputation {
    [CmdletBinding()]
        param(
            [Parameter(
                Position=1,
                Mandatory=$False)]  # End Parameter
            [String]$Path
        )  # End param

    $Uri = 'https://' + $Server + ":$Port" + '/rest/classification/download'

    Write-Verbose "Sending request to $Uri"
    If ($Path.Length -gt 0)
    {

        Write-Verbose "Downloading file to $Path"
        Invoke-RestMethod -URI $Uri -WebSession $CybereasonSession -Headers @{charset='utf-8'} -ContentType "application/json" -Method GET -OutFile "$Path"

    }  # End If
    Else
    {

        Write-Verbose "Returning CSV formatted results to window"
        Invoke-RestMethod -URI $Uri -WebSession $CybereasonSession -ContentType "application/json" -Method GET

    }  # End Else

}  # End Function Get-CybereasonReputation


<#
.SYNOPSIS
This cmdlet is used to update the custom set reputations of files, IP addresses, or domain names in an environment with Cybereason.
 
 
.DESCRIPTION
This cmdlet can add or remove IP addresses, domains, and file hashes to a blacklisit or whitelist to change the reputation of that item in the eyes of Cybereason.
 
 
.PARAMETER Keys
The file hash value (either MD5 or SHA1), IP address, or domain name for which to set a custom reputation.
 
.PARAMETER File
If you do not know the hash of a file or files you wish to modify the reputations of, you can simply enter the path to the file here and this will obtain the hash automatically for you. This can be used to replace the -Keys parameter.
 
.PARAMETER Modify
Modify the reputation of an item by adding a rule to the blacklist or whitelist
 
.PARAMETER Action
Instructs Cybereason to add or remove a reputation. Set the value to Add or Remove to modify the defined reputations.
 
.PARAMETER PreventExecution
This parameter indicates whether to prevent the file’s execution with Application Control. Note this option is applicable for the File type. If your request includes IP addresses or domain names to update, you must set this parameter to false.
 
 
.EXAMPLE
Set-CybereasonReputation -Keys '1.1.1.1' -Modify Whitelist -Action Add -PreventExecution False
# This example sets the Cybereason repuations of IP address 1.1.1.1 by adding it to the whitelist. Because this is an IP address the -PreventExecution parameter needs to be false. This will be modified automatically in the script if set incorrectly.
 
.EXAMPLE
Set-CybereasonReputation -Keys 'maliciousdomain.com' -Modify Blacklist -Action Add -PreventExecution False
# This example sets the Cybereason repuations of domain maliciousdomain.com by adding it to the blacklist. Because this is not a file hash the -PreventExecution parameter needs to be false. This will be modified automatically in the script if set incorrectly.
 
.EXAMPLE
Set-CybereasonReputation -Keys 'badguy.com','badperson.com' -Modify Blacklist -Action Add -PreventExecution False
# This example sets the Cybereason repuations of domain badguy.com and badperson.com by adding them to the blacklist. Because this is not a file hash the -PreventExecution parameter needs to be false. This will be modified automatically in the script if set incorrectly.
 
.EXAMPLE
Set-CybereasonReputation -Keys 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' -Modify 'Blacklist' -Action 'Add' -PreventExecution 'True'
# This example sets the Cybereason repuations of a file with the defined SHA1 hash value and adds it to the blacklist. Prevent Execution is set to true which will prevent all devices in an environment from executing this file when App Control is enabled in Cybereason.
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/get-reputation#getreputations
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Set-CybereasonReputation {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact='High')]
        param(
            [Parameter(
                ParameterSetName='Keys',
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [String[]]$Keys,

            [Parameter(
                ParameterSetName='File',
                Mandatory=$True,
                ValueFromPipeline=$False)]
            [Alias('f','Path','FilePath')]
            [ValidateScript({Test-Path -Path $_})]
            [String[]]$File,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateSet('blacklist','whitelist')]
            [String]$Modify,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False)]
            [ValidateSet('Add','Remove')]
            [String]$Action,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [Alias('Prevent')]
            [ValidateSet('true','false')]
            [String]$PreventExecution = 'false',

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch]$Force
        )  # End param

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    $Uri = "https://" + $Server + ":" + $Port + '/rest/classification/update '
    Switch ($Action)
    {

        'Add' { $Remove = 'false' }
        'Remove' { $Remove = 'true' }

    }  # End Switch

}  # End BEGIN

PROCESS {

    If ($PSBoundParameters.Keys -eq 'File')
    {

        ForEach ($F in $File)
        {

            $Hash = (Get-FileHash -Algorithm MD5 -Path $F).Hash
            If ($PreventExecution -like 'true')
            {

                Write-Warning "You are about to prevent the execution of this file on all devices in your environment"
                $Answer = Read-Host -Prompt "Are you sure you wish to perform this action? [Y/n]"

                If ($Answer -like 'n')
                {

                    $PreventExecution = 'false'

                }  # End If
                Else
                {

                    Write-Output "[*] Preventing the execution of the file with hash : $F"

                }  # End Else

            }  # End If

            $JsonData = '[{"keys": ["' + $Hash + '"],"maliciousType": "' + $Modify + '", "prevent": "' + $PreventExecution + '", "remove": "' + $Remove + '"}]'

            If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
            {

                Write-Verbose "Sending request to $Uri"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData -WebSession $CybereasonSession
                $Response.Content | ConvertFrom-Json

            }  # End If

        }  # End ForEach

    }  # End Switch File
    Else
    {

        $IPv4Regex = '(((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))'
        ForEach ($Key in $Keys)
        {

            Write-Verbose "Ensuring the Prevent Execution value is set to false when the Key value defined is an IP address or domain name"
            If ((!($Key.Length -eq 32)) -or (!($Key.Length -eq 40)) -or ($Key -Match $IPv4Regex) -or ($Key -like "*.*"))
            {

                $PreventExecution = 'false'

            }  # End If

            $JsonData = '[{"keys": ["' + $Key + '"],"maliciousType": "' + $Modify + '", "prevent": "' + $PreventExecution + '", "remove": "' + $Remove + '"}]'

            If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
            {

                Write-Verbose "Sending request to $Uri"
                $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData -WebSession $CybereasonSession
                $Response.Content | ConvertFrom-Json

            }  # End If

        }  # End ForEach

    }  # End Else

}  # End PROCESS

END {

    Write-Verbose ('[{0}] Confirm={1} ConfirmPreference={2} WhatIf={3} WhatIfPreference={4}' -f $MyInvocation.MyCommand, $Confirm, $ConfirmPreference, $WhatIf, $WhatIfPreference)

}  # End END

}  # End Function Set-CybereasonReputation


<#
.SYNOPSIS
This cmdlet is used to perform remediation actions on a specific process, file, or registry key
 
 
.DESCRIPTION
This uses the Cybereason API to perform a remediation action on a specific file, process, or registry key.
 
 
.PARAMETER MalopID
The unique ID assigned by the Cybereason platform for the Malop. This ID is found when you retrieve the list of Malops. For details on getting this ID, see, Get Malops. You can perform remediation without this malop ID.
 
.PARAMETER InitiatorUserName
The Cybereason user name for the user performing the remediation.
 
.PARAMETER MachineId
The unique GUID for the machine. Note this is different from the sensor ID (pylumID) value.
 
.PARAMETER TargetID
The unique GUID for the process or file to remediate. You can find this GUID in the response when you perform an investigation query for a process. If you provide a Malop ID in the request, do not add this field in the request. Note that using the targetId parameter is supported only for processes (the KILL_PROCESS action) and files (the QUARANTINE_FILE or UNQUARANTINE_FILE action). If you use the UNQUARANTINE_FILE action, the targetId (GUID) value is different than the GUID of the original file for the QUARANTINE_FILE action. You can find this GUID for the quarantined file by running a query with the Quarantine File Element.
 
.PARAMETER ActionType
The remediation action to perform. Possible values include:
KILL_PROCESS. Use this option to immediately stop the process associated with the root cause of the Malop.
DELETE_REGISTRY_KEY. Use this option to remove any registry keys detected as malicious as part of the Malop.
QUARANTINE_FILE. Use this option to quarantine the detected malicious file in a secure location.
UNQUARANTINE_FILE. Use this option to enable the Cybereason platform to remove a file from quarantine. This option is available in version 20.1.120 and later.
BLOCK_FILE. Use this to enable Application Control to block the file(s) associated with the Malop when it they are detected in the future.
KILL_PREVENT_UNSUSPEND. Use this option to prevent detected ransomware from running on the machine.
UNSUSPEND_PROCESS. Use this option to prevent a file associated with ransomware.
ISOLATE_MACHINE: Use this option to isolate a specific machine.
 
 
.EXAMPLE
Invoke-RemediateItem -MalopID "11.2718161727221199870" -InitiatorUserName "admin@yourserver.com" -MachineID "-1632138521.1198775089551518743" -ActionType KILL_PROCESS
# This example remediates a process by killing it after it was discovered by a Malop
 
.EXAMPLE
Invoke-RemediateItem -InitiatorUserName "admin@yourserver.com" -MachineID "-1632138521.1198775089551518743" -TargetID "-2095200899.6557717220054083334" -ActionType KILL_PROCESS
# This example remediates a process that was not involved in a Malop
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
System.Object[]
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/remediate-items#remediatemalops
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Invoke-RemediateItem {
    [CmdletBinding()]
    [OutputType([System.Object[]])]
        param(
            [Parameter(
                ParameterSetName='MalopID',
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [Alias('Malop','Id')]
            [String]$MalopID,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the Cybereason user name for the user performing the remediation`n[E] EXAMPLE: admin@cyberason.com")]  # End Parameter
            [Alias('User','Username','Initiator')]
            [String]$InitiatorUserName,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the unique GUID number of the machine. NOTE: This is different from the sensor ID (pylumID) value.`n[E] EXAMPLE: -1632138521.1198775089551518743")]  # End Parameter
            [Int64]$MachineId,

            [Parameter(
                ParameterSetName='TargetID',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The unique GUID for the process or file to remediate. You can find this GUID in the response when you perform an investigation query for a process. Note that using the targetId parameter is supported only for processes (the KILL_PROCESS action) and files (the QUARANTINE_FILE or UNQUARANTINE_FILE action). If you use the UNQUARANTINE_FILE action, the targetId (GUID) value is different than the GUID of the original file for the QUARANTINE_FILE action. You can find this GUID for the quarantined file by running a query with the Quarantine File Element.`n[E] EXAMPLE: null")]
            [String]$TargetID,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateSet('KILL_PROCESS','DELETE_REGISTRY_KEY','QUARANTINE_FILE','UNQUARANTINE_FILE','BLOCK_FILE','KILL_PREVENT_UNSUSPEND','UNSUSPEND_PROCESS','ISOLATE_MACHINE')]
            [String]$ActionType
        )  # End param


    $Obj = @()
    Write-Verbose "Validating -InitiatorUserName parameter is in email address format"
    Try
    {

        $Null = [MailAddress]$InitiatorUserName

    }  # End Try
    Catch
    {

        Throw "[x] The username you defined, $InitiatorUserName, is not a valid email address."

    }  # End Catch

    $Uri = "https://" + $Server + ":" + $Port + "/rest/remediate"

    Switch ($PSBoundParameters.Keys)
    {

        'MalopID' {

            $JsonData = '{"malopId":' + $MalopID + ',"initiatorUserName":' + $InitiatorUserName + ',"actionsByMachine":{' + $MachineId + ':[{"actionType":' + $ActionType + '}]}}'

        }  # End Switch MalopID

        'TargetID' {

            $JsonData = '{"initiatorUserName":' + $InitiatorUserName + ',"actionsByMachine":{' + $MachineId + ':[{"targetId":' + $TargetID + ',"actionType":' + $ActionType + '}]}}'

        }  # End Switch TargetID

    }  # End Switch

    Write-Verbose "Sending request to $Uri"
    $Response = Invoke-WebRequest -Uri $Uri -Method POST -ContentType "application/json" -Body $JsonData -WebSession $CybereasonSession
    $Response.Content | ConvertFrom-Json | `
        ForEach-Object {
                $MalopId = ($_.malopId | Out-String).Trim()
                $RemediationId = ($_.remediationId | Out-String).Trim()
                $Start = Get-Date -Date ($_.start)
                $End = Get-Date ($_.end)
                $InitiatingUser = ($_.initiatingUser | Out-String).Trim()
                $MachineId = ($_.statusLog.machineID | Out-String).Trim()
                $TargetId = ($_.statusLog.targetId | Out-String).Trim()
                $Status = ($_.statusLog.status | Out-String).Trim()
                $ActionType = ($_.statusLog.actionType | Out-String).Trim()
                $ErrorMessage = $_.statusLog.error
                $TimeStamp = Get-Date -Date ($_.statusLog.timestamp)

                $Obj += New-Object -TypeName PSObject -Property @{malopId=$MalopId; remediationId=$RemediationId; Start=$Start; End=$End; initiatingUser=$InitiatingUser; MachineId=$MachineId; TargetId=$TargetId; Status=$Status; ActionType=$ActionType; TimeStamp=$TimeStamp; Error=$ErrorMessage}

        }  # End ForEach-Object

    $Obj

}  # End Function Invoke-CybereasonRemediateItem


<#
.SYNOPSIS
This cmdlet is used too return details on the progress of a specific remediation operation.
 
 
.DESCRIPTION
Returns details on the progress of a specific remediation operation.
 
 
.PARAMETER Username
The Cybereason user name of the user performing the remediation operation.
 
.PARAMETER MalopID
The unique Malop ID for the Malop for which you are performing remediation.
 
.PARAMETER RemediationID
This parameter defines the Cybereason remediation Id to check the progress of. The remediation ID returned in a previous remediation request. For details on finding this remediation ID, see https://nest.cybereason.com/api-documentation/all-versions/APIReference/RemediationAPI/remediateMalop.html#remediate-items.
 
 
.EXAMPLE
Get-CybereasonRemediationProgress -Username 'admin@cyberason.com' -MalopID '11.2718161727221199870' -RemediationID '86f3faa1-bac0-4a17-9192-9d106b734664'
# This example gets the current status on a Malop that was remediated by the user admin@cyberason.com
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/check-remediation-progress
https://nest.cybereason.com/api-documentation/all-versions/APIReference/RemediationAPI/remediateMalop.html#remediate-items
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonRemediationProgress {
    [CmdletBinding()]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the username you are querying to view the status of their Malops request `n[E] EXAMPLE: admin@cybereason.com")]  # End Parameter
            [String]$Username,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the Malops ID you are querying to view the progress of in this query `n[E] EXAMPLE: 11.2718161727221199870")]  # End Parameter
            [String]$MalopID,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the Remediation ID you are querying to view the progress of the request `n[E] EXAMPLE: 86f3faa1-bac0-4a17-9192-9d106b734664")]  # End Parameter
            [String]$RemediationID
        )  # End param


    $Obj = @()
    Write-Verbose "Validating -InitiatorUserName parameter is in email address format"
    Try
    {

        $Null = [MailAddress]$InitiatorUserName

    }  # End Try
    Catch
    {

        Throw "[x] The username you defined, $InitiatorUserName, is not a valid email address."

    }  # End Catch

    $Uri = "https://" + $Server + ":" + $Port + "/rest/remediate/progress/" + $Username + "/" + $MalopID + "/" + $RemediationID

    $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

    $Response.Content | ConvertFrom-Json | `
    ForEach-Object {
        $MalopId = ($_.malopId | Out-String).Trim()
        $RemediationId = ($_.remediationId | Out-String).Trim()
        $Start = Get-Date -Date ($_.start)
        $End = Get-Date ($_.end)
        $InitiatingUser = ($_.initiatingUser | Out-String).Trim()
        $MachineId = ($_.statusLog.machineID | Out-String).Trim()
        $TargetId = ($_.statusLog.targetId | Out-String).Trim()
        $Status = ($_.statusLog.status | Out-String).Trim()
        $ActionType = ($_.statusLog.actionType | Out-String).Trim()
        $ErrorMessage = $_.statusLog.error
        $TimeStamp = Get-Date -Date ($_.statusLog.timestamp)

        $Obj += New-Object -TypeName PSObject -Property @{malopId=$MalopId; remediationId=$RemediationId; Start=$Start; End=$End; initiatingUser=$InitiatingUser; MachineId=$MachineId; TargetId=$TargetId; Status=$Status; ActionType=$ActionType; TimeStamp=$TimeStamp; Error=$ErrorMessage}

    }  # End ForEach-Object

    $Obj

}  # End Function Get-CybereasonRemediationProgress

<#
.SYNOPSIS
This cmdlet aborts a remediation operation on a specific Malop.
 
 
.DESCRIPTION
This aborts a remediation operation for the Malop and Remediation ID you define
 
 
.PARAMETER MalopID
The unique Malop ID for the Malop for which you are performing remediation.
 
.PARAMETER RemediationID
This parameter defines the Cybereason remediation Id to check the progress of. The remediation ID returned in a previous remediation request. For details on finding this remediation ID, see https://nest.cybereason.com/api-documentation/all-versions/APIReference/RemediationAPI/remediateMalop.html#remediate-items.
 
 
.EXAMPLE
Stop-CybereasonMalopRemediation -MalopID '11.2718161727221199870' -RemediationID '86f3faa1-bac0-4a17-9192-9d106b734664'
# This example aborts the remediation action take on the defined Malop
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/abort-malop-remediation
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Stop-CybereasonMalopRemediation {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the Malops ID you are querying to view the progress of in this query `n[E] EXAMPLE: 11.2718161727221199870")]  # End Parameter
            [String]$MalopID,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the Remediation ID you are querying to view the progress of the request `n[E] EXAMPLE: 86f3faa1-bac0-4a17-9192-9d106b734664")]  # End Parameter
            [String]$RemediationID,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch]$Force
        )  # End parm

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    $Uri = "https://" + $Server + ":" + $Port + "/rest/remediate/abort/" + $MalopID + "/" + $RemediationID

}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {
        $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

        $Response.Content | ConvertFrom-Json | `
        ForEach-Object {
            $MalopId = ($_.malopId | Out-String).Trim()
            $RemediationId = ($_.remediationId | Out-String).Trim()
            $Start = Get-Date -Date ($_.start)
            $End = Get-Date ($_.end)
            $InitiatingUser = ($_.initiatingUser | Out-String).Trim()
            $MachineId = ($_.statusLog.machineID | Out-String).Trim()
            $TargetId = ($_.statusLog.targetId | Out-String).Trim()
            $Status = ($_.statusLog.status | Out-String).Trim()
            $ActionType = ($_.statusLog.actionType | Out-String).Trim()
            $ErrorMessage = $_.statusLog.error
            $TimeStamp = Get-Date -Date ($_.statusLog.timestamp)

            $Obj += New-Object -TypeName PSObject -Property @{malopId=$MalopId; remediationId=$RemediationId; Start=$Start; End=$End; initiatingUser=$InitiatingUser; MachineId=$MachineId; TargetId=$TargetId; Status=$Status; ActionType=$ActionType; TimeStamp=$TimeStamp; Error=$ErrorMessage}

        }  # End ForEach-Object

        $Obj

    }  # End If ShouldProcess

}  # End PROCESS

}  # End Function Stop-CybereasonMalopRemediation

<#
.SYNOPSIS
This cmdlet retrieves details about remediation actions performed on a particular Malop.
 
 
.DESCRIPTION
This retrieves details about remediation actions performed on a particular Malop you define
 
 
.PARAMETER MalopID
The unique Malop ID for the Malop for which you are performing remediation.
 
 
.EXAMPLE
Get-CybereasonRemediationStatus -MalopID '11.2718161727221199870'
# This example gets the current status for the defined Malop
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/get-remediation-statuses
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonRemediationStatus {
    [CmdletBinding()]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the Malops ID you are querying to view the progress of in this query `n[E] EXAMPLE: 11.2718161727221199870")]  # End Parameter
            [String]$MalopID
        )  # End param


    $Uri = "https://" + $Server + ":" + $Port + "/rest/remediate/status/" + $MalopID

    $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

    $Response.Content | ConvertFrom-Json | `
    ForEach-Object {
        $MalopId = ($_.malopId | Out-String).Trim()
        $RemediationId = ($_.remediationId | Out-String).Trim()
        $Start = Get-Date -Date ($_.start)
        $End = Get-Date ($_.end)
        $InitiatingUser = ($_.initiatingUser | Out-String).Trim()
        $MachineId = ($_.statusLog.machineID | Out-String).Trim()
        $TargetId = ($_.statusLog.targetId | Out-String).Trim()
        $Status = ($_.statusLog.status | Out-String).Trim()
        $ActionType = ($_.statusLog.actionType | Out-String).Trim()
        $ErrorMessage = $_.statusLog.error
        $TimeStamp = Get-Date -Date ($_.statusLog.timestamp)

        $Obj += New-Object -TypeName PSObject -Property @{malopId=$MalopId; remediationId=$RemediationId; Start=$Start; End=$End; initiatingUser=$InitiatingUser; MachineId=$MachineId; TargetId=$TargetId; Status=$Status; ActionType=$ActionType; TimeStamp=$TimeStamp; Error=$ErrorMessage}

    }  # End ForEach-Object

    $Obj

}  # End Function Get-CybereasonRemediationStatus


<#
.SYNOPSIS
This cmdlet retrieves a list of all rules for isolating specific machines.
 
 
.DESCRIPTION
Retrieves a list of all rules for isolating specific machines.
 
 
.EXAMPLE
Get-CybereasonIsolationRule
# This example retrieves a list of all rules for isolating specific machines
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/api-documentation/all-versions/APIReference/IsolationAPI/retrieveRules.html#getisolationrules
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonIsolationRule {
    [CmdletBinding()]
        param()

    $Obj = @()
    $Uri = "https://" + $Server + ":" + $Port + "/rest/settings/isolation-rule"
    $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

    If ($Response.StatusCode -eq 200)
    {

        $Response.Content | ConvertFrom-Json | `
        ForEach-Object {
            $RuleId = ($_.ruleId | Out-String).Trim()
            $IpAddress = ($_.ipAddress | Out-String).Trim()
            $IpAddressString = ($_.ipAddressString | Out-String).Trim()
            $Domain = ($_.domain | Out-String).Trim()
            $PortNumber = ($_.port | Out-String).Trim()
            $Direction = ($_.direction | Out-String).Trim()
            $LastUpdated = Get-Date -Date ($_.lastUpdated)
            $Blocking = ($_.blocking | Out-String).Trim()

            $Obj += New-Object -TypeName PSObject -Property @{RuleId=$RuleId; IPAddress=$IpAddress; IPAddressString=$ipAddressString; Domain=$Domain; Port=$PortNumber; Direction=$Direction; LastUpdated=$LastUpdated; Blocking=$Blocking}

        }  # End ForEach-Object

        $Obj

    }
    Else
    {

        Write-Output "[*] No isolation rules were found or access was denied. Try authenticating with a non-api user if you believe you should have this access."
        $Response

    }  # End Catch

}  # End Function Get-CybereasonIsolationRule


<#
.SYNOPSIS
This cmdlet is used to create an isolation exception rule.
 
 
.DESCRIPTION
Creates an isolation exception rule.
 
 
.PARAMETER IPAddressString
The IP address of the machine to which the rule applies.
 
.PARAMETER PortNumber
Optional if the ipAddressString parameter exists. The port by which Cybereason communicates with an isolated machine, according to the rule.
 
.PARAMETER Blocking
States whether communication with the given IP or port is allowed. Set to true if communication is blocked.
 
.PARAMETER Direction
The direction of the allowed communication. Values include ALL, INCOMING, or OUTGOING.
 
 
.EXAMPLE
New-CybereasonIsolationRule -IPAddressString '123.45.67.89' -PortNumber 8443 -Blocking -Direction ALL
# This example creates a new isolation rule that blocks All communication to 123.45.67.89
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/api-documentation/all-versions/APIReference/IsolationAPI/createRule.html#createisolationrule
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function New-CybereasonIsolationRule {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the IP Address of the machine for which the rule should apply.`n[E] EXAMPLE: 123.45.67.89")]  # End Parameter
            [String[]]$IpAddressString,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateRange(1,65535)]
            [Int16]$PortNumber,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]
             [Switch][Bool]$Blocking,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the direction the rule should be applied too.`n[E] EXAMPLE: INCOMING")]  # End Parameter
            [ValidateSet('ALL','INCOMING','OUTGOING')]
            [String]$Direction,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch]$Force
        )  # End param

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    $Obj = @()
    If ($Blocking.IsPresent)
    {

        $Block = 'true'

    }  # End If
    Else
    {

        $Block = 'false'

    }  # End If

    If ($IpAddressString.Length -gt 0)
    {

        $StringOne = '"ipAddressString":"' + $IpAddressString + '"'

    }  # End If

    If ($PortNumber.Length -gt 0)
    {

        $StringTwo = ',"port":' + $PortNumber

    }  # End If

    $Uri = "https://" + $Server + ":" + $Port + "/rest/settings/isolation-rule"

    $JsonData = '{' + $StringOne + $StringTwo + ',"blocking":"' + $Block + '","direction":"' + $Direction + '"}'
}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {

        $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

        $Response.Content | ConvertFrom-Json | `
        ForEach-Object {
            $RuleId = ($_.ruleId | Out-String).Trim()
            $IpAddress = ($_.ipAddress | Out-String).Trim()
            $IpAddressString = ($_.ipAddressString | Out-String).Trim()
            $Domain = ($_.domain | Out-String).Trim()
            $PortNumber = ($_.port | Out-String).Trim()
            $Direction = ($_.direction | Out-String).Trim()
            $LastUpdated = Get-Date -Date ($_.lastUpdated)
            $Blocking = ($_.blocking | Out-String).Trim()

            $Obj += New-Object -TypeName PSObject -Property @{RuleId=$RuleId; IPAddress=$IpAddress; IPAddressString=$ipAddressString; Domain=$Domain; Port=$PortNumber; Direction=$Direction; LastUpdated=$LastUpdated; Blocking=$Blocking}

        }  # End ForEach-Object

        $Obj

    }  # End If

} # End PROCESS

}  # End Function New-CybereasonIsolationRule


<#
.SYNOPSIS
This cmdlet is used to updates an isolation exception rule.
 
 
.DESCRIPTION
Updates an isolation exception rule.
 
 
.PARAMETER RuleID
A unique identifier for the rule
 
.PARAMETER IPAddressString
The IP address of the machine to which the rule applies.
 
.PARAMETER PortNumber
Optional if the ipAddressString parameter exists. The port by which Cybereason communicates with an isolated machine, according to the rule.
 
.PARAMETER Blocking
States whether communication with the given IP or port is allowed. Set to true if communication is blocked.
 
.PARAMETER Direction
The direction of the allowed communication. Values include ALL, INCOMING, or OUTGOING.
 
 
.EXAMPLE
Set-CybereasonIsolationRule -RuleID "5a7b2e95e4b082f2e909a4f3" -IPAddressString '123.45.67.89' -PortNumber 8443 -Blocking -Direction ALL
# This example creates a new isolation rule that blocks All communication to 123.45.67.89
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/api-documentation/all-versions/APIReference/IsolationAPI/updateRule.html#updateisolationrule
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Set-CybereasonIsolationRule {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False)]  # End Parameter
            [String]$RuleID,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Enter the IP Address of the machine for which the rule should apply.`n[E] EXAMPLE: 123.45.67.89")]  # End Parameter
            [String]$IpAddressString,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateRange(1,65535)]
            [Int16]$PortNumber,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]
             [Switch][Bool]$Blocking,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the direction the rule should be applied too.`n[E] EXAMPLE: INCOMING")]  # End Parameter
            [ValidateSet('ALL','INCOMING','OUTGOING')]
            [String]$Direction,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Using the Tick format, define the last update value to specifiy the rule you wish to modify the info on `n[E] EXAMPLE: 1525594605852")]  # End Parameter
            [String]$LastUpdated,

            [Parameter(
                Mandatory=$True)]  # End Parameter
            [Switch]$Force
        )  # End param

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    $Obj = @()
    If ($Blocking.IsPresent)
    {

        $Block = 'true'
        $StringThree = ',"blocking":"' + $Block + '"'

    }  # End If
    Else
    {

        $Block = 'false'
        $StringThree = ',"blocking":"' + $Block + '"'

    }  # End If

    $Uri = "https://" + $Server + ":" + $Port + "/rest/settings/isolation-rule"

    If ($IpAddressString.Length -gt 0)
    {

        $StringOne = ',"ipAddressString":"' + $IpAddressString + '"'

    }  # End If

    If ($PortNumber.Length -gt 0)
    {

        $StringTwo = ',"port":' + $PortNumber

    }  # End If

    If ($Direction.Length -gt 0)
    {

        $StringFour = ',"direction":"' + $Direction + '"'

    }  # End If

    If ($LastUpdated.Length -gt 0)
    {

        $StringFive = ',"lastUpdated":' + $LasUpdated

    }  # End If

    $JsonData = '{"ruleId":"' + $RuleID + '"' + $StringOne + $StringTwo + $StringThree + $StringFour + $StringFive + '}'

}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {

        $Response = Invoke-WebRequest -Method PUT -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

        $Response.Content | ConvertFrom-Json | `
        ForEach-Object {
            $RuleId = ($_.ruleId | Out-String).Trim()
            $IpAddress = ($_.ipAddress | Out-String).Trim()
            $IpAddressString = ($_.ipAddressString | Out-String).Trim()
            $Domain = ($_.domain | Out-String).Trim()
            $PortNumber = ($_.port | Out-String).Trim()
            $Direction = ($_.direction | Out-String).Trim()
            $LastUpdated = Get-Date -Date ($_.lastUpdated)
            $Blocking = ($_.blocking | Out-String).Trim()

            $Obj += New-Object -TypeName PSObject -Property @{RuleId=$RuleId; IPAddress=$IpAddress; IPAddressString=$ipAddressString; Domain=$Domain; Port=$PortNumber; Direction=$Direction; LastUpdated=$LastUpdated; Blocking=$Blocking}

        }  # End ForEach-Object

        $Obj

    }  # End If ShouldProcess

} # End PROCESS

}  # End Function Set-CybereasonIsolationRule


<#
.SYNOPSIS
This cmdlet is used too delete an isolation exception rule.
 
 
.DESCRIPTION
Deletes an isolation exception rule.
 
 
.PARAMETER RuleID
A unique identifier for the rule
 
.PARAMETER IPAddressString
The IP address of the machine to which the rule applies.
 
.PARAMETER PortNumber
Optional if the ipAddressString parameter exists. The port by which Cybereason communicates with an isolated machine, according to the rule.
 
.PARAMETER Blocking
States whether communication with the given IP or port is allowed. Set to true if communication is blocked.
 
.PARAMETER Direction
The direction of the allowed communication. Values include ALL, INCOMING, or OUTGOING.
 
.PARAMETER LastUpdate
The epoch timestamp for the last update time for the rule.
 
 
.EXAMPLE
Remove-CybereasonIsolationRule -RuleID '5859b3d0ae8eeb920e9d2f4e' -IPAddressString '1.1.1.1' -PortNumber 8443 -Direction ALL -LastUpdated 1525594605852
# This example deletes the isolation rule that is blocking all traffic to 1.1.1.1
 
.EXAMPLE
Remove-CybereasonIsolationRule -RuleID '5859b3d0ae8eeb920e9d2f4e' -IPAddressString '10.10.10.10' -PortNumber 8443 -Blocking -Direction OUTGOING -LastUpdated 1525594605852
# This example deletes the rule ID that has IP address 10.10.10.10 outbound traffic blocked
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/api-documentation/all-versions/APIReference/IsolationAPI/deleteRule.html#deleteisolationrule
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Remove-CybereasonIsolationRule {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
        [Parameter(
            Mandatory=$True,
            ValueFromPipeline=$False)]  # End Parameter
        [String]$RuleID,

        [Parameter(
            Mandatory=$False,
            ValueFromPipeline=$False,
            HelpMessage="`n[H] Enter the IP Address of the machine in the rule to delete.`n[E] EXAMPLE: 123.45.67.89")]  # End Parameter
        [String]$IpAddressString,

        [Parameter(
            Mandatory=$False,
            ValueFromPipeline=$False)]  # End Parameter
        [ValidateRange(1,65535)]
        [Int16]$PortNumber,

        [Parameter(
            Mandatory=$False,
            ValueFromPipeline=$False)]
         [Switch][Bool]$Blocking,

        [Parameter(
            Mandatory=$False,
            ValueFromPipeline=$False,
            HelpMessage="`n[H] Define the direction the rule should be applied too.`n[E] EXAMPLE: INCOMING")]  # End Parameter
        [ValidateSet('ALL','INCOMING','OUTGOING')]
        [String]$Direction,

        [Parameter(
            Mandatory=$True,
            ValueFromPipeline=$False,
            HelpMessage="`n[H] Using the Tick format, define the last update value to specifiy the rule you wish to modify the info on `n[E] EXAMPLE: 1525594605852")]  # End Parameter
        [String]$LastUpdated,

        [Parameter(
            Mandatory=$True)]  # End Parameter
        [Switch]$Force
    )  # End param

BEGIN {

    $Uri = "https://" + $Server + ":" + $Port + "/rest/settings/isolation-rule/delete"

    If ($Blocking.IsPresent)
    {

        $Block = 'true'
        $StringThree = ',"blocking":"' + $Block + '"'

    }  # End If
    Else
    {

        $Block = 'false'
        $StringThree = ',"blocking":"' + $Block + '"'

    }  # End If

    If ($IpAddressString.Length -gt 0)
    {

        $StringOne = ',"ipAddressString":"' + $IpAddressString + '"'

    }  # End If

    If ($PortNumber.Length -gt 0)
    {

        $StringTwo = ',"port":' + $PortNumber

    }  # End If

    If ($Direction.Length -gt 0)
    {

        $StringFour = ',"direction":"' + $Direction + '"'

    }  # End If

    If ($LastUpdated.Length -gt 0)
    {

        $StringFive = ',"lastUpdated":' + $LasUpdated

    }  # End If

    $JsonData = '{"ruleId":' + $RuleID + $StringOne + $StringTwo + $StringThree + $StringFour + $StringFive + '}'

}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {

        $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData
        $Response.Content | ConvertFrom-Json

    }  # End If ShouldProcess

}  # End PROCESS

}  # End Function Remove-CybereasonIsolationRule


<#
.SYNOPSIS
This cmdlet returns a count of each type of malware.
 
 
.DESCRIPTION
Returns a count of each type of malware. When sending this request, there may be a delay in returning a response, depending on how much data and activity is in your system. Ensure you do not send this request multiple times while waiting for response as this may cause unexpected results and performance issues in your environment. If you want to return fewer types of malware, you can remove the necessary filters object from the template above. In addition, if you are trying to retrieve types of malware other than the Needs Attention type, you must add multiple objects in the filters object as seen above.
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/get-malware-counts#getmalwarecounts
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonMalwareCount {
    [CmdletBinding()]
        param()  # End param


    $Uri = 'https://' + $Server + ':' + $Port + '/rest/malware/counts'
    $JsonData = '{"compoundQueryFilters":[{"filters":[{"fieldName":"needsAttention","operator":"Is","values":[true]}],"filterName":"needsAttention"},{"filters":[{"fieldName":"type","operator":"Equals","values":["KnownMalware"]},{"fieldName":"needsAttention","operator":"Is","values":[false]}],"filterName":"KnownMalware"},{"filters":[{"fieldName":"type","operator":"Equals","values":["UnknownMalware"]},{"fieldName":"needsAttention","operator":"Is","values":[false]}],"filterName":"UnknownMalware"},{"filters":[{"fieldName":"type","operator":"Equals","values":["FilelessMalware"]},{"fieldName":"needsAttention","operator":"Is","values":[false]}],"filterName":"FilelessMalware"},{"filters":[{"fieldName":"type","operator":"Equals","values":["ApplicationControlMalware"]}],"filterName":"ApplicationControlMalware"}]}'

    Write-Verbose "Sending query to $Uri"
    $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData
    $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty data | Select-Object -ExpandProperty malwareCountFilters

    $TotalCount = ($Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty data).TotalCount
    $Results += New-Object -TypeName PSObject -Property @{Filter='Total'; Count=$TotalCount}

    $Results

}  # End Function Get-CybereasonMalwareCount


<#
.SYNOPSIS
This cmdlet is supported from Cybereason version 17.5 and later. Returns details on malware currently in your environment.
 
 
.DESCRIPTION
Returns details on malware currently in your environment.
 
 
.PARAMETER MalwareType
This parameter defines the type of malware you wish to return results on
 
.PARAMETER NeedsAttention
This switch parameter indicates you wish to return results on all malware that needs attention
 
.PARAMETER All
This switch parameter indicates you wish to return information on all results of the malware type you define
 
.PARAMETER MalwareAfter
This indicates a timestamp in the form of ticks from which to start a search on malware. This will return info on any malware that occured before the date you define
 
.PARAMETER MalwareBefore
This indicates a timestamp in the form of ticks from which to start a search on malware. This will return info on any malware that occured after the date you define
 
.PARAMETER Limit
This parameter defines the amount of results to return. The default value is 25
 
.PARAMETER Sort
This parameter defines whether to sort the results in Ascending or Descending order. The default value is descending
 
.PARAMETER Offset
This parameter defines the malware page to start your search from. 0 is the default value which starts your search from the beginning
 
.PARAMETER CompletedKnownMalware
This switch parameter returns all known malware with a status of done
 
 
.EXAMPLE
Get-CybereasonMalwareType -MalwareType KnownMalware -NeedsAttention -Limit 1 -Sort ASC
# This example returns 1 result on all malware that needs attention in ascending order of their occurences
 
.EXAMPLE
Get-CybereasonMalwareType -MalwareType KnownMalware -All -Limit 25 -Sort DESC -Offset 0
# This example returns up to 25 results on all known malware in descending order
 
.EXAMPLE
Get-CybereasonMalwareType -MalwareAfter (Get-Date).AddDays(-2).Ticks
# This example returns info on all known malware that occured after a defined date
 
.EXAMPLE
Get-CybereasonMalwareType -MalwareBefore (Get-Date).AddDays(-2).Ticks
# This example returns info on all known malware that occured before a defined date
 
.EXAMPLE
Get-CybereasonMalwareType -MalwareType KnownMalware -Status Done -Limit 25 -Sort DESC -Offset 0
# This example returns info on all known malware with a status of done
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/query-malware-types
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonMalwareType {
    [CmdletBinding(DefaultParameterSetName='All')]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define one of the types of Malware you want to query the results of.`n[E] EXAMPLE: RansomwareMalware")]  # End Parameter
            [ValidateSet('KnownMalware','UnknownMalware','FilelessMalware','ApplicationControlMalware','RansomwareMalware')]
            [String]$MalwareType,

            [Parameter(
                ParameterSetName='Status',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] `n[E] EXAMPLE: Done")]  # End Parameter
            [ValidateSet('Done','Excluded','Detected','Prevented','Remediated','DeleteOnRestart','Quarantined')]
            [String]$Status,

            [Parameter(
                ParameterSetName='MalwareAfter')]  # End Parameter
                [Parameter(
                ParameterSetName='MalwareBefore')]  # End Parameter
            [Parameter(
                ParameterSetName='Status')]  # End Parameter
            [Parameter(
                ParameterSetName='NeedsAttention')]  # End Parameter
            [Switch][Bool]$NeedsAttention,

            [Parameter(
                ParameterSetName='All')]  # End Parameter
            [Switch][Bool]$All,

            [Parameter(
                ParameterSetName='MalwareAfter',
                Position=0,
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Use a timestamp in the form of ticks to discover malware that occured after a certain date and time`n[E] EXAMPLE: 637381353373709085")]  # End Parameter
            [Int64]$MalwareAfter,

            [Parameter(
                ParameterSetName='MalwareBefore',
                Position=0,
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Use a timestamp in the form of ticks to discover malware that occured before a certain date and time`n[E] EXAMPLE: 637381353373709085")]  # End Parameter
            [Int64]$MalwareBefore,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [Int32]$Limit = 25,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateSet('ASC','DESC')]
            [String]$Sort = 'DESC',

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [Int32]$Offset = 0

        )  # End param


    $Uri = 'https://' + $Server + ':' + $Port + '/rest/malware/query'

    Switch ($PSBoundParameters.Keys)
    {

        'NeedsAttention' {

            $JsonData = '{"filters": [{"fieldName":"type","operator":"Equals","values":["' + $MalwareType + '"]}],"sortingFieldName":"timestamp","sortDirection":"' + $Sort + '","limit":' + $Limit + ',"offset":' + $Offset + '})'

        }  # End Switch Needs Attention

        'All' {

            $JsonData = '{"filters":[{"fieldName":"type","operator":"Equals","values":["' + $MalwareType + '"]},{"fieldName":"needsAttention","operator":"Is","values":[' + $NeedsAttentionBool + ']}],"sortingFieldName":"timestamp","sortDirection":"' + $Sort + '","limit":' + $Limit + ',"offset":' + $Offset + '})'

        }  # End Switch AllKnownMalware

        'MalwareAfter' {

            $NeedsAttentionBool = 'false'
            If ($NeedsAttention.IsPresent)
            {

                $NeedsAttentionBool = 'true'

            }  # End If

            $JsonData = '{"filters":[{"fieldName":"type","operator": "Equals","values":["' + $MalwareType + '"]},{"fieldName":"needsAttention","operator":"Is","values":[' + $NeedsAttentionBool + ']},{"fieldName":"timestamp","operator":"GreaterOrEqualsTo","values":["timestamp"]}],"sortingFieldName":"timestamp","sortDirection":"' + $Sort + '","limit":' + $Limit + ',"offset":' + $Offset + '})'

        }  # End Switch KnownMalwareFromTime

        'MalwareBefore' {

            $NeedsAttentionBool = 'false'
            If ($NeedsAttention.IsPresent)
            {

                $NeedsAttentionBool = 'true'

            }  # End If

            $JsonData = '{"filters":[{"fieldName":"type","operator": "Equals","values":["' + $MalwareType + '"]},{"fieldName":"needsAttention","operator":"Is","values":[' + $NeedsAttentionBool + ']},{"fieldName":"timestamp","operator":"LessOrEqualsTo","values":["timestamp"]}],"sortingFieldName":"timestamp","sortDirection":"' + $Sort + '","limit":' + $Limit + ',"offset":' + $Offset + '})'

        }  # End Switch KnownMalwareFromTime

        'Status' {

            $NeedsAttentionBool = 'false'
            If ($NeedsAttention.IsPresent)
            {

                $NeedsAttentionBool = 'true'

            }  # End If

            $JsonData = '{"filters":[{"fieldName":"type","operator":"Equals","values":["' + $MalwareType + '"]},{"fieldName":"needsAttention","operator":"Is","values":[' + $NeedsAttentionBool + ']},{"fieldName":"status","operator":"Equals","values":["' + $Status + '"]}],"sortingFieldName":"timestamp","sortDirection":"' + $Sort + '","limit":' + $Limit + ',"offset":' + $Offset + '})'

        }  # End Switch CompletedKnownMalware

    }  # End Switch
    Write-Verbose "Sending query to $Uri"
    $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

    $Results = $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty data

    If ($Results.totalResults -eq 0)
    {

        Write-Output "[*] There were not any results returned"
        $Results

    }  # End If
    Else
    {

        $Results.malwares

    }  # End Else

    If ($Results.hasMoreResults -like 'True')
    {

        Write-Output "[*] More results were found but not all were returned. Raise the -Limit parameters value if you wish to view more"

    }  # End If

}  # End Function Get-CybereasonMalwareType


<#
.SYNOPSIS
This cmdlet is used to retrieve a list of custom detection rules
 
 
.DESCRIPTION
Retrieve a list of custom detection rules
 
 
.PARAMETER ActiveRules
This switch parameter returns a list of all custom rules currently active in your environment.
 
.PARAMETER DisabledRules
This switch parameter returns a list of all custom rules currently disabled in your environment.
 
.PARAMETER RootCauses
Returns a list of all Elements you can use for a root cause for a Malop generated from this custom rule.
 
.PARAMETER DetectionTypes
Returns a list of all available detection types you can use for the custom detection rule.
 
.PARAMETER ActivityTypes
Returns a list of all available Malop activity types you can use for the custom detection rule.
 
.PARAMETER RuleID
Define the rule ID value you wish to view the modificaiton history on
 
.PARAMETER ModificationHistory
Returns details on modifications made to a custom rule.
 
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -ActiveRules
# This eample returns a list of all custom rules currently active in your environment.
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -DisabledRules
# This eample returns a list of all custom rules currently disabled in your environment.
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -RootCauses
# This eample returns a list of all Elements you can use for a root cause for a Malop generated from this custom rule.
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -DetectionTypes
# This eample returns a list of all available detection types you can use for the custom detection rule.
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -ActivityTypes
# This eample returns a list of all available Malop activity types you can use for the custom detection rule.
 
.EXAMPLE
Get-CybereasonCustomDetectionRule -RuleID 1582038865368 -ModificationHistory
# This eample returns details on modifications made to a custom rule.
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/add-custom-detection-rules
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonCustomDetectionRule {
    [CmdletBinding(DefaultParameterSetName='Active')]
        param(
            [Parameter(
                ParameterSetName='Active')]  # End Parameter
            [Switch][Bool]$Active,

            [Parameter(
                ParameterSetName='Disabled')]  # End Parameter
            [Switch][Bool]$Disabled,

            [Parameter(
                ParameterSetName='RootCauses')]  # End Parameter
            [Switch][Bool]$RootCauses,

            [Parameter(
                ParameterSetName='DetectionTypes')]  # End Parameter
            [Switch][Bool]$DetectionTypes,

            [Parameter(
                ParameterSetName='ActivityTypes')]  # End Parameter
            [Switch][Bool]$ActivityTypes,

            [Parameter(
                ParameterSetName='ModificationHistory',
                Position=0,
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the Rule ID you want to view modification history on `n[E] EXAMPLE: 1582038865368")]  # End Parameter
            [Int64]$RuleID,

            [Parameter(
                ParameterSetName='ModificationHistory'
            )]  # End Parameter
            [Switch][Bool]$ModificationHistory

        )  # End param

    $Obj = @()

    Switch ($PSBoundParameters.Keys)
    {

        'Active' {

            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/decisionFeature/live'

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty rules | `
            ForEach-Object {
                $id = ($_.id | Out-String).Trim()
                $Name = ($_.name | Out-String).Trim()
                $RootCause = ($_.rootCause | Out-String).Trim()
                $malopDetectionType = ($_.malopDetectionType | Out-String).Trim()
                $parentId = ($_.rule.parentId | Out-String).Trim()
                $elementType = ($_.rule.root.elementType | Out-String).Trim()
                $facetName = ($_.rule.root.filters.facetName | Out-String).Trim()
                $values = ($_.rule.root.filters.values | Out-String).Trim()
                $filterType = ($_.rule.root.filters.filterType | Out-String).Trim()
                $featureTranslation = ($_.rule.root.filters.featureTranslation | Out-String).Trim()
                $children = $_.rule.root.children
                $malopActivityType = ($_.root.malopActivityType | Out-String).Trim()
                $description = ($_.description | Out-String).Trim()
                $enabled = ($_.enabled | Out-String).Trim()
                $userName = ($_.userName | Out-String).Trim()
                $creationTime = Get-Date -Date ($_.creationTime)
                $updateTime = Get-Date -Date ($_.updateTime)
                $lastTriggerTime = Get-Date -Date ($_.lastTriggerTime)
                $autoRemediationActions = $_.autoRemediationActions
                $autoRemediationStatus = $_.autoRemediationStatus
                $limitExceed = ($Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty limitExceed | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{
                    id=$id;
                    Name=$name;
                    RootCause=$RootCause;
                    malopDetectionType=$malopDetectionType;
                    parentId=$parentId;
                    elementType=$elementType;
                    facetName=$facetName;
                    values=$values;
                    filterType=$filterType;
                    featureTranslation=$featureTranslation;
                    children=$children;
                    malopActivityType=$malopActivityType;
                    description=$description;
                    enabled=$enabled;
                    userName=$userName;
                    creationTime=$creationTime;
                    updateTime=$updateTime;
                    lastTriggerTime=$lastTriggerTime;
                    autoRemediationActions=$autoRemediationActions;
                    autoRemediationStatus=$autoRemediationStatus;
                    limitExceed=$limitExceed
                }  # End Properties

            }  # End ForEach-Object

            If ($Obj.Count -eq 0)
            {

                Write-Output "[*] No results were found"

            }  # End If
            Else
            {

                $Obj

            }  # End Else


        }  # End Switch Active

        'Disabled' {

            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/decisionFeature/deleted'

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty rules | `
            ForEach-Object {
                $id = ($_.id | Out-String).Trim()
                $Name = ($_.name | Out-String).Trim()
                $RootCause = ($_.rootCause | Out-String).Trim()
                $malopDetectionType = ($_.malopDetectionType | Out-String).Trim()
                $parentId = ($_.rule.parentId | Out-String).Trim()
                $elementType = ($_.rule.root.elementType | Out-String).Trim()
                $facetName = ($_.rule.root.filters.facetName | Out-String).Trim()
                $values = ($_.rule.root.filters.values | Out-String).Trim()
                $filterType = ($_.rule.root.filters.filterType | Out-String).Trim()
                $featureTranslation = ($_.rule.root.filters.featureTranslation | Out-String).Trim()
                $children = $_.rule.root.children
                $malopActivityType = ($_.root.malopActivityType | Out-String).Trim()
                $description = ($_.description | Out-String).Trim()
                $enabled = ($_.enabled | Out-String).Trim()
                $userName = ($_.userName | Out-String).Trim()
                $creationTime = Get-Date -Date ($_.creationTime)
                $updateTime = Get-Date -Date ($_.updateTime)
                $lastTriggerTime = Get-Date -Date ($_.lastTriggerTime)
                $autoRemediationActions = $_.autoRemediationActions
                $autoRemediationStatus = $_.autoRemediationStatus
                $limitExceed = ($Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty limitExceed | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{
                    id=$id;
                    Name=$name;
                    RootCause=$RootCause;
                    malopDetectionType=$malopDetectionType;
                    parentId=$parentId;
                    elementType=$elementType;
                    facetName=$facetName;
                    values=$values;
                    filterType=$filterType;
                    featureTranslation=$featureTranslation;
                    children=$children;
                    malopActivityType=$malopActivityType;
                    description=$description;
                    enabled=$enabled;
                    userName=$userName;
                    creationTime=$creationTime;
                    updateTime=$updateTime;
                    lastTriggerTime=$lastTriggerTime;
                    autoRemediationActions=$autoRemediationActions;
                    autoRemediationStatus=$autoRemediationStatus;
                    limitExceed=$limitExceed
                }  # End Properties

            }  # End ForEach-Object

            If ($Obj.Count -eq 0)
            {

                Write-Output "[*] No results were found"

            }  # End If
            Else
            {

                $Obj

            }  # End Else

        }  # End Switch Disabled

        'RootCauses' {

            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/rootCauses'

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json

        }  # End Switch RootCauses

        'DetectionTypes' {

            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/getMalopDetectionTypes'

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json

        }  # End Switch DetectionTypes

        'ActivityTypes' {

            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/getMalopActivityTypes'

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json

        }  # End Switch ActivityTypes

        'ModificationHistory' {

            $Obj = @()
            $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/history/' + $RuleID.ToString()

            Write-Verbose "Sending query to $Uri"
            $Response = Invoke-WebRequest -Method GET -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession

            $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty history | `
            ForEach-Object {
                $Username = ($_.username | Out-String).Trim()
                $Date = Get-Date -Date $_.date
                $JsonRef = ($_.changes.jsonRef | Out-String).Trim()
                $OriginalValue = ($_.changes.originalValue | Out-String).Trim()
                $NewValue = ($_.changes.newValue | Out-String).Trim()

                $Obj += New-Object -TypeName PSObject -Property @{Username=$Username; $Date=$Date; JsonRef=$JsonRef; OriginalValue=$OriginalValue; NewValue=$NewValue}

            }  # End ForEach-Object

            If ($Obj.Length -eq 0)
            {

                Write-Output "[*] No results were found"

            }  # End If
            Else
            {

                $Obj

            }  # End Else

        }  # End Switch ModificationHistory

    }  # End Switch

}  # End Function Get-CybereasonCustomDetectionRule


<#
.SYNOPSIS
This cmdlet is used to creates a custom detection rule
 
 
.DESCRIPTION
Creates a custom detection rule. Custom detection rules created via API should be created only after adequate research regarding precision and coverage has been completed. Creating a custom detection rule that is not specific enough can have detrimental impact on retention and overall performance of the environment.
 
 
.PARAMETER Name
This parameter gives the rule you are creating a name
 
.PARAMETER FacetName
The name of the Feature on which to filter the base Element
 
.PARAMETER ChildFacetName
The name of the child feature on which to filter the base Child Element
 
.PARAMETER RootCause
The Element which is identified as the root cause in the Malop generated from the custom detection rule. Possible values include: self (the base Element is malicious) OR imageFile (the image file for the base Element is malicious) OR parentProcess (the parent process for the base Element is malicious)
 
.PARAMETER MalopDetectionType
The detection type to assign to Malops generated from this custom detection rule.
 
.PARAMETER MalopActivityType
The activity type to assign to Malops generated from this custom detection rule.
 
.PARAMETER ElementType
The Element used as the base of the custom detection rule.
 
.PARAMETER ChildElementType
The Child Element used as the base of the custom detection rule.
 
.PARAMETER ConnectionFeature
Parameter to define the link between parent and child facets. https://nest.cybereason.com/api-documentation/all-versions/APIReference/CustomRulesAPI/customRulesConnectionFeatures.html#supported-features-for-linking-elements-in-a-custom-detection-rule
 
.PARAMETER Description
The description for this custom detection rule.
 
.PARAMETER EnableOnCreation
Indicates whether or not to enable this detection rule upon creation. Defining this switch parameter sets this value to true to automatically enable the rule.
 
.PARAMETER KillProcess
This parameter indicates you want to kill any malicious discovered processes
 
.PARAMETER QuarantineFile
This paraemeter defines that you want to quarantine files that are infectious
 
.PARAMETER IsolateMachine
This parameter indicates you want to isolate machines that become infected
 
 
.EXAMPLE
New-CybereasonCustomDetectionRule
# This example
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/add-custom-detection-rules
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function New-CybereasonCustomDetectionRule {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] This parameter is a name to assign to the custom rule. `n[E] EXAMPLE: Test Rule 1"
            )]  # End Parameter
            [String]$Name,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the Feature on which to filter the base Element.`n[E] EXAMPLE: maliciousUseOfRegsvr32ModuleEvidence")]  # End Parameter
            [String]$FacetName,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the child Feature on which to filter the base Element.`n[E] EXAMPLE: maliciousUseOfRegsvr32ModuleEvidence")]  # End Parameter
            [String]$ChildFacetName,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element which is identified as the root cause in the Malop generated from the custom detection rule. `n[E] EXAMPLE: parentProcess")]  # End Parameter
            [ValidateSet('self','imageFile','parentProcess')]
            [String]$RootCause,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The detection type to assign to Malops generated from this custom detection rule.`n[E] EXAMPLE: BLACKLIST")]  # End Parameter
            [ValidateSet('BLACKLIST','CNC','CUSTOM_RULE','UNAUTHORIZED_USER','CREDENTIAL_THEFT','DATA_TRANSMISSION_VOLUME','ELEVATED_ACCESS','EXTENSION_MANIPULATION','KNOWN_MALWARE','LATERAL_MOVEMENT','MALWARE_PROCESS','MALICIOUS_PROCESS','PUP','PERSISTENCE','PHISHING','PROCESS_INJECTION','RANSOMWARE','RECONNAISSANCE')]
            [String]$MalopDetectionType,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The activity type to assign to Malops generated from this custom detection rule.`n[E] EXAMPLE: STOLEN_CREDENTIALS")]  # End Parameter
            [ValidateSet('CNC_COMMUNICATION','DATA_THEFT','MALICIOUS_INFECTION','LATERAL_MOVEMENT','PRIVILEGE_ESCALATION','RANSOMWARE','SCANNING','STOLEN_CREDENTIALS')]
            [String]$MalopActivityType,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element used as the base of the custom detection rule. Possible values include: Process or LogonSession `n[E] EXAMPLE: Process")]  # End Parameter
            [ValidateSet('Process','LogonSession')]
            [String]$ElementType,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element used as the base of the custom detection rule. Possible values include: Process or LogonSession `n[E] EXAMPLE: Process")]  # End Parameter
            [ValidateSet('Process','LogonSession')]
            [String]$ChildElementType,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the Feature that connects the linked Elements. `n[E] EXAMPLE: msword.exe")]  # End Parameter
            [String]$ChildElementName,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="The name of the Feature that connects the linked Elements. This Feature name corresponds with the name of the linked Element. For details on the Features available to use as connection features, see Supported Features for Linking Elements in a Custom Detection Rule. https://nest.cybereason.com/api-documentation/all-versions/APIReference/CustomRulesAPI/customRulesConnectionFeatures.html#supported-features-for-linking-elements-in-a-custom-detection-rule")]  # End Parameter
            [ValidateSet('DomainName','Machine','urlDomains','fileHash','ownerMachine','remoteMachine','user','file','autorun','children','connections','hostedChildren','hostProcess','imageFile','injectedChildren','loadedModules','originInjector','parentProcess','scheduledTask','service','executableActions','binaryFile')]
            [String]$ConnectionFeature,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [String]$Description = $Name,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$EnableOnCreation,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$KillProcess,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$QuarantineFile,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$IsolateMachine,

            [Parameter(
                Mandatory=$True)]  # End Parameter
            [Switch]$Force
        )  # End param

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If

    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If

    if (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    If ($EnableOnCreation.IsPresent) { $EnableOnCreate = 'true' }  # End If
    Else { $EnableOnCreate = 'false' }  # End Else

    If ($QuarantineFile.IsPresent) { $EnableQuarantine = 'true' }  # End If
    Else { $EnableQuarantine = 'false' }  # End Else

    If ($IsolateMachine.IsPresent) { $EnableIsolate = 'true' }  # End If
    Else { $EnableIsolate = 'false' }  # End Else

    If ($KillProcess.IsPresent) { $EnableKill = 'true' }  # End If
    Else { $EnableKill = 'false' }  # End Else


    $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/decisionFeature/create'

    Switch ($PSBoundParameters.Keys)
    {

        'Children' {

            $JsonData = '{"name":"' + $Name + '","rootCause":"' + $RootCause + '","malopDetectionType":"' + $MalopDetectionType + '","autoRemediationActions":{"killProcess":' + $EnableKill + ',"quarantineFile":' + $EnableQuarantine + ',"isolateMachine":' + $EnableIsolate + '},"autoRemediationStatus":"Active","rule":{"root":{"elementType":"' + $ElementType + '","elementTypeTranslation":"' + $ElementType + '","filters":[{"facetName":"' + $FacetName + '","filterType":"Equals","values":[True]}],"children": [{"elementType":"' + $ChildElementType + '","elementTypeTranslation":"' + $ChildElementType + '","connectionFeature":"' + $ConnectionFeature + '","connectionFeatureTranslation":"' + $ConnectionFeature + '","reversed":False,"filters": [{"facetName":"' + $ChildFacetName + '","filterType":"ContainsIgnoreCase","values":["' + $ChildElementName + '"]}]}]},"malopActivityType":"' + $MalopActivityType +  '"},"description":"' + $Description + '","enabled":' + $EnableOnCreate + '}'

        }  # End Switch Children

        Default {

            $JsonData = '{"name":"' + $Name + '","rootCause":"' + $RootCause + '","malopDetectionType":"' + $MalopDetectionType + '","autoRemediationActions":{"killProcess":' + $EnableKill + ',"quarantineFile":' + $EnableQuarantine + ',"isolateMachine":' + $EnableIsolate + '},"autoRemediationStatus":"Active","rule":{"root":{"elementType":"' + $ElementType + '","elementTypeTranslation":"' + $ElementType + '","filters":[{"facetName":"' + $FacetName + '","filterType":"Equals","values":[True]}]}},"malopActivityType":"' + $MalopActivityType +  '"},"description":"' + $Description + '","enabled":' + $EnableOnCreate + '}'

        }  # End Switch Default

    }  # End Switch

}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {

        Write-Verbose "Sending query to $Uri"
        $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

        $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty rules | `
                ForEach-Object {
                    $id = ($_.id | Out-String).Trim()
                    $Name = ($_.name | Out-String).Trim()
                    $RootCause = ($_.rootCause | Out-String).Trim()
                    $malopDetectionType = ($_.malopDetectionType | Out-String).Trim()
                    $parentId = ($_.rule.parentId | Out-String).Trim()
                    $elementType = ($_.rule.root.elementType | Out-String).Trim()
                    $facetName = ($_.rule.root.filters.facetName | Out-String).Trim()
                    $values = ($_.rule.root.filters.values | Out-String).Trim()
                    $filterType = ($_.rule.root.filters.filterType | Out-String).Trim()
                    $featureTranslation = ($_.rule.root.filters.featureTranslation | Out-String).Trim()
                    $children = $_.rule.root.children
                    $malopActivityType = ($_.root.malopActivityType | Out-String).Trim()
                    $description = ($_.description | Out-String).Trim()
                    $enabled = ($_.enabled | Out-String).Trim()
                    $userName = ($_.userName | Out-String).Trim()
                    $creationTime = Get-Date -Date ($_.creationTime)
                    $updateTime = Get-Date -Date ($_.updateTime)
                    $lastTriggerTime = Get-Date -Date ($_.lastTriggerTime)
                    $autoRemediationActions = $_.autoRemediationActions
                    $autoRemediationStatus = $_.autoRemediationStatus
                    $limitExceed = ($Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty limitExceed | Out-String).Trim()

                    $Obj += New-Object -TypeName PSObject -Property @{id=$id; Name=$name; RootCause=$RootCause; malopDetectionType=$malopDetectionType; parentId=$parentId; elementType=$elementType; facetName=$facetName; Values=$values;filterType=$filterType;featureTranslation=$featureTranslation;children=$children;malopActivityType=$malopActivityType;description=$description;enabled=$enabled;userName=$userName;creationTime=$creationTime;updateTime=$updateTime;lastTriggerTime=$lastTriggerTime;autoRemediationActions=$autoRemediationActions;autoRemediationStatus=$autoRemediationStatus;limitExceed=$limitExceed}  # End Properties

                }  # End ForEach-Object

        $Obj

    }  # End If ShouldProcess

}  # End PROCESS

}  # End Function New-CybereasonCustomDetectionRule


<#
.SYNOPSIS
This cmdlet is used to updates an existing custom detection rule
 
 
.DESCRIPTION
Updates an existing custom detection rule. Custom Detection Rules can be created via API but should be created only once adequate research regarding precision and coverage has been completed. Creating a custom detection rule that is not specific enough can have detrimental impact on Retention and overall performance of the environment
 
 
.PARAMETER RuleID
The unique identifier for the custom detection rule.
 
.PARAMETER Name
This parameter gives the rule you are creating a name
 
.PARAMETER FacetName
The name of the Feature on which to filter the base Element
 
.PARAMETER ChildFacetName
The name of the child feature on which to filter the base Child Element
 
.PARAMETER RootCause
The Element which is identified as the root cause in the Malop generated from the custom detection rule. Possible values include: self (the base Element is malicious) OR imageFile (the image file for the base Element is malicious) OR parentProcess (the parent process for the base Element is malicious)
 
.PARAMETER MalopDetectionType
The detection type to assign to Malops generated from this custom detection rule.
 
.PARAMETER MalopActivityType
The activity type to assign to Malops generated from this custom detection rule.
 
.PARAMETER ElementType
The Element used as the base of the custom detection rule.
 
.PARAMETER ChildElementType
The Child Element used as the base of the custom detection rule.
 
.PARAMETER ConnectionFeature
Parameter to define the link between parent and child facets. https://nest.cybereason.com/api-documentation/all-versions/APIReference/CustomRulesAPI/customRulesConnectionFeatures.html#supported-features-for-linking-elements-in-a-custom-detection-rule
 
.PARAMETER Description
The description for this custom detection rule.
 
.PARAMETER EnableOnCreation
Indicates whether or not to enable this detection rule upon creation. Defining this switch parameter sets this value to true to automatically enable the rule.
 
.PARAMETER KillProcess
This parameter indicates you want to kill any malicious discovered processes
 
.PARAMETER QuarantineFile
This paraemeter defines that you want to quarantine files that are infectious
 
.PARAMETER IsolateMachine
This parameter indicates you want to isolate machines that become infected
 
.PARAMETER Username
The Cybereason user name for the user updating the rule
 
 
.EXAMPLE
Set-CybereasonCustomDetectionRule -RuleID 1580246401162 -Name 'Test Rule 1' -FacetName 'maliciousUseOfRegsvr32ModuleEvidence' -ChildFacetName name -RootCause self
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/update-custom-detection-rule
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Set-CybereasonCustomDetectionRule {
    [CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="High")]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The unique identifier for the custom detection rule.`n[E] EXAMPLE: 1580246401162")]  # End Parameter
            [Int64]$RuleID,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] This parameter is a name to assign to the custom rule. `n[E] EXAMPLE: Test Rule 1"
            )]  # End Parameter
            [String]$Name,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the Feature on which to filter the base Element.`n[E] EXAMPLE: maliciousUseOfRegsvr32ModuleEvidence")]  # End Parameter
            [String]$FacetName,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the child Feature on which to filter the base Element.`n[E] EXAMPLE: name")]  # End Parameter
            [String]$ChildFacetName,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element which is identified as the root cause in the Malop generated from the custom detection rule. `n[E] EXAMPLE: parentProcess")]  # End Parameter
            [ValidateSet('self','imageFile','parentProcess')]
            [String]$RootCause,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The detection type to assign to Malops generated from this custom detection rule.`n[E] EXAMPLE: BLACKLIST")]  # End Parameter
            [ValidateSet('BLACKLIST','CNC','CUSTOM_RULE','UNAUTHORIZED_USER','CREDENTIAL_THEFT','DATA_TRANSMISSION_VOLUME','ELEVATED_ACCESS','EXTENSION_MANIPULATION','KNOWN_MALWARE','LATERAL_MOVEMENT','MALWARE_PROCESS','MALICIOUS_PROCESS','PUP','PERSISTENCE','PHISHING','PROCESS_INJECTION','RANSOMWARE','RECONNAISSANCE')]
            [String]$MalopDetectionType,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The activity type to assign to Malops generated from this custom detection rule.`n[E] EXAMPLE: STOLEN_CREDENTIALS")]  # End Parameter
            [ValidateSet('CNC_COMMUNICATION','DATA_THEFT','MALICIOUS_INFECTION','LATERAL_MOVEMENT','PRIVILEGE_ESCALATION','RANSOMWARE','SCANNING','STOLEN_CREDENTIALS')]
            [String]$MalopActivityType,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element used as the base of the custom detection rule. Possible values include: Process or LogonSession `n[E] EXAMPLE: Process")]  # End Parameter
            [ValidateSet('Process','LogonSession')]
            [String]$ElementType,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Element used as the base of the custom detection rule. Possible values include: Process or LogonSession `n[E] EXAMPLE: Process")]  # End Parameter
            [ValidateSet('Process','LogonSession')]
            [String]$ChildElementType,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The name of the Feature that connects the linked Elements. `n[E] EXAMPLE: msword.exe")]  # End Parameter
            [String]$ChildElementName,

            [Parameter(
                ParameterSetName='Children',
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="The name of the Feature that connects the linked Elements. This Feature name corresponds with the name of the linked Element. For details on the Features available to use as connection features, see Supported Features for Linking Elements in a Custom Detection Rule. https://nest.cybereason.com/api-documentation/all-versions/APIReference/CustomRulesAPI/customRulesConnectionFeatures.html#supported-features-for-linking-elements-in-a-custom-detection-rule")]  # End Parameter
            [ValidateSet('DomainName','Machine','urlDomains','fileHash','ownerMachine','remoteMachine','user','file','autorun','children','connections','hostedChildren','hostProcess','imageFile','injectedChildren','loadedModules','originInjector','parentProcess','scheduledTask','service','executableActions','binaryFile')]
            [String]$ConnectionFeature,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [String]$Description = $Name,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$EnableOnCreation,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$KillProcess,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$QuarantineFile,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch][Bool]$IsolateMachine,

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] The Cybereason user name for the user updating the rule.`n[E] EXAMPLE: admin@cybereason.com")]  # End Parameter
            [String]$Username,

            [Parameter(
                Mandatory=$False)]  # End Parameter
            [Switch]$Force

        )  # End param

BEGIN {

    If (-not $PSBoundParameters.ContainsKey('Verbose'))
    {

        $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('Confirm'))
    {

        $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')

    }  # End If
    If (-not $PSBoundParameters.ContainsKey('WhatIf'))
    {

        $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')

    }  # End If

    If ($EnableOnCreation.IsPresent) { $EnableOnCreate = 'true' }  # End If
    Else { $EnableOnCreate = 'false' }  # End Else

    If ($QuarantineFile.IsPresent) { $EnableQuarantine = 'true' }  # End If
    Else { $EnableQuarantine = 'false' }  # End Else

    If ($IsolateMachine.IsPresent) { $EnableIsolate = 'true' }  # End If
    Else { $EnableIsolate = 'false' }  # End Else

    If ($KillProcess.IsPresent) { $EnableKill = 'true' }  # End If
    Else { $EnableKill = 'false' }  # End Else

    $Uri = 'https://' + $Server + ':' + $Port + '/rest/customRules/decisionFeature/update'

    $JsonData = '{"id":' + $RuleID + ',"name":"' + $Name + '","rootCause":"' + $RootCause + '","malopDetectionType":"' + $MalopDetectionType + '","autoRemediationActions":{"killProcess":' + $EnableKill + ',"quarantineFile":' + $EnableQuarantine + ',"isolateMachine":' + $EnableIsolate + '},"autoRemediationStatus":"Active","rule":{"root":{"elementType":"' + $ElementType + '","elementTypeTranslation":"' + $ElementType + '","filters":[{"facetName":"' + $FacetName + '","filterType":"Equals","values":[True]}],"children": [{"elementType":"' + $ChildElementType + '","elementTypeTranslation":"' + $ChildElementName + '","connectionFeature":"' + $ConnectionFeature + '","connectionFeatureTranslation":"' + $ConnectionFeature + '","reversed":False,"filters": [{"facetName":"' + $ChildElementType + '","filterType":"ContainsIgnoreCase","values":["' + $ChildElementName + '"]}]}]},"malopActivityType":"' + $MalopActivityType + '"},"description":"' + $Description + '","enabled":' + $EnableOnCreate + '})'

}  # End BEGIN
PROCESS {

    If ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?"))
    {

        Write-Verbose "Sending query to $Uri"
        $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

        $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty rules | `
                ForEach-Object {
                    $id = ($_.id | Out-String).Trim()
                    $Name = ($_.name | Out-String).Trim()
                    $RootCause = ($_.rootCause | Out-String).Trim()
                    $malopDetectionTypes = ($_.malopDetectionType | Out-String).Trim()
                    $parentId = ($_.rule.parentId | Out-String).Trim()
                    $elementType = ($_.rule.root.elementType | Out-String).Trim()
                    $facetName = ($_.rule.root.filters.facetName | Out-String).Trim()
                    $values = ($_.rule.root.filters.values | Out-String).Trim()
                    $filterType = ($_.rule.root.filters.filterType | Out-String).Trim()
                    $featureTranslation = ($_.rule.root.filters.featureTranslation | Out-String).Trim()
                    $children = $_.rule.root.children
                    $malopActivityType = ($_.root.malopActivityType | Out-String).Trim()
                    $description = ($_.description | Out-String).Trim()
                    $enabled = ($_.enabled | Out-String).Trim()
                    $userName = ($_.userName | Out-String).Trim()
                    $creationTime = Get-Date -Date ($_.creationTime)
                    $updateTime = Get-Date -Date ($_.updateTime)
                    $lastTriggerTime = Get-Date -Date ($_.lastTriggerTime)
                    $autoRemediationActions = $_.autoRemediationActions
                    $autoRemediationStatus = $_.autoRemediationStatus
                    $limitExceed = ($Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty limitExceed | Out-String).Trim()

                    $Obj += New-Object -TypeName PSObject -Property @{id=$id; Name=$name; RootCause=$RootCause; malopDetectionType=$MalopDetectionTypes; parentId=$parentId; elementType=$elementType; facetName=$facetName; Values=$values;filterType=$filterType;featureTranslation=$featureTranslation;children=$children;malopActivityType=$malopActivityType;description=$description;enabled=$enabled;userName=$userName;creationTime=$creationTime;updateTime=$updateTime;lastTriggerTime=$lastTriggerTime;autoRemediationActions=$autoRemediationActions;autoRemediationStatus=$autoRemediationStatus;limitExceed=$limitExceed}  # End Properties

                }  # End ForEach-Object

                $Obj

    }  # End If

}  # End PROCESS

}  # End Function Set-CybereasonCustomDetectionRule


<#
.SYNOPSIS
Sends a request to return details on all or a selected group of sensors. You must be assigned the System Admin role to send requests to this endpoint URL.
 
 
.PARAMETER Limit
The number of sensors to which to send the request. Valid values run from 0-1000.
 
.PARAMETER Offset
Set to 0 to receive the first limit set of sensors.
 
.PARAMETER Sort
The order in which to receive results. Valid values are ASC (ascending) or DESC (descending)
 
.PARAMETER Filter
An object containing details on the filter to apply to return a select group of sensors. f you add a parameter in the filters object, ensure you use this syntax: {“fieldName”: “<filter parameter>”, “operator”: “<operator>”, “values”: [“<value>”]}
Field Type Description
actionsInProgress Integer The number of actions in progress (i.e. Not Resolved) on the machine.
amStatus Enum
 
The Anti-Malware installation status for the sensor. Possible values include:
 
    AM_INSTALLED
    AM_UNINSTALLED
 
antiExploitStatus Enum
 
The status of the Exploit Prevention feature. Possible values include:
 
    ENABLED
    DISABLED
 
This field returns a value only if you have enabled Exploit Prevention.
 
This field is applicable for versions 20.1 and higher.
antiMalwareStatus Enum
 
The Anti-Malware prevention mode for the sensor. Possible values include:
 
    AM_DETECT_DISINFECT
    AM_DEFAULT
 
archiveTimeMs Timestamp The time (in epoch) when the sensor was archived.
archiveOrUnarchiveComment String The comment added when a sensor was archived or unarchived.
collectionComponents Enum
 
Any special collections enabled on the server and/or sensor. Possible values include:
 
    DPI
    Metadata
    File events
    Registry events
 
collectionStatus Enum
 
States whether the machine has data collection enabled. Possible values include:
 
    ENABLED
    DISABLED
    SUSPENDED
 
compliance Boolean Indicates whether the current sensor settings match the policy settings.
cpuUsage Float The amount of CPU used by the machine (expressed as a percentage).
criticalAsset Boolean The value assigned for the machine for the CRITICAL ASSET sensor tag.
customTags String A list of custom sensor tags assigned to the machine.
deliveryTime Timestamp The time (in epoch) when the last policy update was delivered to the sensor
department String The value assigned to the machine for the DEPARTMENT sensor tag.
deviceType String The value assigned to the machine for the DEVICE TYPE sensor tag.
disconnected Boolean Indicates whether a sensor is currently disconnected.
disconnectionTime Timestamp Time the machine was disconnected. Returns 0 if this is the first connection time. After the first connection, this is the time it was last connected.
exitReason String The reason the sensor service (minionhost.exe) stopped.
externalIpAddress String The machine’s external IP address for the local network.
firstSeenTime Timestamp The first time the machine was recognized. Timestamp values are returned in epoch.
fullScanStatus Enum The status set for the sensor for the full scan.
fqdn String The fully qualified domain name (fqdn) for the machine.
fwStatus Enum
 
The status of the Personal Firewall Control feature. Possible values include:
 
    DISABLED
    ENABLED
 
This field returns a value only if you have enabled Endpoint Controls.
 
This field is applicable for versions 19.2 and higher.
guid String The globally unique sensor identifier.
lastStatusAction String The last action taken that changed the sensor status.
lastUpgradeResult Enum
 
The result of the last upgrade process. Possible values include:
 
    None
    Pending
    InProgress
    FailedSending
    Primed
    UnknownProbe
    NotSupported
    Disconnected
    TimeoutSending
    Failed
    Succeeded
    Timeout
    InvalidState
    UnauthorizedUser
    partialResponse
    ChunksRequired
    Aborted
    GettingChunks
    ProbeRemoved
    FailedSendingToServer
    Started
    SendingMsi
    MsiSendFail
    MsiFileCorrupted
    AlreadyUpdated
    NewerInstalled
 
lastUpgradeSteps Enum
 
A list of step taken in the upgrade process. Possible values include:
 
    None
    Pending
    InProgress
    FailedSending
    Primed
    UnknownProbe
    NotSupported
    Disconnected
    TimeoutSending
    Failed
    Succeeded
    Timeout
    InvalidState
    UnauthorizedUser
    partialResponse
    ChunksRequired
    Aborted
    GettingChunks
    ProbeRemoved
    FailedSendingToServer
    Started
    SendingMsi
    MsiSendFail
    MsiFileCorrupted
    AlreadyUpdated
    NewerInstalled
 
If there is a failure to upgrade the sensor, this list shows the failure.
internalIpAddress String The machine’s internal IP address as identified by the sensor.
isolated Boolean States whether the machine is isolated. Returns true if the machine is isolated.
lastFullScheduleScanSuccessTime Timestamp The time (in epoch) that the sensor last did a successful full scan.
lastQuickScheduleScanSuccessTime Timestamp The time (in epoch) that the sensor last did a successful quick scan.
lastPylumInfoMsgUpdateTime Timestamp The last time (in epoch) the sensor sent a message to the Cybereason server.
location String The value assigned for this machine for the LOCATION sensor tag.
machineName String The name of the machine.
memoryUsage Long The amount of RAM on the hosting computer used by the sensor.
offlineTimeMS Timestamp The last time (in epoch) that the sensor was offline.
onlineTimeMS Timestamp The last time the sensor was seen online.
organization String The organization name for the machine on which the sensor is installed.
osType Enum
 
The operating system running on the machine. Possible values include:
 
    UNKNOWN_OS
    WINDOWS
    OSX
    LINUX
 
osVersionType Enum
 
Version of operating system for the machine. Possible values include:
 
    Windows_8_1
    Windows_8
    Windows_7
    Windows_Vista
    Windows_XP_Professional_x64_Edition
    Windows_XP
    Windows_2000
    Windows_Server_2012_R2
    Windows_Server_2012
    Windows_Server_2008_R2
    Windows_Server_2008
    Windows_Server_2003_R2
    Windows_Home_Server
    Windows_Server_2003
    Windows_Server_2016
    Windows_Server_2019
    Windows_10
    Catalina_10_15
    Mojave_10_14
    High_Sierra_10_13
    Sierra_10_12
    El_Capitan_10_11
    Yosemite_10_10
    Maverick_10_9
    Centos_Linux_6
    Centos_Linux_7
    Red_Hat_Enterprise_Linux_6
    Red_Hat_Enterprise_Linux_7
    Ubuntu_Linux_12
    Ubuntu_Linux_14
    Ubuntu_Linux_16
    Ubuntu_Linux_17
    Ubuntu_Linux_18
    Oracle_Linux_6
    Oracle_Linux_7
    Suse_Linux_12
    Amazon_Linux_2011__09
    Amazon_Linux_2012__03
    Amazon_Linux_2012__09
    Amazon_Linux_2013__03
    Amazon_Linux_2013__09
    Amazon_Linux_2014__03
    Amazon_Linux_2014__09
    Amazon_Linux_2015__03
    Amazon_Linux_2015__09
    Amazon_Linux_2016__03
    Amazon_Linux_2016__09
    Amazon_Linux_2017__03
    Debian_Linux_8
    Debian_Linux_9
 
outdated Boolean States whether or not the sensor version is out of sync with the server version.
pendingActions Array A list of actions pending to run on the sensor.
policyId String The unique identifier the Cybereason platform uses for the policy assigned to the sensor.
policyName String The name of the policy assigned to this sensor.
powerShellStatus Enum
 
The PowerShell Prevention mode. Possible values include:
 
    PS_DISABLED
    PS_ENABLED
    PS_DEFAULT
 
preventionError String The error received for prevention by the sensor.
preventionStatus Enum
 
The Execution Prevention mode. Possible values include:
 
    ENABLE
    DISABLE
    UNINSTALL
    UNKNOWN
 
proxyAddress String The address for the Proxy server used by this sensor.
pylumID String The unique identifier assigned by Cybereason to the sensor.
quickScanStatus Enum The status set for the sensor for a quick scan.
ransomwareStatus Enum
 
The Anti-Ransomware mode. Possible values include:
 
    UNKNOWN
    DISABLED
    DETECT_ONLY
    DETECT_AND_SUSPEND
    DETECT_SUSPEND_PREVENT
 
remoteShellStatus Enum
 
Whether or not the Remote Shell utility is enabled for the sensor. Possible values include:
 
    AC_DISABLED
    AC_ENABLED
 
This field returns a value only if you have enabled Remote Shell for your Cybereason server.
sensorId String The unique identifier for a sensor.
sensorArchivedByUser String The Cybereason user name for the user who archived the selected sensor.
sensorLastUpdate Timestamp The last time (in epoch) that the sensor was updated.
serverId String The unique identifier for the sensor’s server.
serverName String The name of the server for the sensor.
serviceStatus Enum
 
Indicates the current value of the Anti-Malware service. Possible values include:
 
    DISABLED
    DETECT
    PREVENT
    SET_BY_POLICY
 
siteName String The name of the site for the sensor.
siteId Long The identifier for the sensor’s site.
staleTimeMS Integer The time (in epoch) when the Sensor was classified as Stale.
staticAnalysisDetectMode Enum
 
The value for the Artificial Intelligence Detect mode in the Anti-Malware settings. Possible values include:
 
    DISABLED
    CAUTIOUS
    MODERATE
    AGGRESSIVE
    SET_BY_POLICY
 
staticAnalysisDetectModeOrigin Enum
 
The source of the value for the Artificial Intelligence Detect mode setting. Possible values include:
 
    NOT_AVAILBLE
    SET_BY_POLICY
    SET_MANUALLY
    AWAITING_UPDATE
 
staticAnalysisPreventMode Enum
 
The value for the Artificial Intelligence Prevent Mode in the Anti-Malware settings. Possible values include:
 
    DISABLED
    CAUTIOUS
    MODERATE
    AGGRESSIVE
 
staticAnalysisPreventModeOrigin Enum
 
The source of the value for the Artificial Intelligence Prevent mode setting. Possible values include:
 
    NOT_AVAILBLE
    SET_BY_POLICY
    SET_MANUALLY
    AWAITING_UPDATE
 
status Enum
 
The status of the sensor. Possible values include:
 
    Online
    Offline
    Stale
    Archived
 
statusTimeMS Timestamp The last time (in epoch) when the sensor sent a status.
upTime Long The time the sensors have been in the UP state.
usbStatus Enum
 
The status of the Device Control feature. Possible values include:
 
    ENABLED: the Cybereason platform blocks access to all USB devices
    DISABLED: the Cybereason platform allows access to all USB devices
 
This field returns a value only if you have enabled Endpoint Controls.
 
This field is applicable for versions 19.2 and higher.
version String The sensor version number.
 
.EXAMPLE
Set-CybereasonCustomDetectionRule -RuleID 1580246401162 -Name 'Test Rule 1' -FacetName 'maliciousUseOfRegsvr32ModuleEvidence' -ChildFacetName name -RootCause self
 
 
.NOTES
Author: Robert H. Osborne
Alias: tobor
Contact: rosborne@osbornepro.com
 
 
.INPUTS
None
 
 
.OUTPUTS
None
 
.LINK
https://nest.cybereason.com/documentation/api-documentation/all-versions/query-sensors#getsensors
https://roberthsoborne.com
https://writeups.osbornepro.com
https://btps-secpack.com
https://github.com/tobor88
https://gitlab.com/tobor88
https://www.powershellgallery.com/profiles/tobor
https://www.linkedin.com/in/roberthosborne/
https://www.credly.com/users/roberthosborne/badges
https://www.hackthebox.eu/profile/52286
#>

Function Get-CybereasonListAllSensor {
    [CmdletBinding()]
        param(
            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the number of sensors to which to send the request (1-1000).`n[E] EXAMPLE: 100")]  # End Parameter
            [Int32]$Limit,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False)]  # End Parameter
            [ValidateRange(0,1000)]
            [Int32]$Offset = 0,

            [Parameter(
                Mandatory=$False,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define the sort order as Ascending or Descending.`n[E] EXAMPLE: ASC")]  # End Parameter
            [ValidateSet("ASC","DESC")]
            [String]$Sort = "DESC",

            [Parameter(
                Mandatory=$True,
                ValueFromPipeline=$False,
                HelpMessage="`n[H] Define a field name to filter by. Use a : to separate the value. Use the command 'Get-Help Get-CybereasonListAllSensors -Parameter Filter' to view the possible Value options for each field name`n[E] EXAMPLE: 'machineName:server01', 'usbStatus:Enum'")]  # End Parameter
            [ValidateSet("actionsInProgress:<int>","amStatus:AM_INSTALLED","amStatus:AM_UNINSTALLED","antiExploitStatus:ENABLED","antiExploitStatus:DISABLED","antiMalwareStatus:AM_DETECT_DISINFECT","antiMalwareStatus:AM_DEFAULT","archiveTimeMs:<timestamp>","archiveOrUnarchiveComment:<string>","collectionComponents:DPI","collectionComponents:Metadata","collectionComponents:File events","collectionComponents:Registry events","collectionStatus:ENABLED","collectionStatus:DISABLED","collectionStatus:SUSPENDED","compliance:true","compliance:false","cpuUsage:<float>","criticalAsset:true","criticalAsset:false","customTags:<string>","deliveryTime:<timestamp>","department:<string DEPARTMENT sensor tag>","deviceType:<string DEVICE TYPE sensor tag>","disconnected:true","disconnected:false","disconnectionTime:<timestamp>","exitReason:<string reason the sensor stopped>","externalIpAddress:<string ipaddress>","firstSeenTime:<timestamp>","fullScanStatus","fqdn:<string FQDN of machine>","fwStatus:DISABLED","fwStatus:ENABLED","guid:<string>","lastStatusAction:<string>","lastUpgradeResult:None","lastUpgradeResult:Pending","lastUpgradeResult:InProgress","lastUpgradeResult:FailedSending","lastUpgradeResult:Primed","lastUpgradeResult:UnknownProbe","lastUpgradeResult:NotSupported","lastUpgradeResult:Disconnected","lastUpgradeResult:TimeoutSending","lastUpgradeResult:Failed","lastUpgradeResult:Succeeded","lastUpgradeResult:Timeout","lastUpgradeResult:InvalidState","lastUpgradeResult:UnauthorizedUser","lastUpgradeResult:partialResponse","lastUpgradeResult:ChunksRequired","lastUpgradeResult:Aborted","lastUpgradeResult:GettingChunks","lastUpgradeResult:ProbeRemoved","lastUpgradeResult:FailedSendingToServer","lastUpgradeResult:Started","lastUpgradeResult:SendingMsi","lastUpgradeResult:MsiSendFail","lastUpgradeResult:MsiFileCorrupted","lastUpgradeResult:AlreadyUpdated","lastUpgradeResult:NewerInstalled","lastUpgradeSteps:None","lastUpgradeSteps:Pending","lastUpgradeSteps:InProgress","lastUpgradeSteps:FailedSending","lastUpgradeSteps:Primed","lastUpgradeSteps:UnknownProbe","lastUpgradeSteps:NotSupported","lastUpgradeSteps:Disconnected","lastUpgradeSteps:TimeoutSending","lastUpgradeSteps:Failed","lastUpgradeSteps:Succeeded","lastUpgradeSteps:Timeout","lastUpgradeSteps:InvalidState","lastUpgradeSteps:UnauthorizedUser","lastUpgradeSteps:partialResponse","lastUpgradeSteps:ChunksRequired","lastUpgradeSteps:Aborted","lastUpgradeSteps:GettingChunks","lastUpgradeSteps:ProbeRemoved","lastUpgradeSteps:FailedSendingToServer","lastUpgradeSteps:Started","lastUpgradeSteps:SendingMsi","lastUpgradeSteps:MsiSendFail","lastUpgradeSteps:MsiFileCorrupted","lastUpgradeSteps:AlreadyUpdated","lastUpgradeSteps:NewerInstalled,","internalIpAddress:<ipaddress>","isolated:true","isolated:false","lastFullScheduleScanSuccessTime:<timestamp>","lastQuickScheduleScanSuccessTime:<timestamp>","lastPylumInfoMsgUpdateTime:<timestamp>","location:<string value of LOCATION sensor tag>","machineName:<string>","memoryUsage:<Long>","offlineTimeMS:<timestamp>","onlineTimeMS:<timestamp>","organization:<string>","osType:UNKNOWN_OS","osType:WINDOWS","osType:OSX","osType:LINUX","osVersionType:Windows_10","osVersionType:Windows_8_1","osVersionType:Windows_8","osVersionType:Windows_7","osVersionType:Windows_Vista","osVersionType:Windows_XP_Professional_x64_Edition","osVersionType:Windows_XP","osVersionType:Windows_2000","osVersionType:Windows_Server_2012_R2","osVersionType:Windows_Server_2012","osVersionType:Windows_Server_2008_R2","osVersionType:Windows_Server_2008","osVersionType:Windows_Server_2003_R2","osVersionType:Windows_Home_Server","osVersionType:Windows_Server_2003","osVersionType:Windows_Server_2016","osVersionType:Windows_Server_2019","osVersionType:Catalina_10_15","osVersionType:Mojave_10_14","osVersionType:High_Sierra_10_13","osVersionType:Sierra_10_12","osVersionType:El_Capitan_10_11","osVersionType:Yosemite_10_10","osVersionType:Maverick_10_9","osVersionType:Centos_Linux_6","osVersionType:Centos_Linux_7","osVersionType:Red_Hat_Enterprise_Linux_6","osVersionType:Red_Hat_Enterprise_Linux_7","osVersionType:Ubuntu_Linux_12","osVersionType:Ubuntu_Linux_14","osVersionType:Ubuntu_Linux_16","osVersionType:Ubuntu_Linux_17","osVersionType:Ubuntu_Linux_18","osVersionType:Oracle_Linux_6","osVersionType:Oracle_Linux_7","osVersionType:Suse_Linux_12","osVersionType:Amazon_Linux_2011__09","osVersionType:Amazon_Linux_2012__03","osVersionType:Amazon_Linux_2012__09","osVersionType:Amazon_Linux_2013__03","osVersionType:Amazon_Linux_2013__09","osVersionType:Amazon_Linux_2014__03","osVersionType:Amazon_Linux_2014__09","osVersionType:Amazon_Linux_2015__03","osVersionType:Amazon_Linux_2015__09","osVersionType:Amazon_Linux_2016__03","osVersionType:Amazon_Linux_2016__09","osVersionType:Amazon_Linux_2017__03","osVersionType:Debian_Linux_8","osVersionType:Debian_Linux_9","outdated:true","outdated:false","pendingActions:<array so it can be defined more than once>","policyId:<string>","policyName:<string>","powerShellStatus:PS_DISABLED","powerShellStatus:PS_ENABLED","powerShellStatus:PS_DEFAULT","preventionError:<string>","preventionStatus:ENABLE","preventionStatus:DISABLE","preventionStatus:UNINSTALL","preventionStatus:UNKNOWN","proxyAddress:<ipaddress>","pylumID:<string>","quickScanStatus","ransomwareStatus:UNKNOWN","ransomwareStatus:DISABLED","ransomwareStatus:DETECT_ONLY","ransomwareStatus:DETECT_AND_SUSPEND","ransomwareStatus:DETECT_SUSPEND_PREVENT","remoteShellStatus:AC_DISABLED","remoteShellStatus:AC_ENABLED","sensorId:<string>","sensorArchivedByUser:<string>","sensorLastUpdate:<timestamp>","serverId:<string>","serverName:<string>","serviceStatus:DISABLED","serviceStatus:DETECT","serviceStatus:PREVENT","serviceStatus:SET_BY_POLICY","siteName:<string>","siteId:<long>","staleTimeMS:<time in epoch>","staticAnalysisDetectMode:DISABLED","staticAnalysisDetectMode:CAUTIOUS","staticAnalysisDetectMode:MODERATE","staticAnalysisDetectMode:AGGRESSIVE","staticAnalysisDetectMode:SET_BY_POLICY","staticAnalysisDetectModeOrigin:NOT_AVAILBLE","staticAnalysisDetectModeOrigin:SET_BY_POLICY","staticAnalysisDetectModeOrigin:SET_MANUALLY","staticAnalysisDetectModeOrigin:AWAITING_UPDATE","staticAnalysisPreventMode:DISABLED","staticAnalysisPreventMode:CAUTIOUS","staticAnalysisPreventMode:MODERATE","staticAnalysisPreventMode:AGGRESSIVE","staticAnalysisPreventModeOrigin:NOT_AVAILBLE","staticAnalysisPreventModeOrigin:SET_BY_POLICY","staticAnalysisPreventModeOrigin:SET_MANUALLY","staticAnalysisPreventModeOrigin:AWAITING_UPDATE","status:Online","status:Offline","status:Stale","status:Archived","statusTimeMS:<timestamp>","upTime:<Long>","usbStatus:ENABLED","usbStatus:DISABLED","version:<string sensor version number>")]
            [String]$Filter

        )  # End param

    $Uri = 'https://' + $Server + ':' + $Port + '/rest/sensors/query'
    # '{"limit":' + $Limit + ',"offset":"' + $Offset + '","sortDirection":"' + $Sort + '","filters":[{"fieldName":filter_1_name,"operator":"Equals","values":[filter_1_value]}]})})'
    $JsonData = '{"limit":' + $Limit + ',"offset":' + $Offset + ',"sortDirection":"' + $Sort + '","filters":[{'
    $FieldName,$Values = $Filter.Split(":")
    $Value = $Values.Split(",").Trim()
    $JsonData = $JsonData + "`"fieldName`":`"$FieldName`",`"operator`":`"Equals`",`"values`":[`"$Value`"]}]})"

    Write-Verbose "Sending query to $Uri"
    $Response = Invoke-WebRequest -Method POST -ContentType 'application/json' -Uri $Uri -WebSession $CybereasonSession -Body $JsonData

    $Response.Content | ConvertFrom-Json | Select-Object -ExpandProperty sensors | `
            ForEach-Object {
                $SensorId = ($_.sensorId | Out-String).Trim()
                $pylumId = ($_.pylumId | Out-String).Trim()
                $guid = ($_.guid | Out-String).Trim()
                $fqdn = ($_.fqdn | Out-String).Trim()
                $machineName = ($_.machineName | Out-String).Trim()
                $internalIpAddress = ($_.internalIpAddress | Out-String).Trim()
                $externalIpAddress = ($_.externalIpAddress | Out-String).Trim()
                $siteName = ($_.siteName | Out-String).Trim()
                $siteId = ($_.siteId | Out-String).Trim()
                $ransomwareStatus = ($_.ransomwareStatus | Out-String).Trim()
                $preventionStatus = $_.preventionStatus
                $isolated = ($_.isolated | Out-String).Trim()
                $disconnectionTime = Get-Date -Date ($_.disconnectionTime)
                $lastPylumInfoMsgUpdateTime = Get-Date -Date ($_.lastPylumInfoMsgUpdateTime)
                $status = ($_.status | Out-String).Trim()
                $onlineTimeMS = Get-Date -Date ($_.onlineTimeMS)
                $offlineTimeMS = Get-Date -Date ($_.offlineTimeMS)
                $staleTimeMS = Get-Date -Date ($_.staleTimeMS)
                $archiveTimeMs = Get-Date -Date ($_.archiveTimeMs)
                $statusTimeMS = Get-Date -Date ($_.statusTimeMS)
                $lastStatusAction = ($_.lastStatusAction | Out-String).Trim()
                $archivedOrUnarchiveComment = ($_.archivedOrUnarchiveComment | Out-String).Trim()
                $sensorArchivedByUser = ($_.sensorArchivedByUser | Out-String).Trim()
                $serverName = ($_.serverName | Out-String).Trim()
                $serverId = ($_.serverId | Out-String).Trim()
                $osType = ($_.osType | Out-String).Trim()
                $osVersionType = ($_.osVersionType | Out-String).Trim()
                $collectionStatus = ($_.collectionStatus | Out-String).Trim()
                $version = ($_.version | Out-String).Trim()
                $firstSeenTime = Get-Date -Date ($_.firstSeenTime)
                $upTime = Get-Date -Date ($_.upTime)
                $cpuUsage = ($_.cpuUsage | Out-String).Trim()
                $memoryUsage = ($_.memoryUsage | Out-String).Trim()
                $outdated = ($_.outdated | Out-String).Trim()
                $amStatus = ($_.amStatus | Out-String).Trim()
                $powerShellStatus = ($_.powerShellStatus | Out-String).Trim()
                $antiMalwareStatus = ($_.antiMalwareStatus | Out-String).Trim()
                $organization = ($_.organization | Out-String).Trim()
                $proxyAddress = ($_.proxyAddress | Out-String).Trim()
                $preventionError = ($_.preventionError | Out-String).Trim()
                $exitReason = ($_.exitReason | Out-String).Trim()
                $actionsInProgress = ($_.actionsInProgress | Out-String).Trim()
                $pendingActions = ($_.pendingActions | Out-String).Trim()
                $lastUpgradeResult = ($_.lastUpgradeResult | Out-String).Trim()
                $lastUpgradeSteps = ($_.lastUpgradeSteps | Out-String).Trim()
                $disconnected = ($_.disconnected | Out-String).Trim()
                $sensorLastUpdate = Get-Date -Date ($_.sensorLastUpdate)
                $fullScanStatus = ($_.fullScanStatus | Out-String).Trim()
                $quickScanStatus = ($_.quickScanStatus | Out-String).Trim()
                $lastFullScheduleScanSuccessTime = Get-Date -Date ($_.lastFullScheduleScanSuccessTime)
                $lastQuickScheduleScanSuccessTime = Get-Date -Date ($_.lastQuickScheduleScanSuccessTime)

                $Obj += New-Object -TypeName PSObject -Property @{sensorId=$sensorId; pylumId=$pylumId; guid=$guid; fqdn=$fqdn; machineName=$machineName; internalIpAddress=$internalIpAddress; externalIpAddress=$externalIpAddress; siteName=$siteName;siteId=$siteId;ransomwareStatus=$ransomwareStatus;preventionStatus=$preventionStatus;isolated=$isolated;disconnectionTime=$disconnectionTime;lastPylumInfoMsgUpdateTime=$lastPylumInfoMsgUpdateTime;status=$status;onlineTimeMS=$onlineTimeMS;offlineTimeMS=$offlineTimeMS;staleTimeMS=$staleTimeMS;archiveTimeMs=$archiveTimeMs;statusTimeMS=$statusTimeMS;lastStatusAction=$lastStatusAction;archivedOrUnarchiveComment=$archivedOrUnarchiveComment;sensorArchivedByUser=$sensorArchivedByUser;serverName=$serverName;serverId=$serverId;osType=$osType;osVersionType=$osVersionType;collectionStatus=$collectionStatus;version=$version;firstSeenTime=$firstSeenTime;upTime=$upTime;cpuUsage=$cpuUsage;memoryUsage=$memoryUsage;outdated=$outdated;amStatus=$amStatus;powerShellStatus=$powerShellStatus;antiMalwareStatus=$antiMalwareStatus;organization=$organization;proxyAddress=$proxyAddress;preventionError=$preventionError;exitReason=$exitReason;actionsInProgress=$actionsInProgress;pendingActions=$pendingActions;lastUpgradeResult=$lastUpgradeResult;lastUpgradeSteps=$lastUpgradeSteps;disconnected=$disconnected;sensorLastUpdate=$sensorLastUpdate;fullScanStatus=$fullScanStatus;quickScanStatus=$quickScanStatus;lastFullScheduleScanSuccessTime=$lastFullScheduleScanSuccessTime;lastQuickScheduleScanSuccessTime=$lastQuickScheduleScanSuccessTime}  # End Properties

            }  # End ForEach-Object

            $Obj

}  # End Function Get-CybereasonListAllSensor

# SIG # Begin signature block
# MIIM9AYJKoZIhvcNAQcCoIIM5TCCDOECAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUS8RwNpeOYsaQNRqHHbv/coba
# yVKgggn7MIIE0DCCA7igAwIBAgIBBzANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UE
# BhMCVVMxEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAY
# BgNVBAoTEUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290
# IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTExMDUwMzA3MDAwMFoXDTMx
# MDUwMzA3MDAwMFowgbQxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMw
# EQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjEt
# MCsGA1UECxMkaHR0cDovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkvMTMw
# MQYDVQQDEypHbyBEYWRkeSBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IC0g
# RzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC54MsQ1K92vdSTYusw
# ZLiBCGzDBNliF44v/z5lz4/OYuY8UhzaFkVLVat4a2ODYpDOD2lsmcgaFItMzEUz
# 6ojcnqOvK/6AYZ15V8TPLvQ/MDxdR/yaFrzDN5ZBUY4RS1T4KL7QjL7wMDge87Am
# +GZHY23ecSZHjzhHU9FGHbTj3ADqRay9vHHZqm8A29vNMDp5T19MR/gd71vCxJ1g
# O7GyQ5HYpDNO6rPWJ0+tJYqlxvTV0KaudAVkV4i1RFXULSo6Pvi4vekyCgKUZMQW
# OlDxSq7neTOvDCAHf+jfBDnCaQJsY1L6d8EbyHSHyLmTGFBUNUtpTrw700kuH9zB
# 0lL7AgMBAAGjggEaMIIBFjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
# BjAdBgNVHQ4EFgQUQMK9J47MNIMwojPX+2yz8LQsgM4wHwYDVR0jBBgwFoAUOpqF
# BxBnKLbv9r0FQW4gwZTaD94wNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhho
# dHRwOi8vb2NzcC5nb2RhZGR5LmNvbS8wNQYDVR0fBC4wLDAqoCigJoYkaHR0cDov
# L2NybC5nb2RhZGR5LmNvbS9nZHJvb3QtZzIuY3JsMEYGA1UdIAQ/MD0wOwYEVR0g
# ADAzMDEGCCsGAQUFBwIBFiVodHRwczovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9z
# aXRvcnkvMA0GCSqGSIb3DQEBCwUAA4IBAQAIfmyTEMg4uJapkEv/oV9PBO9sPpyI
# BslQj6Zz91cxG7685C/b+LrTW+C05+Z5Yg4MotdqY3MxtfWoSKQ7CC2iXZDXtHwl
# TxFWMMS2RJ17LJ3lXubvDGGqv+QqG+6EnriDfcFDzkSnE3ANkR/0yBOtg2DZ2HKo
# cyQetawiDsoXiWJYRBuriSUBAA/NxBti21G00w9RKpv0vHP8ds42pM3Z2Czqrpv1
# KrKQ0U11GIo/ikGQI31bS/6kA1ibRrLDYGCD+H1QQc7CoZDDu+8CL9IVVO5EFdkK
# rqeKM+2xLXY2JtwE65/3YR8V3Idv7kaWKK2hJn0KCacuBKONvPi8BDABMIIFIzCC
# BAugAwIBAgIIXIhNoAmmSAYwDQYJKoZIhvcNAQELBQAwgbQxCzAJBgNVBAYTAlVT
# MRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQK
# ExFHb0RhZGR5LmNvbSwgSW5jLjEtMCsGA1UECxMkaHR0cDovL2NlcnRzLmdvZGFk
# ZHkuY29tL3JlcG9zaXRvcnkvMTMwMQYDVQQDEypHbyBEYWRkeSBTZWN1cmUgQ2Vy
# dGlmaWNhdGUgQXV0aG9yaXR5IC0gRzIwHhcNMjAxMTE1MjMyMDI5WhcNMjExMTA0
# MTkzNjM2WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMIQ29sb3JhZG8xGTAXBgNV
# BAcTEENvbG9yYWRvIFNwcmluZ3MxEzARBgNVBAoTCk9zYm9ybmVQcm8xEzARBgNV
# BAMTCk9zYm9ybmVQcm8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDJ
# V6Cvuf47D4iFITUSNj0ucZk+BfmrRG7XVOOiY9o7qJgaAN88SBSY45rpZtGnEVAY
# Avj6coNuAqLa8k7+Im72TkMpoLAK0FZtrg6PTfJgi2pFWP+UrTaorLZnG3oIhzNG
# Bt5oqBEy+BsVoUfA8/aFey3FedKuD1CeTKrghedqvGB+wGefMyT/+jaC99ezqGqs
# SoXXCBeH6wJahstM5WAddUOylTkTEfyfsqWfMsgWbVn3VokIqpL6rE6YCtNROkZq
# fCLZ7MJb5hQEl191qYc5VlMKuWlQWGrgVvEIE/8lgJAMwVPDwLNcFnB+zyKb+ULu
# rWG3gGaKUk1Z5fK6YQ+BAgMBAAGjggGFMIIBgTAMBgNVHRMBAf8EAjAAMBMGA1Ud
# JQQMMAoGCCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIHgDA1BgNVHR8ELjAsMCqgKKAm
# hiRodHRwOi8vY3JsLmdvZGFkZHkuY29tL2dkaWcyczUtNi5jcmwwXQYDVR0gBFYw
# VDBIBgtghkgBhv1tAQcXAjA5MDcGCCsGAQUFBwIBFitodHRwOi8vY2VydGlmaWNh
# dGVzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkvMAgGBmeBDAEEATB2BggrBgEFBQcB
# AQRqMGgwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmdvZGFkZHkuY29tLzBABggr
# BgEFBQcwAoY0aHR0cDovL2NlcnRpZmljYXRlcy5nb2RhZGR5LmNvbS9yZXBvc2l0
# b3J5L2dkaWcyLmNydDAfBgNVHSMEGDAWgBRAwr0njsw0gzCiM9f7bLPwtCyAzjAd
# BgNVHQ4EFgQUkWYB7pDl3xX+PlMK1XO7rUHjbrwwDQYJKoZIhvcNAQELBQADggEB
# AFSsN3fgaGGCi6m8GuaIrJayKZeEpeIK1VHJyoa33eFUY+0vHaASnH3J/jVHW4BF
# U3bgFR/H/4B0XbYPlB1f4TYrYh0Ig9goYHK30LiWf+qXaX3WY9mOV3rM6Q/JfPpf
# x55uU9T4yeY8g3KyA7Y7PmH+ZRgcQqDOZ5IAwKgknYoH25mCZwoZ7z/oJESAstPL
# vImVrSkCPHKQxZy/tdM9liOYB5R2o/EgOD5OH3B/GzwmyFG3CqrqI2L4btQKKhm+
# CPrue5oXv2theaUOd+IYJW9LA3gvP/zVQhlOQ/IbDRt7BibQp0uWjYaMAOaEKxZN
# IksPKEJ8AxAHIvr+3P8R17UxggJjMIICXwIBATCBwTCBtDELMAkGA1UEBhMCVVMx
# EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT
# EUdvRGFkZHkuY29tLCBJbmMuMS0wKwYDVQQLEyRodHRwOi8vY2VydHMuZ29kYWRk
# eS5jb20vcmVwb3NpdG9yeS8xMzAxBgNVBAMTKkdvIERhZGR5IFNlY3VyZSBDZXJ0
# aWZpY2F0ZSBBdXRob3JpdHkgLSBHMgIIXIhNoAmmSAYwCQYFKw4DAhoFAKB4MBgG
# CisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcC
# AQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYE
# FFpiP2kwPC7KDwEe/mViwiGu9cfnMA0GCSqGSIb3DQEBAQUABIIBABnjwRoda2z5
# N6uAtUBsrfvoLz0/U8wBUaBHVSFfYR8r/9lvHy4FdotZI8rlHAqO79mtcjwuWb3m
# FYnwzKtPeTn6XNne6hU7982FDVP61KovdJ3juIXGOPt8OZvRZcUMp70LkWSxeJ7X
# 7TbmZJ9oqTLcQFYqhOoVP6NpKnPiMAC3i6JQjdoXnmmnlynwf1r4ich/wy//jwAE
# 1iVAJjAWboD+LEzXmgUDJ1cSGXcUnQsjILWcyG8b0XFKTL9W8g2N1PVd5w8zORzq
# 72x0HFCHMD8wF5whLhG2ld9MTSeF1T838LR7SVvdxZuHNbDAVHtSo8T8saT+ewd6
# PZ6l8Ciz7aY=
# SIG # End signature block