ORCA.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
#Requires -Version 5.1

<#
    .SYNOPSIS
        The Office 365 Recommended Configuration Analyzer (ORCA)
 
    .DESCRIPTION
        
 
    .NOTES
        Cam Murray
        Field Engineer - Microsoft
        camurray@microsoft.com
 
        Output report uses open source components for HTML formatting
        - bootstrap - MIT License - https://getbootstrap.com/docs/4.0/about/license/
        - fontawesome - CC BY 4.0 License - https://fontawesome.com/license/free
         
        ############################################################################
 
        This sample script is not supported under any Microsoft standard support program or service.
        This sample script is provided AS IS without warranty of any kind.
        Microsoft further disclaims all implied warranties including, without limitation, any implied
        warranties of merchantability or of fitness for a particular purpose. The entire risk arising
        out of the use or performance of the sample script and documentation remains with you. In no
        event shall Microsoft, its authors, or anyone else involved in the creation, production, or
        delivery of the scripts be liable for any damages whatsoever (including, without limitation,
        damages for loss of business profits, business interruption, loss of business information,
        or other pecuniary loss) arising out of the use of or inability to use the sample script or
        documentation, even if Microsoft has been advised of the possibility of such damages.
 
        ############################################################################
 
    .LINK
        about_functions_advanced
 
#>


function Get-ORCADirectory
{
    <#
        Gets or creates the ORCA directory in AppData
    #>


    $Directory = "$($env:LOCALAPPDATA)\Microsoft\ORCA"

    If(Test-Path $Directory) 
    {
        Return $Directory
    }
    else 
    {
        mkdir $Directory | out-null
        Return $Directory
    }

}

<#
 
    Check modules
 
#>


function Invoke-CheckAllowedSenderDomains {
    Param(
        $ContentFilterPolicies
    )

    $Check = "Content Filter AllowedSenderDomains"
    $CID = "118-1"

    $return = @()

    ForEach($Policy in $ContentFilterPolicies) {

        # Fail if AllowedSenderDomains is not null

        If(($Policy.AllowedSenderDomains).Count -gt 0) {
            ForEach($Domain in $Policy.AllowedSenderDomains) {
                $return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    ConfigItem=$($Policy.Name)
                    ConfigData="$($Domain.Domain)"
                    Rule="AllowedSenderDomains is not empty"
                    Control=$CID
                } 
            }
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData="0 Allowed Sender Domains"
                Rule="AllowedSenderDomains is empty"
                Control=$CID
            } 
        }
    }

    return $return        
}

function Invoke-CheckZAP {
    Param(
        $MalwareFilterPolicies,
        $ContentFilterPolicies
    )

    $Check = "ZAP"

    $return = @()

    ForEach($Policy in $MalwareFilterPolicies) {

        if($Policy.ZapEnabled -eq $true) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.ZapEnabled
                Rule="ZAP Malware Enabled"
                Control="120-malware"
            } 
        } else {
            $return +=  New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.ZapEnabled
                Control="120-malware"
                SupplementText="Zero Hour Autopurge for Malware is disabled in the Malware Policy $($Policy.Name)"
            }
        }
    }

    ForEach($Policy in $ContentFilterPolicies) {
        if($Policy.SpamZapEnabled -eq $true) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.SpamZapEnabled)
                Rule="ZAP Spam Enabled"
                Control="120-spam"
            } 
        } else {
            $return +=  New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.SpamZapEnabled)
                Rule="ZAP Spam Disabled"
                Control="120-spam"
            }
        }
        if($Policy.PhishZapEnabled -eq $true) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishZapEnabled)
                Rule="ZAP Phish Enabled"
                Control="120-phish"
            } 
        } else {
            $return +=  New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishZapEnabled)
                Rule="ZAP Phish Disabled"
                Control="120-phish"
            }
        }
        # Check requirement of Spam ZAP - MoveToJmf, redirect, delete, quarantine
        If($Policy.SpamAction -eq "MoveToJmf" -or $Policy.SpamAction -eq "Redirect" -or $Policy.SpamAction -eq "Delete" -or $Policy.SpamAction -eq "Quarantine") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="SpamAction"
                ConfigData=($Policy.SpamAction)
                Rule="SpamAction set to an action necessary to move to JMF- ZAP Requirement"
                Control="121"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="SpamAction"
                ConfigData=$($Policy.SpamAction)
                SupplementText="Spam Action on policy $($Policy.Name) is set to $($Policy.SpamAction)"
                Control="121"
            }             
        }
        # Check requirement of Phish ZAP - MoveToJmf, redirect, delete, quarantine
        If($Policy.PhishSpamAction -eq "MoveToJmf" -or $Policy.PhishSpamAction -eq "Redirect" -or $Policy.PhishSpamAction -eq "Delete" -or $Policy.PhishSpamAction -eq "Quarantine") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="PhishSpamAction"
                ConfigData=$($Policy.PhishSpamAction)
                Rule="PhishSpamAction set to an action necessary to move to JMF - ZAP Requirement"
                Control="121"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="PhishSpamAction"
                ConfigData=$($Policy.PhishSpamAction)
                Rule="PhishSpamAction not set to an action necessary to move to JMF- ZAP Requirement"
                Control="121"
            }           
        }

    }

    return $return
}

function Invoke-CheckIPAllowList {
    Param(
        $HostedConnectionFilterPolicies
    )

    $Check = "IP Allow List Size"
    $Return = @()

    ForEach($HostedConnectionFilterPolicy in $HostedConnectionFilterPolicies) {
        # Check if IPAllowList < 0 and return inconclusive for manual checking of size
        If($HostedConnectionFilterPolicy.IPAllowList.Count -gt 0) {
            # IP Allow list present
            ForEach($IPAddr in @($HostedConnectionFilterPolicy.IPAllowList)) {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    ConfigItem=$($HostedConnectionFilterPolicy.Name)
                    ConfigData=$IPAddr
                    Rule="IP Allow List contains too many IPs"
                    Control="114"
                }    
            }

        } else {
            # IPAllowList is blank, so pass.
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($HostedConnectionFilterPolicy.Name)
                ConfigData="IP Entries $($HostedConnectionFilterPolicy.IPAllowList.Count)"
                Rule="IP Allow List empty"
                Control="114"
            }
        }
    }

    return $Return
}

function Invoke-CheckATPForSPOTeamsODB {
    <#
     
    158
 
    Checks to determine if ATP is enabled for SharePoint, Teams, and OD4B as per 'tickbox' in
    the ATP configuration.
     
    #>

    Param(
        $ATPPolicy,
        $Questions
    )

    $Check = "ATP"
    $Cid = "158"
    
    $Return = @()

        ForEach($Policy in $ATPPolicy) {
        # Determine if ATP is enabled or not
        If($Policy.EnableATPForSPOTeamsODB -eq $true) {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy["EnableATPForSPOTeamsODB"])
                Rule="ATP enabled for SPO - OD4B - Teams"
                Control=$Cid
            }
        } else {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy["EnableATPForSPOTeamsODB"])
                Rule="ATP enabled for SPO - OD4B - Teams"
                Control=$Cid
            }
        }
    }

    Return $Return
}

function Invoke-CheckContentFilterActions {
    Param(
        $ContentFilterPolicies
    )

    $Check = "Content Filter Actions"

    $return = @()

    ForEach($Policy in $ContentFilterPolicies) {

        # Fail if HighConfidenceSpamAction is not set to Quarantine

        If($Policy.HighConfidenceSpamAction -ne "Quarantine") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.HighConfidenceSpamAction)
                Rule="HighConfidenceSpamAction set to $($Policy.HighConfidenceSpamAction)"
                Control="140"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.HighConfidenceSpamAction)
                Rule="HighConfidenceSpamAction set to $($Policy.HighConfidenceSpamAction)"
                Control="140"
            } 
        }

        # Fail if SpamAction is not set to MoveToJmf

        If($Policy.SpamAction -ne "MoveToJmf") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.SpamAction)
                Rule="SpamAction set to $($Policy.SpamAction)"
                Control="139"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.SpamAction)
                Rule="SpamAction set to $($Policy.SpamAction)"
                Control="139"
            } 
        }

        # Fail if BulkSpamAction is not set to MoveToJmf

        If($Policy.BulkSpamAction -ne "MoveToJmf") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.BulkSpamAction)
                Rule="BulkSpamAction set to $($Policy.BulkSpamAction)"
                Control="141"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.BulkSpamAction)
                Rule="BulkSpamAction set to $($Policy.BulkSpamAction)"
                Control="141"
            } 
        }

        # Fail if PhishSpamAction is not set to Quarantine

        If($Policy.PhishSpamAction -ne "Quarantine") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishSpamAction)
                Rule="PhishSpamAction set to $($Policy.PhishSpamAction)"
                Control="142"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishSpamAction)
                Rule="PhishSpamAction set to $($Policy.PhishSpamAction)"
                Control="142"
            } 
        }

        # Fail if HighConfidencePhishAction is not set to Quarantine

        If($Policy.HighConfidencePhishAction -ne "Quarantine") {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.HighConfidencePhishAction)
                Rule="PhishSpamAction set to $($Policy.PhishSpamAction)"
                Control="ORCA-104"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.HighConfidencePhishAction)
                Rule="PhishSpamAction set to $($Policy.PhishSpamAction)"
                Control="ORCA-104"
            } 
        }
        
    }

    return $return        
}

function Invoke-CheckATPSafeLinksTrackingInternal 
{
    <#
     
    179
 
    Checks to determine if SafeLinks is re-wring internal to internal emails. Does not however,
    check to determine if there is a rule enforcing this.
     
    #>

    Param(
        $ATPPolicy
    )

    $Check = "ATP"
    $Cid = "179"
    
    $Return = @()

    # Determine if ATP license

    ForEach($Policy in $ATPPolicy) 
    {
        # Determine if ATP link tracking is on for this safelinks policy
        If($Policy.EnableForInternalSenders -eq $true) 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.EnableForInternalSenders
                Rule="SafeLinks Enabled for Internal Senders"
                Control=$Cid
            }
        } 
        Else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.EnableForInternalSenders
                Rule="SafeLinks Disabled for Internal Senders"
                Control=$Cid
            }
        }
    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            ConfigItem="All"
            ConfigData="Enabled False"
            Control=$Cid
        }
    }

    Return $Return
}

function Invoke-CheckATPSafeLinksDeliverMessageAfterScan
{
    <#
     
    ORCA-105
 
    Checks to determine if SafeLinks setting: wait for URL scanning to complete before delivering the message is enabled. Does not however,
    check to determine if there is a rule enforcing this.
     
    #>

    Param
    (
        $ATPPolicy
    )

    $Check = "ATP"
    $Cid = "ORCA-105"
    
    $Return = @()
    
    ForEach($Policy in ($ATPPolicy | Where-Object {$_.IsEnabled -eq $True})) 
    {
        # Determine if DeliverMessageAfterScan is on for this safelinks policy
        If($Policy.DeliverMessageAfterScan -eq $true) 
        {
            $DeliverMessageAfterScan_Result = "Pass"
        }
        Else
        {
            $DeliverMessageAfterScan_Result = "Fail"
        }

        If($Policy.ScanUrls -eq $true)
        {
            $ScanURLs_Result = "Pass"
        }
        Else 
        {
            $ScanURLs_Result = "Fail"
        }

        $Return += New-Object -TypeName psobject -Property @{
            Result=$DeliverMessageAfterScan_Result
            Check=$Check
            Object=$($Policy.Name)
            ConfigItem="DeliverMessageAfterScan"
            ConfigData="$($Policy.DeliverMessageAfterScan)"
            Control=$Cid
        }

        $Return += New-Object -TypeName psobject -Property @{
            Result=$ScanURLs_Result
            Check=$Check
            Object=$($Policy.Name)
            ConfigItem="ScanUrls"
            ConfigData="$($Policy.ScanUrls)"
            Control=$Cid
        }    
    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Control=$Cid
        } 
    }

    Return $Return
}

function Invoke-CheckATPSafeLinksTrackingOfficeApps {
    <#
     
    169
 
    Determines if ATP SafeLinks protection extends to Office Apps in each policy,
    Does not however determine if SafeLinks policy extends to all users.
     
    #>


    Param(
        $ATPPolicy
    )

    $Check = "ATP"
    $Cid = "169"
    
    $Return = @()

    If($ATPPolicy.EnableSafeLinksForClients -eq $true)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            ConfigItem="365 ATP Policy EnableSafeLinksForClients"
            ConfigData=$ATPPolicy.EnableSafeLinksForClients
            Rule="SafeLinks URL Tracking Enabled for Office Clients"
            Control=$Cid
        }
    } 
    Else 
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            ConfigItem="365 ATP Policy EnableSafeLinksForClients"
            ConfigData=$ATPPolicy.EnableSafeLinksForClients
            Rule="SafeLinks URL Tracking Enabled for Office Clients"
            Control=$Cid
        }
    }

    Return $Return
}

function Invoke-CheckATPSafeAttachmentsBypass {
<#
 
    189
     
    Checks to determine if SafeAttachments is being bypassed by injecting X-MS-Exchange-Organization-SkipSafeAttachmentProcessing
    header in to emails using a mail flow rule.
 
#>

    Param(
        $TransportRules
    )

    $Check = "ATP"
    $Cid = "189"
    
    $Return = @()

    $BypassRules = @($TransportRules | Where-Object {$_.SetHeaderName -eq "X-MS-Exchange-Organization-SkipSafeAttachmentProcessing"})
    
    If($BypassRules.Count -gt 0) 
    {
        # Rules exist to bypass
        ForEach($Rule in $BypassRules) 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem="Transport Rule - $($Rule.Name)"
                ConfigData="Setting X-MS-Exchange-Organization-SkipSafeAttachmentProcessing to $($Rule.SetHeaderValue)"
                Rule="SafeAttachments not bypassed"
                Control=$Cid
            }
        }
    } 
    Else 
    {
        # Rules do not exist to bypass
        $Return += New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            ConfigItem="Transport Rules"
            Rule="SafeAttachments not bypassed"
            Control=$Cid
        }
    }

    Return $Return
}

function Invoke-CheckATPSafeLinksTracking {
    <#
     
    156
 
    Determines if SafeLinks URL tracing is enabled on the default policy for Office apps or in a Policy, does not however check
    that there is a rule enforcing this policy.
     
    #>

    Param(
        $SafeLinksPolicies,
        $ATPPolicy
    )

    $Check = "ATP"
    $Cid = "156"
    
    $Return = @()

    If($AtpPolicy.TrackClicks -eq $False -and $($AtpPolicy.EnableSafeLinksForClients -eq $True -or $AtpPolicy.EnableSafeLinksForWebAccessCompanion -eq $True -or $AtpPolicy.EnableSafeLinksForO365Clients -eq $True))
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object=$($AtpPolicy.Name)
            ConfigItem="TrackClicks"
            ConfigData=$($AtpPolicy.TrackClicks)
            Rule="TrackClicks off and EnableSafeLinksForClients or EnableSafeLinksForWebAccessCompanion or EnableSafeLinksForO365Clients enabled"
            Control=$Cid
        }
    }
    ElseIf ($AtpPolicy.TrackClicks -eq $True)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            Object=$($AtpPolicy.Name)
            ConfigItem="TrackClicks"
            ConfigData=$($AtpPolicy.TrackClicks)
            Rule="TrackClicks in Office 365 Apps, Office for iOS and Android in ATP Policy"
            Control=$Cid
        }            
    }

    ForEach($Policy in $SafeLinksPolicies) 
    {
        # Determine if ATP link tracking is on for this safelinks policy
        If($Policy.DoNotTrackUserClicks -eq $false) {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="DoNotTrackUserClicks"
                ConfigData=$($Policy.DoNotTrackUserClicks)
                Rule="SafeLinks URL Tracking Enabled"
                Control=$Cid
            }
        } 
        else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="DoNotTrackUserClicks"
                ConfigData=$($Policy.DoNotTrackUserClicks)
                Rule="SafeLinks URL Tracking Enabled"
                Control=$Cid
            }
        }
    }

    Return $Return
}

function Invoke-CheckContentFilterSafetyTips {
    Param(
        $ContentFilterPolicies
    )

    $Check = "Content Filter Safety Tips"
    $CID = "143"

    $return = @()

    ForEach($Policy in $ContentFilterPolicies) {

        # Fail if InlineSafetyTipsEnabled is not set to true

        If($Policy.InlineSafetyTipsEnabled -eq $false) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.InlineSafetyTipsEnabled)
                Rule="InlineSafetyTipsEnabled is false - Safety Tips Disabled"
                Control=$CID
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.InlineSafetyTipsEnabled)
                Rule="InlineSafetyTipsEnabled is true - Safety Tips Enabled"
                Control=$CID
            } 
        }
    }

    return $return        
}

function Invoke-CheckAntiPhishPolicy 
{
    Param
    (
        $AntiPhishPolicy
    )

    $Check = "Anti Phish Policy"
    $Return = @()

    ForEach($Policy in $AntiPhishPolicy) 
    {
        # Fail if Enabled or EnableAntiSpoofEnforcement is not set to true in any policy
        If(($Policy.Enabled -eq $true -and $Policy.EnableAntiSpoofEnforcement -eq $true) -or ($Policy.Identity -eq "Office365 AntiPhish Default" -and $Policy.EnableAntiSpoofEnforcement -eq $true))
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableAntiSpoofEnforcement"
                ConfigData=$Policy.EnableAntiSpoofEnforcement 
                Rule="Anti-spoof protection is enabled"
                Control="180"
            } 
        } 
    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Rule="Anti-spoof protection is not enabled"
            Control="180"
        } 
    }

    Return $return
}

function Invoke-CheckMalwareNotifications {
    Param(
        $MalwareFilterPolicies
    )

    $Check = "Malware Notifications"

    $return = @()

    ForEach($Policy in $MalwareFilterPolicies) {

        # Fail if EnableExternalSenderNotifications is set to true in the policy

        If($Policy.EnableExternalSenderNotifications -eq $true) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                Rule="EnableExternalSenderNotifications set to True"
                Control="125"
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                Rule="EnableExternalSenderNotifications set to False"
                Control="125"
            } 
        }
    }

    return $return
}

function Invoke-CheckCommonAttachmentTypeFilter {
    Param(
        $MalwareFilterPolicies
    )

    $Check = "Common Attachment Type Filter"
    $Control = "205"

    $return = @()

    ForEach($Policy in $MalwareFilterPolicies) {

        # Fail if NotifyOutboundSpam is not set to true in the policy

        If($Policy.EnableFileFilter -eq $false -or @($Policy.FileTypes).Count -eq 0) {
            $return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=""
                Rule="EnableFilterFilter eq false or FileType count is zero"
                Control=$Control
            } 
        } else {
            $return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData="EnableFileFilter $($Policy.EnableFileFilter) FileTypes Count $(($Policy.FileTypes).Count)"
                Rule="EnableFileFilter eq true and FileType count is greater than zero"
                Control=$Control
            } 
        }
    }

    return $return
}

function Invoke-CheckUnifiedLogging {
    Param(
        $AdminAuditLogConfig
    )

    $Check = "Unified Logging"
    $ConfigItem = "Admin Audit Log Settings"
    $CID="122"

    If($AdminAuditLogConfig.UnifiedAuditLogIngestionEnabled -eq $true) {

        # Unified audit logging turned on

        $return = New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            ConfigItem=$ConfigItem
            Rule="UnifiedAuditLogIngestionEnabled is true"
            Control=$CID
        } 

    } else {

        # Unified audit logging turned off

        $return = New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            ConfigItem=$ConfigItem
            Rule="UnifiedAuditLogIngestionEnabled is false"
            Control=$CID
        } 

    }

    return $return
}

Function Invoke-CheckTransportRuleSCL {
    Param(
        $TransportRules
    )

    $Check = "Transport Rule SCL"
    $CID = "118-2"

    $return = @()

    # Look through Transport Rule for an action SetSCL -1

    ForEach($TransportRule in $TransportRules) {
        If($TransportRule.SetSCL -eq "-1") {
            #Rules that apply to the sender domain
            #From Address notmatch is to include if just domain name is value
            If($TransportRule.SenderDomainIs -ne $null -or ($TransportRule.FromAddressContainsWords -ne $null -and $TransportRule.FromAddressContainsWords -notmatch ".+@") -or ($TransportRule.FromAddressMatchesPatterns -ne $null -and $TransportRule.FromAddressMatchesPatterns -notmatch ".+@")){
                #Look for condition that checks auth results header and its value
                If(($TransportRule.HeaderContainsMessageHeader -eq 'Authentication-Results' -and $TransportRule.HeaderContainsWords -ne $null) -or ($TransportRule.HeaderMatchesMessageHeader -like '*Authentication-Results*' -and $TransportRule.HeaderMatchesPatterns -ne $null)) {
                    # OK
                }
                #Look for exception that checks auth results header and its value
                elseif(($TransportRule.ExceptIfHeaderContainsMessageHeader -eq 'Authentication-Results' -and $TransportRule.ExceptIfHeaderContainsWords -ne $null) -or ($TransportRule.ExceptIfHeaderMatchesMessageHeader -like '*Authentication-Results*' -and $TransportRule.ExceptIfHeaderMatchesPatterns -ne $null)) {
                    # OK
                }
                elseif($TransportRule.SenderIpRanges -ne $null) {
                    # OK
                }
                #Look for condition that checks for any other header and its value
                else {
                    ForEach($RuleDomain in $($TransportRule.SenderDomainIs)) {
                        $return +=  New-Object -TypeName psobject -Property @{
                            Result="Fail"
                            Check=$Check
                            ConfigItem=$($TransportRule.Name)
                            ConfigData=$($RuleDomain)
                            Rule="SetSCL -1 action for sender domain but no check for auth results header, sender IP, or other header"
                            Control=$CID
                        }
                    }
                    ForEach($FromAddressContains in $($TransportRule.FromAddressContainsWords)) {
                        $return +=  New-Object -TypeName psobject -Property @{
                            Result="Fail"
                            Check=$Check
                            ConfigItem=$($TransportRule.Name)
                            ConfigData="Contains $($FromAddressContains)"
                            Rule="SetSCL -1 action for sender domain but no check for auth results header, sender IP, or other header"
                            Control=$CID
                        }
                    }
                    ForEach($FromAddressMatch in $($TransportRule.FromAddressMatchesPatterns)) {
                        $return +=  New-Object -TypeName psobject -Property @{
                            Result="Fail"
                            Check=$Check
                            ConfigItem=$($TransportRule.Name)
                            ConfigData="Matches $($FromAddressMatch)"
                            Rule="SetSCL -1 action for sender domain but no check for auth results header, sender IP, or other header"
                            Control=$CID
                        }
                    }

                }
            }
            #No sender domain restriction, so check for IP restriction
            elseif($null -ne $TransportRule.SenderIpRanges) {
                ForEach($SenderIpRange in $TransportRule.SenderIpRanges) {
                    $return +=  New-Object -TypeName psobject -Property @{
                        Result="Fail"
                        Check=$Check
                        ConfigItem=$($TransportRule.Name)
                        ConfigData=$SenderIpRange
                        Rule="SetSCL -1 action with IP condition but not limiting sender domain"
                        Control="114"
                    }
                }
            }
            #No sender restriction, so check for condition that checks auth results header and its value
            elseif(($TransportRule.HeaderContainsMessageHeader -eq 'Authentication-Results' -and $TransportRule.HeaderContainsWords -ne $null) -or ($TransportRule.HeaderMatchesMessageHeader -like '*Authentication-Results*' -and $TransportRule.HeaderMatchesPatterns -ne $null)) {
                # OK
            }
            #No sender restriction, so check for exception that checks auth results header and its value
            elseif(($TransportRule.ExceptIfHeaderContainsMessageHeader -eq 'Authentication-Results' -and $TransportRule.ExceptIfHeaderContainsWords -ne $null) -or ($TransportRule.ExceptIfHeaderMatchesMessageHeader -like '*Authentication-Results*' -and $TransportRule.ExceptIfHeaderMatchesPatterns -ne $null)) {
                # OK
            }
        }
    }
    # If no rules found with SetSCL -1, then pass.

    if(!$return) {
        $return +=  New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            ConfigItem="Transport Rules"
            Rule="No SetSCL -1 actions found"
            Control=$CID
        }  
    }

    return $return
}

function Invoke-CheckATPPhishThreshold
{
    <#
 
    Checks ATP Anti-phishing policy Advanced phishing thresholds
     
    #>

    Param(
        $AntiPhishPolicy
    )

    $Check = "ATP Phish Threshold"
    $Cid = "220"
    
    $Return = @()

    ForEach($Policy in $AntiPhishPolicy) {
        If($Policy.PhishThresholdLevel -eq 1 -or $Policy.PhishThresholdLevel -eq 4)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishThresholdLevel)
                Rule="PhishThreshold Level is 1"
                Control=$Cid
            }
        } 
        else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                ConfigItem=$($Policy.Name)
                ConfigData=$($Policy.PhishThresholdLevel)
                Rule="PhishThreshold Level 2 or higher"
                Control=$Cid
            }
        }
    }

    Return $Return
}

function Invoke-CheckATPPhishDomainImpAction
{
    Param(
        $AntiPhishPolicy
    )

    $Check = "ATP Phish Domain Impersonation"
    $Cid = "222"
    
    $Return = @()

    ForEach($Policy in ($AntiPhishPolicy | Where-Object {$_.Enabled -eq $True}))
    {

        If($Policy.EnableTargetedDomainsProtection -eq $False -and $Policy.EnableOrganizationDomainsProtection -eq $False)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableTargetedDomainsProtection"
                ConfigData=$($Policy.EnableTargetedDomainsProtection)
                Control=$Cid
            }
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableOrganizationDomainsProtection"
                ConfigData=$($Policy.EnableOrganizationDomainsProtection)
                Control=$Cid
            }           
        }

        If($Policy.EnableTargetedDomainsProtection -eq $True)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableTargetedDomainsProtection"
                ConfigData=$Policy.EnableTargetedDomainsProtection
                Control=$Cid
            }            
        }

        If($Policy.EnableOrganizationDomainsProtection -eq $True)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableOrganizationDomainsProtection"
                ConfigData=$Policy.EnableOrganizationDomainsProtection
                Control=$Cid
            }            
        }

        If($Policy.TargetedDomainProtectionAction -ne "Quarantine")
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="TargetedDomainProtectionAction"
                ConfigData=$($Policy.TargetedDomainProtectionAction)
                Control=$Cid
            }
        }
        Else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="TargetedDomainProtectionAction"
                ConfigData=$($Policy.TargetedDomainProtectionAction)
                Control=$Cid
            }
        }

    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Rule="No Enabled AntiPhish Policy"
            Control=$Cid
        }            
    }

    Return $Return
}


function Invoke-CheckATPPhishUserImpAction
{
    Param(
        $AntiPhishPolicy
    )

    $Check = "ATP User Impersonation"
    $Cid = "223"
    
    $Return = @()

    ForEach($Policy in ($AntiPhishPolicy | Where-Object {$_.Enabled -eq $True}))
    {

        If($Policy.EnableTargetedUserProtection -eq $False)
        {
            # Policy Targeted UserProtection is off
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableTargetedUserProtection"
                ConfigData=$($Policy.EnableTargetedUserProtection)
                Rule="Targeted User Protection Off"
                Control=$Cid
            }
        } 
        Else
        {
            # Check for action being MoveToJmf
            If($Policy.TargetedUserProtectionAction -eq "Quarantine")
            {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Pass"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="TargetedUserProtectionAction"
                    ConfigData=$($Policy.TargetedUserProtectionAction)
                    Control=$Cid
                }   
            }
            Else
            {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="TargetedUserProtectionAction"
                    ConfigData=$($Policy.TargetedUserProtectionAction)
                    Control=$Cid
                }                 
            }
        }
    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Control=$Cid
        }            
    }

    Return $Return
}

function Invoke-CheckATPPhishMIAction
{
    <#
     
    221 and 224 - Check ATP Phishing Mailbox Intelligence Action
     
    #>

    Param(
        $AntiPhishPolicy
    )

    $Check = "ATP Mailbox Intelligence"
    
    $Return = @()


    ForEach($Policy in ($AntiPhishPolicy | Where-Object {$_.Enabled -eq $True}))
    {

        # Determine Mailbox Intelligence is ON

        If($Policy.EnableMailboxIntelligence -eq $false)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableMailboxIntelligence"
                ConfigData=$($Policy.EnableMailboxIntelligence)
                Rule="Mailbox Intelligence Off"
                Control="221"
            }                
        }
        Else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableMailboxIntelligence"
                ConfigData=$($Policy.EnableMailboxIntelligence)
                Rule="Mailbox Intelligence On"
                Control="221"
            }                            
        }

        # Determine if tips for user impersonation is on

        If($Policy.EnableSimilarUsersSafetyTips -eq $false)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableSimilarUsersSafetyTips"
                ConfigData=$($Policy.EnableSimilarUsersSafetyTips)
                Control="224"
            }  
        }
        else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="EnableSimilarUsersSafetyTips"
                ConfigData=$($Policy.EnableSimilarUsersSafetyTips)
                Control="224"
            }                  
        }
    }

    If($Return.Count -eq 0)
    {
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Check=$Check
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Control="221"
        }
        $Return += New-Object -TypeName psobject -Property @{
            Result="Fail"
            Object="All"
            ConfigItem="Enabled"
            ConfigData="False"
            Check=$Check
            Control="224"
        }             
    }

    Return $Return
}

function Invoke-CheckContentFilterASF {
    <#
    Checks to determine if Content Filter Policy ASF options are tunred off.
    #>

    Param(
        $ContentFilterPolicies
    )

    $Check = "Content Filter Polciy ASF"
    $Cid = "ORCA-102"
    
    $Return = @()

    ForEach($Policy in $ContentFilterPolicies) {
        # Determine if ASF options are off or not
        If($Policy.IncreaseScoreWithImageLinks -eq "On" -or $Policy.IncreaseScoreWithNumericIps -eq "On" -or $Policy.IncreaseScoreWithRedirectToOtherPort -eq "On" -or $Policy.IncreaseScoreWithBizOrInfoUrls -eq "On" -or $Policy.MarkAsSpamEmptyMessages -eq "On" -or $Policy.MarkAsSpamJavaScriptInHtml -eq "On" -or $Policy.MarkAsSpamFramesInHtml -eq "On" -or $Policy.MarkAsSpamObjectTagsInHtml -eq "On" -or $Policy.MarkAsSpamEmbedTagsInHtml -eq "On" -or $Policy.MarkAsSpamFormTagsInHtml -eq "On" -or $Policy.MarkAsSpamWebBugsInHtml -eq "On" -or $Policy.MarkAsSpamSensitiveWordList -eq "On" -or $Policy.MarkAsSpamFromAddressAuthFail -eq "On" -or $Policy.MarkAsSpamNdrBackscatter -eq "On" -or $Policy.MarkAsSpamSpfRecordHardFail -eq "On") {
            If($Policy.IncreaseScoreWithImageLinks -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="IncreaseScoreWithImageLinks"
                    ConfigData=$($Policy.IncreaseScoreWithImageLinks)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.IncreaseScoreWithNumericIps -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="IncreaseScoreWithNumericIps"
                    ConfigData=$($Policy.IncreaseScoreWithNumericIps)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.IncreaseScoreWithRedirectToOtherPort -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="IncreaseScoreWithRedirectToOtherPort"
                    ConfigData=$($Policy.IncreaseScoreWithRedirectToOtherPort)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.IncreaseScoreWithBizOrInfoUrls -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="IncreaseScoreWithBizOrInfoUrls"
                    ConfigData=$($Policy.IncreaseScoreWithBizOrInfoUrls)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamEmptyMessages -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamEmptyMessages"
                    ConfigData=$($Policy.MarkAsSpamEmptyMessages)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamJavaScriptInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamJavaScriptInHtml"
                    ConfigData=$($Policy.MarkAsSpamJavaScriptInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamFramesInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamFramesInHtml"
                    ConfigData=$($Policy.MarkAsSpamFramesInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamObjectTagsInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamObjectTagsInHtml"
                    ConfigData=$($Policy.MarkAsSpamObjectTagsInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamEmbedTagsInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamEmbedTagsInHtml"
                    ConfigData=$($Policy.MarkAsSpamEmbedTagsInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamFormTagsInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamFormTagsInHtml"
                    ConfigData=$($Policy.MarkAsSpamFormTagsInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamWebBugsInHtml -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamWebBugsInHtml"
                    ConfigData=$($Policy.MarkAsSpamWebBugsInHtml)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamSensitiveWordList -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamSensitiveWordList"
                    ConfigData=$($Policy.MarkAsSpamSensitiveWordList)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamFromAddressAuthFail -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamFromAddressAuthFail"
                    ConfigData=$($Policy.MarkAsSpamFromAddressAuthFail)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamNdrBackscatter -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamNdrBackscatter"
                    ConfigData=$($Policy.MarkAsSpamNdrBackscatter)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }
            If ($Policy.MarkAsSpamSpfRecordHardFail -eq "On") {
                $Return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    Object=$($Policy.Name)
                    ConfigItem="MarkAsSpamSpfRecordHardFail"
                    ConfigData=$($Policy.MarkAsSpamSpfRecordHardFail)
                    Rule="Content Fileter policy ASF options"
                    Control=$Cid
                }
            }

        }
        else {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Check=$Check
                Object=$($Policy.Name)
                ConfigItem="ASF Options"
                ConfigData="Disabled"
                Rule="Content Fileter policy ASF options"
                Control=$Cid
            }
        }
    }

    Return $Return
}


function Invoke-CheckMarkAsSpamBulkMail
{
    <#
     
    ORCA-101
 
    #>

    Param(
        $HostedContentFilterPolicy
    )
    
    $Return = @()
    $CID = "ORCA-101"

    ForEach($Policy in $HostedContentFilterPolicy)
    {

        If($Policy.MarkAsSpamBulkMail -eq "On")
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.MarkAsSpamBulkMail
                Control=$CID
            }                
        }
        Else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.MarkAsSpamBulkMail
                Control=$CID
            }                            
        }

    }

    Return $Return
}
function Invoke-CheckBulkThreshold
{
    <#
     
    ORCA-100
 
    #>

    Param(
        $HostedContentFilterPolicy
    )
    
    $Return = @()
    $CID = "ORCA-100"

    ForEach($Policy in $HostedContentFilterPolicy)
    {

        If($Policy.BulkThreshold -ge 4 -and $Policy.BulkThreshold -le 6)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.BulkThreshold
                Control=$CID
            }                
        }
        Else 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                ConfigItem=$($Policy.Name)
                ConfigData=$Policy.BulkThreshold
                Control=$CID
            }                            
        }

    }

    Return $Return
}

function Invoke-CheckDKIMSigning 
{
    Param(
        $DkimSigningConfigs,
        $AcceptedDomains
    )

    $Check = "DKIM"

    $return = @()

    # Check DKIM is enabled

    ForEach($AcceptedDomain in $AcceptedDomains) 
    {

        If($AcceptedDomain.Name -notlike "*.onmicrosoft.com") 
        {

            # Get matching DKIM signing configuration
            $DkimSigningConfig = $DkimSigningConfigs | Where-Object {$_.Name -eq $AcceptedDomain.Name}

            If($DkimSigningConfig)
            {
                if($DkimSigningConfig.Enabled -eq $false)
                {
                    $return += New-Object -TypeName psobject -Property @{
                        Result="Fail"
                        Check=$Check
                        ConfigItem=$($DkimSigningConfig.Domain)
                        Rule="DKIM Signing Disabled"
                        Control="108"
                    }    
                } 
                else
                {
                    $return += New-Object -TypeName psobject -Property @{
                        Result="Pass"
                        Check=$Check
                        ConfigItem=$($DkimSigningConfig.Domain)
                        Rule="DKIM Signing Enabled"
                        Control="108"
                    }     
                        # Check DKIM Selector Records
                        Try { $Selector1 = Resolve-DnsName -Type TXT -Name "selector1._domainkey.$($DkimSigningConfig.Domain)" -ErrorAction:stop } Catch {}
                        If($Selector1.Type -eq "CNAME" -and $Selector1.NameHost -eq $DkimSigningConfig.Selector1CNAME)
                        {
                            # DKIM Selector1 Correctly Configured
                            $return += New-Object -TypeName psobject -Property @{
                                Result="Pass"
                                Check=$Check
                                ConfigItem=$($DkimSigningConfig.Domain)
                                ConfigData="Selector1 CNAME $($DkimSigningConfig.Selector1CNAME)"
                                Rule="DKIM Signing Selectors Configured"
                                Control="108-1"
                            }
                        } 
                        else
                        {
                            $return += New-Object -TypeName psobject -Property @{
                                Result="Fail"
                                Check=$Check
                                ConfigItem=$($DkimSigningConfig.Domain)
                                Rule="DKIM Signing Selectors Misconfigured"
                                ConfigData="Selector1 CNAME"
                                Control="108-1"
                            }     
                        }
        
                        # Check DKIM Selector Records
                        Try { $Selector2 = Resolve-DnsName -Type TXT -Name "selector2._domainkey.$($DkimSigningConfig.Domain)" -ErrorAction:stop } Catch {}
                        If($Selector2.Type -eq "CNAME" -and $Selector2.NameHost -eq $DkimSigningConfig.Selector2CNAME)
                        {
                            # DKIM Selector2 Correctly Configured
                            $return += New-Object -TypeName psobject -Property @{
                                Result="Pass"
                                Check=$Check
                                ConfigItem=$($DkimSigningConfig.Domain)
                                ConfigData="Selector2 CNAME $($DkimSigningConfig.Selector2CNAME)"
                                Rule="DKIM Signing Selectors Configured"
                                Control="108-1"
                            }
                        }
                        else
                        {
                            $return += New-Object -TypeName psobject -Property @{
                                Result="Fail"
                                Check=$Check
                                ConfigItem=$($DkimSigningConfig.Domain)
                                Rule="DKIM Signing Selectors Misconfigured"
                                ConfigData="Selector2 CNAME"
                                Control="108-1"
                            }    
                        }            
                    }
            }
            Else
            {
                $return += New-Object -TypeName psobject -Property @{
                    Result="Fail"
                    Check=$Check
                    ConfigItem=$($AcceptedDomain.Name)
                    Rule="No DKIM Signing Config"
                    Control="108"
                } 
            }

        }

    }

    return $return        
}

function Invoke-CheckOutboundSpamPolicies
{
    <#
     
    ORCA-103 Check Outbound Spam Policies for Recipients limits and action
 
    #>

    Param(
        $HostedOutboundSpamFilterPolicy
    )
    
    $Return = @()
    $CID = "ORCA-103"

    ForEach($Policy in $HostedOutboundSpamFilterPolicy)
    {

        If($Policy.RecipientLimitExternalPerHour -eq 500)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitExternalPerHour"
                ConfigData=$($Policy.RecipientLimitExternalPerHour)
                Control=$CID
            }                
        }
        Else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitExternalPerHour"
                ConfigData=$($Policy.RecipientLimitExternalPerHour) #the recommended setting is 500
                Control=$CID
            }                            
        }
        If($Policy.RecipientLimitInternalPerHour -eq 1000)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitInternalPerHour"
                ConfigData=$($Policy.RecipientLimitInternalPerHour)
                Control=$CID
            }                
        }
        Else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitInternalPerHour"
                ConfigData=$($Policy.RecipientLimitInternalPerHour) # the recommended setting is 1000"
                Control=$CID
            }                            
        }
        If($Policy.RecipientLimitPerDay -eq 1000)
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitPerDay"
                ConfigData=$($Policy.RecipientLimitPerDay)
                Control=$CID
            }                
        }
        Else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Object=$($Policy.Name)
                ConfigItem="RecipientLimitPerDay"
                ConfigData=$($Policy.RecipientLimitPerDay) # the recommended setting is 1000"
                Control=$CID
            }                            
        }
        If($Policy.ActionWhenThresholdReached -like "BlockUser")
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Pass"
                Object="$($Policy.Name)"
                ConfigItem="ActionWhenThresholdReached"
                ConfigData=$($Policy.ActionWhenThresholdReached)
                Control=$CID
            }                
        }     
        Else
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Object=$($Policy.Name)
                ConfigItem="ActionWhenThresholdReached"
                ConfigData=$($Policy.ActionWhenThresholdReached) # the recommended setting is BlockUser"
                Control=$CID
            }                            
        }
    }

    Return $Return
}

function Invoke-CheckATPSafeLinksBypass 
{
    <#
     
        189-2
         
        Checks to determine if SafeLinks is being bypassed by injecting X-MS-Exchange-Organization-SkipSafeLinksProcessing
        header in to emails using a mail flow rule.
     
    #>

    Param
    (
        $TransportRules
    )

    $Check = "ATP"
    $Cid = "189-2"
    
    $Return = @()

    $BypassRules = @($TransportRules | Where-Object {$_.SetHeaderName -eq "X-MS-Exchange-Organization-SkipSafeLinksProcessing"})
    
    If($BypassRules.Count -gt 0) 
    {
        # Rules exist to bypass
        ForEach($Rule in $BypassRules) 
        {
            $Return += New-Object -TypeName psobject -Property @{
                Result="Fail"
                Check=$Check
                ConfigItem="Transport Rule - $($Rule.Name)"
                ConfigData="Setting $($Rule.SetHeaderName) to $($Rule.SetHeaderValue)"
                Rule="SafeLinks bypassed"
                Control=$Cid
            }
        }
    } 
    Else 
    {
        # Rules do not exist to bypass
        $Return += New-Object -TypeName psobject -Property @{
            Result="Pass"
            Check=$Check
            ConfigItem="Transport Rules"
            Rule="SafeLinks not bypassed"
            Control=$Cid
        }
    }

    Return $Return
}

Function Invoke-ORCAConnections
{
    <#
     
    Check which module is loaded and then run the respective connection
     
    #>


    If(Get-Command "Connect-EXOPSSession" -ErrorAction:SilentlyContinue)
    {
        Write-Host "$(Get-Date) Connecting to Exchange Online.."
        Connect-EXOPSSession -PSSessionOption $ProxySetting -WarningAction:SilentlyContinue | Out-Null    
    } 
    ElseIf(Get-Command "Connect-ExchangeOnline" -ErrorAction:SilentlyContinue)
    {
        Write-Host "$(Get-Date) Connecting to Exchange Online (Modern Module).."
        Connect-ExchangeOnline -WarningAction:SilentlyContinue | Out-Null
    }
    Else 
    {
        Throw "ORCA requires either the Exchange Online PowerShell Module (aka.ms/exopsmodule) loaded or the Exchange Online PowerShell module from the PowerShell Gallery installed."
    }

    # Perform check for Exchange Connection Status
    If($(Get-EXConnectionStatus) -eq $False)
    {
        Throw "ORCA was unable to connect to Exchange Online."
    }
}

enum CheckType
{
    ObjectPropertyValue
    PropertyValue
}

Class ORCACheck
{
    <#
 
        Check definition
 
        The checks defined below allow contextual information to be added in to the report HTML document.
        - Control : A unique identifier that can be used to index the results back to the check
        - Area : The area that this check should appear within the report
        - PassText : The text that should appear in the report when this 'control' passes
        - FailRecommendation : The text that appears as a title when the 'control' fails. Short, descriptive. E.g "Do this"
        - Importance : Why this is important
        - ExpandResults : If we should create a table in the callout which points out which items fail and where
        - ObjectType : When ExpandResults is set to, For Object, Property Value checks - what is the name of the Object, e.g a Spam Policy
        - ItemName : When ExpandResults is set to, what does the check return as ConfigItem, for instance, is it a Transport Rule?
        - DataType : When ExpandResults is set to, what type of data is returned in ConfigData, for instance, is it a Domain?
 
    #>


    [string] $Control
    [String] $Area
    [String] $Name
    [String] $PassText
    [String] $FailRecommendation
    [Boolean] $ExpandResults=$false
    [String] $ObjectType
    [String] $ItemName
    [String] $DataType
    [String] $Importance
    $Links
    [CheckType] $CheckType = [CheckType]::PropertyValue
}
Function Get-ORCACheckDefs
{

    $Checks = @()

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-100"
        Area="Content Filter Policies"
        Name="Bulk Complaint Level"
        PassText="Bulk Complaint Level threshold is between 4 and 6"
        FailRecommendation="Set the Bulk Complaint Level threshold to be between 4 and 6"
        Importance="The differentiation between bulk and spam can sometimes be subjective. The bulk complaint level is based on the number of complaints from the sender. Decreasing the threshold can decrease the amount of perceived spam received, however, too low may be considered too strict."
        ExpandResults=$True
        ItemName="Content Filter Policy"
        DataType="Bulk Complaint Level Threshold"
        Links= @{
            "Bulk Complaint Level values"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/bulk-complaint-level-values"
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-101"
        Area="Content Filter Policies"
        Name="Mark Bulk as Spam"
        PassText="Bulk is marked as spam"
        FailRecommendation="Set the content filter policy to mark bulk mail as spam"
        Importance="The differentiation between bulk and spam can sometimes be subjective. The bulk complaint level is based on the number of complaints from the sender. Marking bulk as spam can decrease the amount of perceived spam received."
        ExpandResults=$True
        ItemName="Content Filter Policy"
        DataType="Mark as Spam Bulk Mail Setting (MarkAsSpamBulkMail)"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-102"
        Area="Content Filter Policies"
        Name="Advanced Spam Filter (ASF)"
        PassText="Advanced Spam filter options are runed off"
        FailRecommendation="Turn off Advanced Spam filter (ASF) options in Content filter policies"
        Importance="Settings in the Advanced Spam Filter (ASF) are currently being deprecated. It is recommended to disable ASF settings."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-103"
        Area="Content Filter Policies"
        Name="Outbound spam filter policy settings"
        PassText="Outbound spam filter policy settings configured"
        FailRecommendation="Set RecipientLimitExternalPerHour to 500, RecipientLimitInternalPerHour to 1000, and ActionWhenThresholdReached to block."
        Importance="Configure the maximum number of recipients that a user can send to, per hour for internal (RecipientLimitInternalPerHour) and external recipients (RecipientLimitExternalPerHour) and maximum number per day for outbound email. It is common, after an account compromise incident, for an attacker to use the account to generate spam and phish. Configuring the recommended values can reduce the impact, but also allows you to receive notifications when these thresholds have been reached."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Outbound Spam Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="108"
        Area="DKIM"
        Name="Signing Configuration"
        PassText="DKIM signing is set up for all your custom domains"
        FailRecommendation="Set up DKIM signing to sign your emails"
        Importance="DKIM signing can help protect the authenticity of your messages in transit and can assist with deliverability of your email messages."
        ExpandResults=$True
        ItemName="Domain"
        DataType="Signing Setting"
        Links= @{
            "Use DKIM to validate outbound email sent from your custom domain in Office 365"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/use-dkim-to-validate-outbound-email"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="108-1"
        Area="DKIM"
        Name="DNS Records"
        PassText="DNS Records have been set up to support DKIM"
        FailRecommendation="Set up the required selector DNS records in order to support DKIM"
        Importance="DKIM signing can help protect the authenticity of your messages in transit and can assist with deliverability of your email messages."
        ExpandResults=$True
        ItemName="Domain"
        DataType="DNS Record"
        Links= @{
            "Use DKIM to validate outbound email sent from your custom domain in Office 365"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/use-dkim-to-validate-outbound-email"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=114
        Area="Content Filter Policies"
        Name="IP Allow Lists"
        PassText="No IP Allow Lists have been configured"
        FailRecommendation="Remove IP addresses from IP allow list"
        Importance="IP addresses containted in the IP allow list are able to bypass spam, phishing and spoofing checks, potentially resulting in more spam. Ensure that the IP list is kept to a minimum."
        ExpandResults=$True
        ItemName="Content Filter Policy"
        DataType="Allowed IP"
        Links= @{
            "Use Anti-Spam Policy IP Allow lists"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/create-safe-sender-lists-in-office-365#use-anti-spam-policy-ip-allow-lists"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="118-1"
        Area="Content Filter Policies"
        Name="Domain Whitelisting"
        PassText="Domains are not being whitelisted in an unsafe manner"
        FailRecommendation="Remove whitelisting on domains"
        Importance="Emails coming from whitelisted domains bypass several layers of protection within Exchange Online Protection. If domains are whitelisted, they are open to being spoofed from malicious actors."
        ExpandResults=$True
        ItemName="Content Filter Policy"
        DataType="Whitelisted Domain"
        Links= @{
            "Use Anti-Spam Policy Sender/Domain Allow lists"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/create-safe-sender-lists-in-office-365#use-anti-spam-policy-senderdomain-allow-lists"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="118-2"
        Area="Transport Rules"
        Name="Domain Whitelisting"
        PassText="Domains are not being whitelisted in an unsafe manner"
        FailRecommendation="Remove whitelisting on domains"
        Importance="Emails coming from whitelisted domains bypass several layers of protection within Exchange Online Protection. If domains are whitelisted, they are open to being spoofed from malicious actors."
        ExpandResults=$True
        ItemName="Transport Rule"
        DataType="Whitelisted Domain"
        Links= @{
            "Using Exchange Transport Rules (ETRs) to allow specific senders"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/create-safe-sender-lists-in-office-365#using-exchange-transport-rules-etrs-to-allow-specific-senders-recommended"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="120-spam"
        Area="Zero Hour Autopurge"
        Name="Zero Hour Autopurge Enabled for Spam"
        PassText="Zero Hour Autopurge is Enabled"
        FailRecommendation="Enable Zero Hour Autopurge"
        Importance="Zero Hour Autopurge can assist removing false-negatives post detection from mailboxes. By default, it is enabled."
        ExpandResults=$True
        ItemName="Policy"
        DataType="ZapEnabled Setting"
        Links= @{
            "Zero-hour auto purge - protection against spam and malware"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/zero-hour-auto-purge"
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="120-phish"
        Area="Zero Hour Autopurge"
        Name="Zero Hour Autopurge Enabled for Phish"
        PassText="Zero Hour Autopurge is Enabled"
        FailRecommendation="Enable Zero Hour Autopurge"
        Importance="Zero Hour Autopurge can assist removing false-negatives post detection from mailboxes. By default, it is enabled."
        ExpandResults=$True
        ItemName="Policy"
        DataType="ZapEnabled Setting"
        Links= @{
            "Zero-hour auto purge - protection against spam and malware"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/zero-hour-auto-purge"
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="120-malware"
        Area="Zero Hour Autopurge"
        Name="Zero Hour Autopurge Enabled for Malware"
        PassText="Zero Hour Autopurge is Enabled"
        FailRecommendation="Enable Zero Hour Autopurge"
        Importance="Zero Hour Autopurge can assist removing false-negatives post detection from mailboxes. By default, it is enabled."
        ExpandResults=$True
        ItemName="Policy"
        DataType="ZapEnabled Setting"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=121
        Area="Zero Hour Autopurge"
        Name="Supported filter policy action"
        PassText="Supported filter policy action used"
        FailRecommendation="Change filter policy action to support Zero Hour Auto Purge"
        Importance="Zero Hour Autopurge can assist removing false-negatives post detection from mailboxes. It requires a supported action in the spam filter policy."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Policy"
        ItemName="Setting"
        DataType="Action"
        Links= @{
            "Zero-hour auto purge - protection against spam and malware"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/zero-hour-auto-purge"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=122
        Area="Tenant Settings"
        Name="Unified Audit Log"
        PassText="Unified Audit Log is enabled"
        FailRecommendation="Enable the Unified Audit Log"
        Importance="The Unified Audit Log collects logs from most Office 365 services and provides one central place to correlate and pull logs from Office 365."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=125
        Area="Malware Filter Policy"
        Name="External Sender Notifications"
        PassText="External Sender notifications are disabled"
        FailRecommendation="Disable notifying external senders of malware detection"
        Importance="Notifying external senders about malware detected in email messages could have negative impact. An adversary may use this information to verify effectiveness of malware detection."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=139
        Area="Content Filter Policies"
        Name="Spam Action"
        PassText="Spam action set to Move message to Junk Email Folder"
        FailRecommendation="Change Spam action to Move message to Junk Email Folder"
        Importance="It is recommended to configure Spam detection action to Move messages to Junk Email folder."
        ExpandResults=$True
        ItemName="Spam Policy"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=140
        Area="Content Filter Policies"
        Name="High Confidence Spam Action"
        PassText="High Confidence Spam action set to Quarantine message"
        FailRecommendation="Change High Confidence Spam action to Quarantine message"
        Importance="It is recommended to configure High Confidence Spam detection action to Quarantine message."
        ExpandResults=$True
        ItemName="Spam Policy"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }  
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=141
        Area="Content Filter Policies"
        Name="Bulk Action"
        PassText="Bulk action set to Move message to Junk Email Folder"
        FailRecommendation="Change Bulk action to Move message to Junk Email Folder"
        Importance="It is recommended to configure Bulk detection action to Move messages to Junk Email folder."
        ExpandResults=$True
        ItemName="Spam Policy"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=142
        Area="Content Filter Policies"
        Name="Phish Action"
        PassText="Phish action set to Quarantine message"
        FailRecommendation="Change Phish action to Quarantine message"
        Importance="It is recommended to configure the Phish detection action to Quarantine so that these emails are not visible to the end user from within Outlook. As Phishing emails are designed to look legitimate, users may mistakenly think that a phishing email in Junk is false-positive."
        ExpandResults=$True
        ItemName="Spam Policy"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-104"
        Area="Content Filter Policies"
        Name="High Confidence Phish Action"
        PassText="High Confidence Phish action set to Quarantine message"
        FailRecommendation="Change High Confidence Phish action to Quarantine message"
        Importance="It is recommended to configure the High Confidence Phish detection action to Quarantine so that these emails are not visible to the end user from within Outlook. As Phishing emails are designed to look legitimate, users may mistakenly think that a phishing email in Junk is false-positive."
        ExpandResults=$True
        ItemName="Spam Policy"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#anti-spam-anti-malware-and-anti-phishing-protection-in-eop"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=143
        Area="Content Filter Policies"
        Name="Safety Tips"
        PassText="Safety Tips are enabled"
        FailRecommendation="Safety Tips should be enabled"
        Importance="By default, safety tips can provide useful security information when reading an email."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=156
        Area="Advanced Threat Protection Policies"
        Name="Safe Links Tracking"
        PassText="Safe Links Policies are tracking when user clicks on safe links"
        FailRecommendation="Enable tracking of user clicks in Safe Links Policies"
        Importance="When these options are configured, click data for URLs in Word, Excel, PowerPoint, Visio documents and in emails is stored by Safe Links. This information can help dealing with phishing, suspicious email messages and URLs."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Policy"
        ItemName="Setting"
        DataType="Current Value"
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=158
        Area="Advanced Threat Protection Policies"
        Name="Safe Attachments SharePoint and Teams"
        PassText="Safe Attachments is enabled for SharePoint and Teams"
        FailRecommendation="Enable Safe Attachments for SharePoint and Teams"
        Importance="Safe Attachments assists scanning for zero day malware by using behavioural analysis and sandboxing, supplimenting signature definitions."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=169
        Area="Advanced Threat Protection Policies"
        Name="Office Enablement"
        PassText="Safe Links is enabled for Office ProPlus, Office for iOS and Android"
        FailRecommendation="Enable Safe Links for Office ProPlus, Office for iOS and Android"
        Importance="Phishing attacks are not limited to email messages. Malicious URLs can be delivered using Office documents as well. Configuring Office 365 ATP Safe Links for Office ProPlus, Office for iOS and Android can help combat against these attacks via providing time-of-click verification of web addresses (URLs) in Office documents."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=179
        Area="Advanced Threat Protection Policies"
        Name="Intra-organization Safe Links"
        PassText="Safe Links is enabled intra-organization"
        FailRecommendation="Enable Safe Links between internal users"
        Importance="Phishing attacks are not limited from external users. Commonly, when one user is compromised, that user can be used in a process of lateral movement between different accounts in your organization. Configuring Safe Links so that internal messages are also re-written can assist with lateral movement using phishing."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="ORCA-105"
        Area="Advanced Threat Protection Policies"
        Name="Safe Links Synchronous URL detonation"
        PassText="Safe Links Synchronous URL detonation is enabled"
        FailRecommendation="Enable Safe Links Synchronous URL detonation"
        Importance="When the 'Wait for URL scanning to complete before delivering the message' option is configured, messages that contain URLs to be scanned will be held until the URLs finish scanning and are confirmed to be safe before the messages are delivered."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Set up Office 365 ATP Safe Links policies"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/set-up-atp-safe-links-policies#step-4-learn-about-atp-safe-links-policy-options"
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=180
        Area="Advanced Threat Protection Policies"
        Name="Anti-spoofing protection"
        PassText="Anti-phishing policy exists and EnableAntiSpoofEnforcement is true"
        FailRecommendation="Enable anti-spoofing protection in Anti-phishing policy"
        Importance="When the sender email address is spoofed, the message appears to originate from someone or somewhere other than the actual source. Anti-spoofing protection examines forgery of the 'From: header' which is the one that shows up in an email client like Outlook. It is recommended to enable anti-spoofing protection in Office 365 Anti-phishing policies."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Antiphishing Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Anti-spoofing protection in Office 365"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/anti-spoofing-protection"
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=189
        Area="Advanced Threat Protection Policies"
        Name="Safe Attachment Whitelisting"
        PassText="Safe Attachments is not bypassed"
        FailRecommendation="Remove mail flow rules which bypass Safe Attachments"
        Importance="Office 365 ATP Safe Attachments assists scanning for zero day malware by using behavioural analysis and sandboxing, supplementing signature definitions. The protection can be bypassed using mail flow rules which set the X-MS-Exchange-Organization-SkipSafeAttachmentProcessing header for email messages."
        ExpandResults=$True
        ItemName="Transport Rule"
        DataType="Details"
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control="189-2"
        Area="Advanced Threat Protection Policies"
        Name="Safe Links Whitelisting"
        PassText="Safe Links is not bypassed"
        FailRecommendation="Remove mail flow rules which bypass Safe Links"
        Importance="Office 365 ATP Safe Links can help protect against phishing attacks by providing time-of-click verification of web addresses (URLs) in email messages and Office documents. The protection can be bypassed using mail flow rules which set the X-MS-Exchange-Organization-SkipSafeLinksProcessing header for email messages."
        ExpandResults=$True
        ItemName="Transport Rule"
        DataType="Details"
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=205
        Area="Malware Filter Policy"
        Name="Common Attachment Type Filter"
        PassText="Common attachment type filter is enabled"
        FailRecommendation="Enable common attachment type filter"
        Importance="The common attachment type filter can block file types that commonly contain malware, including in internal emails."
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=220
        Area="Advanced Threat Protection Policies"
        Name="Advanced Phishing Threshold Level"
        PassText="Advanced Phish filter Threshold level is adequate."
        FailRecommendation="Set Advanced Phish filter Threshold to 2 or 3"
        Importance="The higher the Advanced Phishing Threshold Level, the stricter the mechanisms are that detect phishing attempts against your users, however, too high may be considered too strict."
        ExpandResults=$True
        ItemName="Antiphishing Policy"
        DataType="Advanced Phishing Threshold Level"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=221
        Area="Advanced Threat Protection Policies"
        Name="Mailbox Intelligence Enabled"
        PassText="Mailbox intelligence is enabled in anti-phishing policies"
        FailRecommendation="Enable mailbox intelligence in anti-phishing policies"
        Importance="Mailbox Intelligence checks can provide your users with intelligence on suspicious incoming emails that appear to be from users that they normally communicate with based on their graph."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Antiphishing Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=222
        Area="Advanced Threat Protection Policies"
        Name="Domain Impersonation Action"
        PassText="Domain Impersonation action is set to move to Quarantine"
        FailRecommendation="Configure domain impersonation action to Quarantine"
        Importance="Domain Impersonation can detect impersonation attempts against your domains or domains that look very similiar to your domains. Move messages that are caught using this impersonation protection to Quarantine."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Antiphishing Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=223
        Area="Advanced Threat Protection Policies"
        Name="User Impersonation Action"
        PassText="User impersonation action is set to move to Quarantine"
        FailRecommendation="Configure user impersonation action to Quarantine"
        Importance="User impersonation protection can detect spoofing of your sensitive users. Move messages that are caught using user impersonation detection to Quarantine."
        ExpandResults=$True
        CheckType=[CheckType]::ObjectPropertyValue
        ObjectType="Antiphishing Policy"
        ItemName="Setting"
        DataType="Action"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    $Checks += New-Object -TypeName ORCACheck -Property @{
        Control=224
        Area="Advanced Threat Protection Policies"
        Name="Mailbox Intelligence Action"
        PassText="Your policy is configured to notify users with a tip."
        FailRecommendation="Enable tips so that users can receive visible indication on incoming messages."
        Importance="Mailbox Intelligence checks can provide your users with intelligence on suspicious incoming emails that appear to be from users that they normally communicate with based on their graph."
        ExpandResults=$True
        ObjectType="Antiphishing Policy"
        ItemName="Setting"
        DataType="Current Value"
        Links= @{
            "Recommended settings for EOP and Office 365 ATP security"="https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/recommended-settings-for-eop-and-office365-atp#office-365-advanced-threat-protection-security"
        }
    }

    Return $Checks
}

Function Get-ORCACollection
{
    $Collection = @{}

    Write-Host "$(Get-Date) Getting Anti-Spam Settings"
    $Collection["HostedConnectionFilterPolicy"] = Get-HostedConnectionFilterPolicy
    $Collection["HostedContentFilterPolicy"] = Get-HostedContentFilterPolicy
    $Collection["HostedContentFilterRule"] = Get-HostedContentFilterRule
    $Collection["HostedOutboundSpamFilterPolicy"] = Get-HostedOutboundSpamFilterPolicy

    Write-Host "$(Get-Date) Getting Tenant Settings"
    $Collection["AdminAuditLogConfig"] = Get-AdminAuditLogConfig

    Write-Host "$(Get-Date) Getting Anti Phish Settings"
    $Collection["AntiPhishPolicy"] = Get-AntiphishPolicy

    Write-Host "$(Get-Date) Getting Anti-Malware Settings"
    $Collection["MalwareFilterPolicy"] = Get-MalwareFilterPolicy
    $Collection["MalwareFilterRule"] = Get-MalwareFilterRule

    Write-Host "$(Get-Date) Getting Transport Rules"
    $Collection["TransportRules"] = Get-TransportRule

    Write-Host "$(Get-Date) Getting ATP Policies"
    $Collection["SafeAttachmentsPolicy"] = Get-SafeAttachmentPolicy
    $Collection["SafeAttachmentsRules"] = Get-SafeAttachmentRule
    $Collection["SafeLinksPolicy"] = Get-SafeLinksPolicy
    $Collection["SafeLinksRules"] = Get-SafeLinksRule
    $Collection["AtpPolicy"] = Get-AtpPolicyForO365

    Write-Host "$(Get-Date) Getting Accepted Domains"
    $Collection["AcceptedDomains"] = Get-AcceptedDomain

    Write-Host "$(Get-Date) Getting DKIM Configuration"
    $Collection["DkimSigningConfig"] = Get-DkimSigningConfig

    Return $Collection
}

Function Get-ORCAResults
{
    Param(
        $Collection
    )

    # Main Analysis
    Write-Host "$(Get-Date) Analysis starting. Version $($Version)" -ForegroundColor Green

    $Return = @()
    Write-Host "$(Get-Date) Analysis - Unified Auditing"
    $Return += Invoke-CheckUnifiedLogging $Collection.Get_Item("AdminAuditLogConfig")

    Write-Host "$(Get-Date) Analysis - Exchange - Allow lists"
    $Return += Invoke-CheckAllowedSenderDomains $Collection.Get_Item("HostedContentFilterPolicy")

    Write-Host "$(Get-Date) Analysis - Exchange - ZAP Checks"
    $Return += Invoke-CheckZAP -MalwareFilterPolicies $Collection.Get_Item("MalwareFilterPolicy") -ContentFilterPolicies $Collection.Get_Item("HostedContentFilterPolicy")

    Write-Host "$(Get-Date) Analysis - Exchange - Content Filter Policy"
    $Return += Invoke-CheckContentFilterActions -ContentFilterPolicies $Collection.Get_Item("HostedContentFilterPolicy")
    $Return += Invoke-CheckContentFilterSafetyTips -ContentFilterPolicies $Collection.Get_Item("HostedContentFilterPolicy")
    $Return += Invoke-CheckBulkThreshold -HostedContentFilterPolicy $Collection.Get_Item("HostedContentFilterPolicy")
    $Return += Invoke-CheckMarkAsSpamBulkMail  -HostedContentFilterPolicy $Collection.Get_Item("HostedContentFilterPolicy")
    $Return += Invoke-CheckContentFilterASF -ContentFilterPolicies $Collection.Get_Item("HostedContentFilterPolicy")
    $Return += Invoke-CheckOutboundSpamPolicies -HostedOutboundSpamFilterPolicy $Collection.Get_Item("HostedOutboundSpamFilterPolicy")

    Write-Host "$(Get-Date) Analysis - Exchange - Malware Filter Policy"
    $Return += Invoke-CheckMalwareNotifications $Collection.Get_Item("MalwareFilterPolicy")
    $Return += Invoke-CheckCommonAttachmentTypeFilter -MalwareFilterPolicies $Collection.Get_Item("MalwareFilterPolicy")

    $Return += Invoke-CheckIPAllowList $Collection.Get_Item("HostedConnectionFilterPolicy")

    Write-Host "$(Get-Date) Analysis - Exchange - Transport Rules"
    $Return += Invoke-CheckTransportRuleSCL $Collection.Get_Item("TransportRules")

    Write-Host "$(Get-Date) Analysis - ATP - General"
    $Return += Invoke-CheckATPForSPOTeamsODB -ATPPolicy $Collection.Get_Item("AtpPolicy")

    Write-Host "$(Get-Date) Analysis - ATP - SafeLinks"
    $Return += Invoke-CheckATPSafeLinksTracking -ATPPolicy $Collection.Get_Item("AtpPolicy") -SafeLinksPolicies $Collection.Get_Item("SafeLinksPolicy")
    $Return += Invoke-CheckATPSafeLinksTrackingInternal -ATPPolicy $Collection.Get_Item("SafeLinksPolicy")
    $Return += Invoke-CheckATPSafeLinksTrackingOfficeApps -ATPPolicy $Collection.Get_Item("AtpPolicy")
    $Return += Invoke-CheckATPSafeLinksDeliverMessageAfterScan -ATPPolicy $Collection.Get_Item("SafeLinksPolicy")
    $Return += Invoke-CheckATPSafeLinksBypass -TransportRules $Collection.Get_Item("TransportRules")

    Write-Host "$(Get-Date) Analysis - ATP - SafeAttachments"
    $Return += Invoke-CheckATPSafeAttachmentsBypass -TransportRules $Collection.Get_Item("TransportRules")

    Write-Host "$(Get-Date) Analysis - ATP - Antiphishing"
    $Return += Invoke-CheckATPPhishThreshold -AntiPhishPolicy $Collection.Get_Item("AntiPhishPolicy")
    $Return += Invoke-CheckATPPhishDomainImpAction -AntiPhishPolicy $Collection.Get_Item("AntiPhishPolicy") 
    $Return += Invoke-CheckATPPhishUserImpAction -AntiPhishPolicy $Collection.Get_Item("AntiPhishPolicy")
    $Return += Invoke-CheckATPPhishMIAction -AntiPhishPolicy $Collection.Get_Item("AntiPhishPolicy")
    $Return += Invoke-CheckAntiPhishPolicy -AntiPhishPolicy $Collection.Get_Item("AntiPhishPolicy")

    Write-Host "$(Get-Date) Analysis - Sender Authentication - DKIM"
    $Return += Invoke-CheckDKIMSigning -DkimSigningConfigs $Collection.Get_Item("DkimSigningConfig") -AcceptedDomains $Collection.Get_Item("AcceptedDomains")

    Return $Return
}

Function Invoke-ORCASummary
{
    <#
 
        DETERMINE CHECK RESULTS
 
        To determine the final PASS/FAIL result of the check based on the results
        To add an affected object property which can be used in tables
 
    #>

    Param(
        $Results,
        $Checks
    )

    ForEach($Check in $Checks)
    {    
        $CheckResults = @($Results | Where-Object {$_.Control -eq $Check.Control})

        $FailResults = @($CheckResults | Where-Object {$_.Result -eq "Fail"})
        $PassResults = @($CheckResults | Where-Object {$_.Result -eq "Pass"})

        $Objects = @()
        ForEach($CheckResult in $CheckResults) {
            $TmpObject = New-Object -TypeName PSObject -Property @{
                ConfigItem=$($CheckResult.ConfigItem)
                ConfigData=$($CheckResult.ConfigData)
                Result=$($CheckResult.Result)
            }

            # Add object for OPV checks
            If($Check.CheckType -eq [CheckType]::ObjectPropertyValue)
            {
                $TmpObject | Add-Member -NotePropertyName Object -NotePropertyValue $($CheckResult.Object)
            }

            $Objects += $TmpObject
        }

        If($($FailResults.Count) -eq 0)
        {
            $Result = "Pass"
        }
        else {
            $Result = "Fail"
        }

        $Check | Add-Member -NotePropertyName FailCount -NotePropertyValue $($FailResults.Count)
        $Check | Add-Member -NotePropertyName PassCount -NotePropertyValue $($PassResults.Count)
        $Check | Add-Member -NotePropertyName Result -NotePropertyValue $($Result)
        $Check | Add-Member -NotePropertyName Objects -NotePropertyValue $($Objects)

    }

    Return $Checks

}

Function Get-ORCAHtmlOutput
{
    <#
 
        OUTPUT GENERATION / Header
 
    #>

    Param(
        $Collection,
        $Checks,
        $VersionCheck
    )

    Write-Host "$(Get-Date) Generating Output" -ForegroundColor Green

    # Obtain the tenant domain and date for the report
    $TenantDomain = ($Collection["AcceptedDomains"] | Where-Object {$_.InitialDomain -eq $True}).DomainName
    $ReportDate = $(Get-Date -format 'dd-MMM-yyyy HH:mm')

    # Summary
    $RecommendationCount = $($Checks | Where-Object {$_.Result -eq "Fail"}).Count
    $OKCount = $($Checks | Where-Object {$_.Result -eq "Pass"}).Count

    # Misc
    $ReportTitle = "Office 365 ATP Recommended Configuration Analyzer Report"

    # Area icons
    $AreaIcon = @{}
    $AreaIcon["Default"] = "fas fa-user-cog"
    $AreaIcon["Content Filter Policies"] = "fas fa-scroll"
    $AreaIcon["Malware Filter Policy"] = "fas fa-biohazard"
    $AreaIcon["Zero Hour Autopurge"] = "fas fa-trash"
    $AreaIcon["DKIM"] = "fas fa-file-signature"
    $AreaIcon["Transport Rules"] = "fas fa-list"
    $AreaIcon["Transport Rules"] = "fas fa-list"

    # Output start
    $output = "<!doctype html>
    <html lang='en'>
    <head>
        <!-- Required meta tags -->
        <meta charset='utf-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
 
        <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css' crossorigin='anonymous'>
        <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>
 
 
        <script src='https://code.jquery.com/jquery-3.3.1.slim.min.js' integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo' crossorigin='anonymous'></script>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js' integrity='sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1' crossorigin='anonymous'></script>
        <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js' integrity='sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM' crossorigin='anonymous'></script>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.js'></script>
 
        <style>
        .table-borderless td,
        .table-borderless th {
            border: 0;
        }
        .bd-callout {
            padding: 1.25rem;
            margin-top: 1.25rem;
            margin-bottom: 1.25rem;
            border: 1px solid #eee;
            border-left-width: .25rem;
            border-radius: .25rem
        }
         
        .bd-callout h4 {
            margin-top: 0;
            margin-bottom: .25rem
        }
         
        .bd-callout p:last-child {
            margin-bottom: 0
        }
         
        .bd-callout code {
            border-radius: .25rem
        }
         
        .bd-callout+.bd-callout {
            margin-top: -.25rem
        }
         
        .bd-callout-info {
            border-left-color: #5bc0de
        }
         
        .bd-callout-info h4 {
            color: #5bc0de
        }
         
        .bd-callout-warning {
            border-left-color: #f0ad4e
        }
         
        .bd-callout-warning h4 {
            color: #f0ad4e
        }
         
        .bd-callout-danger {
            border-left-color: #d9534f
        }
         
        .bd-callout-danger h4 {
            color: #d9534f
        }
 
        .bd-callout-success {
            border-left-color: #00bd19
        }
 
        </style>
 
        <title>$($ReportTitle)</title>
 
    </head>
    <body class='app header-fixed bg-light'>
 
        <nav class='navbar fixed-top navbar-light bg-white p-3 border-bottom'>
            <div class='container-fluid'>
                <div class='col-sm' style='text-align:left'>
                    <div class='row'><div><i class='fas fa-binoculars'></i></div><div class='ml-3'><strong>ORCA</strong></div></div>
                </div>
                <div class='col-sm' style='text-align:center'>
                    <strong>$($TenantDomain)</strong>
                </div>
                <div class='col-sm' style='text-align:right'>
                    $($ReportDate)
                </div>
            </div>
        </nav>
 
            <div class='app-body p-3'>
            <main class='main'>
                <!-- Main content here -->
                <div class='container' style='padding-top:50px;'></div>
                <div class='card'>
                         
                        <div class='card-body'>
                            <h2 class='card-title'>$($ReportTitle)</h5>
                            <strong>Version $($VersionCheck.Version.ToString())</strong>
                            <p>This report details any tenant configuration changes recommended within your tenant.</p>"


        <#
 
                OUTPUT GENERATION / Version Warning
 
        #>

                                
        If($VersionCheck.Updated -eq $False) {

            $Output += "
            <div class='alert alert-danger pt-2' role='alert'>
                ORCA is out of date. You're running version $($VersionCheck.Version) but version $($VersionCheck.GalleryVersion) is available! Run Update-Module ORCA to get the latest definitions!
            </div>
             
            "


        }


                        $Output += "</div>
                </div>"




    <#
 
        OUTPUT GENERATION / Summary cards
 
    #>


    $Output += "
 
                <div class='row p-3'>
 
                <div class='col d-flex justify-content-center text-center'>
                    <div class='card text-white bg-warning mb-3' style='width: 18rem;'>
                        <div class='card-header'><h5>Recommendations</h4></div>
                        <div class='card-body'>
                        <h2>$($RecommendationCount)</h3>
                        </div>
                    </div>
                </div>
 
                <div class='col d-flex justify-content-center text-center'>
                    <div class='card text-white bg-success mb-3' style='width: 18rem;'>
                        <div class='card-header'><h5>OK</h4></div>
                        <div class='card-body'>
                        <h2>$($OKCount)</h5>
                        </div>
                    </div>
                </div>
 
            </div>
 
    "


    <#
     
        OUTPUT GENERATION / Summary
 
    #>


    $Output += "
    <div class='card m-3'>
        <div class='card-header'>
            Summary
        </div>
        <div class='card-body'>"



    $Output += "<h5>Areas</h1>
            <table class='table table-borderless'>"

    ForEach($Area in ($Checks | Group-Object Area))
    {

        $Pass = @($Area.Group | Where-Object {$_.Result -eq "Pass"}).Count
        $Fail = @($Area.Group | Where-Object {$_.Result -ne "Pass"}).Count
        $Icon = $AreaIcon[$Area.Name]
        If($Null -eq $Icon) { $Icon = $AreaIcon["Default"]}

        $Output += "
        <tr>
            <td width='20'><i class='$Icon'></i>
            <td><a href='`#$($Area.Name)'>$($Area.Name)</a></td>
            <td align='right'>
                <span class='badge badge-warning' style='padding:15px'>$($Fail)</span>
                <span class='badge badge-success' style='padding:15px'>$($Pass)</span>
            </td>
        </tr>
        "

    }

    $Output+="</table>
        </div>
    </div>
    "


    <#
 
        OUTPUT GENERATION / Zones
 
    #>


    ForEach ($Area in ($Checks | Group-Object Area)) {

        # Write the top of the card
        $Output += "
        <div class='card m-3'>
            <div class='card-header'>
            <a name='$($Area.Name)'>$($Area.Name)</a>
            </div>
            <div class='card-body'>"


        # Each check
        ForEach ($Check in $Area.Group) {

            $Output += "
                <h5>$($Check.Name)</h5>"


                    If($Check.Result -eq "Pass") {
                        $CalloutType = "bd-callout-success"
                        $BadgeType = "badge-success"
                        $BadgeName = "OK"
                        $Icon = "fas fa-thumbs-up"
                        $Title = $Check.PassText
                    } Else {
                        $CalloutType = "bd-callout-warning"
                        $BadgeType = "badge-warning"
                        $BadgeName = "Improvement"
                        $Icon = "fas fa-thumbs-down"
                        $Title = $Check.FailRecommendation
                    }

                    $Output += "
                     
                        <div class='bd-callout $($CalloutType) b-t-1 b-r-1 b-b-1 p-3'>
                            <div class='container-fluid'>
                                <div class='row'>
                                    <div class='col-1'><i class='$($Icon)'></i></div>
                                    <div class='col-8'><h5>$($Title)</h5></div>
                                    <div class='col' style='text-align:right'><h5><span class='badge $($BadgeType)'>$($BadgeName)</span></h5></div>
                                </div>"


                        if($Check.Importance) {

                                $Output +="
                                <div class='row p-3'>
                                    <div><p>$($Check.Importance)</p></div>
                                </div>"


                        }
                        
                        If($Check.ExpandResults -eq $True) {

                            # We should expand the results by showing a table of Config Data and Items
                            $Output +="<h6>Effected objects</h6>
                            <div class='row pl-2 pt-3'>
                                <table class='table'>
                                    <thead class='border-bottom'>
                                        <tr>"


                            If($Check.CheckType -eq [CheckType]::ObjectPropertyValue)
                            {
                                # Object, property, value checks need three columns
                                $Output +="
                                <th>$($Check.ObjectType)</th>
                                <th>$($Check.ItemName)</th>
                                <th>$($Check.DataType)</th>
                                "
    
                            }
                            Else
                            {
                                $Output +="
                                <th>$($Check.ItemName)</th>
                                <th>$($Check.DataType)</th>
                                "
     
                            }

                            $Output +="
                                            <th style='width:50px'></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                            "


                            ForEach($o in $Check.Objects)
                            {
                                if($o.Result -eq "Pass") {
                                    $oicon="fas fa-check-circle text-success"
                                } Else{
                                    $oicon="fas fa-times-circle text-danger"
                                }

                                $Output += "
                                <tr>
                                "


                                If($Check.CheckType -eq [CheckType]::ObjectPropertyValue)
                                {
                                    # Object, property, value checks need three columns
                                    $Output += "
                                        <td>$($o.Object)</td>
                                        <td>$($o.ConfigItem)</td>
                                        <td>$($o.ConfigData)</td>
                                    "

                                }
                                Else 
                                {
                                    $Output += "
                                        <td>$($o.ConfigItem)</td>
                                        <td>$($o.ConfigData)</td>
                                    "

                                }

                                $Output += "
                                    <td><i class='$($oicon)'></i></td>
                                </tr>
                                "

                            }

                            $Output +="
                                    </tbody>
                                </table>"

                                
                            # If any links exist
                            If($Check.Links)
                            {
                                $Output += "
                                <table>"

                                ForEach($Link in $Check.Links.Keys) {
                                    $Output += "
                                    <tr>
                                    <td style='width:40px'><i class='fas fa-external-link-alt'></i></td>
                                    <td><a href='$($Check.Links[$Link])'>$Link</a></td>
                                    <tr>
                                    "

                                }
                                $Output += "
                                </table>
                                "

                            }

                            $Output +="
                            </div>"


                        }

                        $Output += "
                            </div>
                        </div> "

        }            

        # End the card
        $Output+=   "
            </div>
        </div>"


    }
    <#
 
        OUTPUT GENERATION / Footer
 
    #>


    $Output += "
            </main>
            </div>
 
            <footer class='app-footer'>
            <p><center>Bugs? Issues? Suggestions? <a href='https://github.com/cammurray/orca'>GitHub!</a><center></p>
            </footer>
        </body>
    </html>"


    Return $Output
}

function Invoke-ORCAVersionCheck
{
    Param(
        $Terminate
    )

    Write-Host "$(Get-Date) Performing ORCA Version check..."

    $ORCAVersion = (Get-Module ORCA | Sort-Object Version -Desc)[0].Version
    $PSGalleryVersion = (Find-Module ORCA -Repository PSGallery -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue).Version

    If($PSGalleryVersion -gt $ORCAVersion)
    {
        $Updated = $False
        If($Terminate)
        {
            Throw "ORCA is out of date. Your version is $ORCAVersion and the published version is $PSGalleryVersion. Run Update-Module ORCA or run Get-ORCAReport with -NoUpdate."
        }
        else {
            Write-Host "$(Get-Date) ORCA is out of date. Your version: $($ORCAVersion) published version is $($PSGalleryVersion)"
        }
    }
    else
    {
        $Updated = $True
    }

    Return New-Object -TypeName PSObject -Property @{
        Updated=$Updated
        Version=$ORCAVersion
        GalleryVersion=$PSGalleryVersion
    }
}

function Get-EXConnectionStatus
{
    # Perform check to determine if we are connected
    Try
    {
        Get-Mailbox -ResultSize:1 -WarningAction:SilentlyContinue | Out-Null
        Return $True
    }
    Catch
    {
        Return $False
    }
}

Function Get-ORCAReport
{
    <#
        .SYNOPSIS
        The Office 365 Recommended Configuration Analyzer (ORCA) Report Generator
 
        .DESCRIPTION
        Office 365 Recommended Configuration Analyzer (ORCA)
 
        The Get-ORCAReport command generates a HTML report based on recommended practices based
        on field experiences working with Exchange Online Protection and Advanced Threat Protection.
 
        Output report uses open source components for HTML formatting
        - bootstrap - MIT License - https://getbootstrap.com/docs/4.0/about/license/
        - fontawesome - CC BY 4.0 License - https://fontawesome.com/license/free
 
        Engine and report generation
        Cam Murray
        Field Engineer - Microsoft
        camurray@microsoft.com
         
        https://github.com/cammurray/orca
 
        .PARAMETER Report
 
        Optional.
 
        Full path to the report file that you want to generate. If this is not specified,
        a directory in your current users AppData is created called ORCA. Reports are generated in this
        directory in the following format:
 
        ORCA-tenantname-date.html
 
        .PARAMETER NoUpdate
 
        Optional.
 
        Switch that will tell the script not to exit in the event you are running an outdated rule
        definition. It's always recommended to be running the latest rule definition/module.
 
        .PARAMETER NoConnect
 
        Optional.
 
        Switch that will instruct ORCA not to connect and to use an already established connection
        to Exchange Online.
         
        .PARAMETER Collection
 
        Optional.
 
        For passing an already established collection object. Can be used for offline collection
        analysis.
 
        .EXAMPLE
 
        Get-ORCAReport
 
        .EXAMPLE
 
        Get-ORCAReport -Report myreport.html
 
        .EXAMPLE
 
        Get-ORCAReport -Report myreport.html -NoConnect
         
    #>

    Param(
        [CmdletBinding()]
        [Switch]$NoConnect,
        [Switch]$NoUpdate,
        $Collection,
        $Output
    )

    # Version check
    $VersionCheck = Invoke-ORCAVersionCheck

    # Unless -NoConnect specified (already connected), connect to Exchange Online
    If(!$NoConnect -and (Get-EXConnectionStatus) -eq $False) {
        Invoke-ORCAConnections
    }

    # Get the object of ORCA checks
    $Checks = Get-ORCACheckDefs

    # Get the collection in to memory. For testing purposes, we support passing the collection as an object
    If($Null -eq $Collection)
    {
        $Collection = Get-ORCACollection
    }

    # Get the results
    $Return = Get-ORCAResults -Collection $Collection

    # Put data in to Checks from the results
    $Checks = Invoke-ORCASummary -Results $Return -Checks $Checks

    # Generate HTML Output
    $HTMLReport = Get-ORCAHtmlOutput -Collection $Collection -Checks $Checks -VersionCheck $VersionCheck

    # Write to file

    If(!$Output)
    {
        $OutputDirectory = Get-ORCADirectory
        $Tenant = $(($Collection["AcceptedDomains"] | Where-Object {$_.InitialDomain -eq $True}).DomainName -split '\.')[0]
        $ReportFileName = "ORCA-$($tenant)-$(Get-Date -Format 'MMddyy').html"
        $Output = "$OutputDirectory\$ReportFileName"
    }

    $HTMLReport | Out-File -FilePath $Output
    Write-Host "$(Get-Date) Complete! Output is in $Output"
    Invoke-Expression $Output

}