File size: 60,574 Bytes
1c3834b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#####################################
# Rule Identifier:
#   IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS
#
# Description:
#   Checks the IAM policies that you create for Allow statements that grant permissions to all actions on all resources. 
#
# Reports on:
#   AWS::IAM::Policy
#
# Evaluates:
#   AWS CloudFormation
#
# Rule Parameters:
#   NA
#
# Scenarios:
# a) SKIP: when there are no IAM Policies present
# b) PASS: when all IAM Policies do not grant permissions to all actions on all resources
# c) FAIL: when any IAM Policies grant permissions to all actions on all resources
# d) SKIP: when metada has rule suppression for IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS

#
# Select all IAM Policy resources from incoming template (payload)
# 
let aws_iam_policies_no_statements_with_admin_access = Resources.*[ Type == 'AWS::IAM::Policy' 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS"
]

rule IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS when %aws_iam_policies_no_statements_with_admin_access !empty {
  let violations = Resources.*[
    Type == 'AWS::IAM::Policy' 
    some Properties.PolicyDocument.Statement[*] {
      some Action[*] == "*"
      Effect == "Allow"
      Resource == "*"
    }
  ]
  %violations empty
	<<
    Guard Rule Set: cis-top-20
    Controls: CIS.4,CIS.16    
    Violation: One or more IAM policies contain allow statements that grant permissions to all actions on all resources
    Fix: Remove policy statements that match {"Effect": "Allow", "Action": "*", "Resource": "*"}
  >>
} 

#####################################
# Rule Identifier:
#    REDSHIFT_CLUSTER_CONFIGURATION_CHECK
#
# Description:
#    Checks whether Amazon Redshift clusters have the specified settings (Encrypted Only)  
#
# Reports on:
#   AWS::Redshift::Cluster
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no Redshift Cluster resource present
# b) PASS: when Redshift Cluster resources have the Encrypted property set to true
# c) FAIL: when any Redshift Cluster resources do not have Encrypted property set (default false)
# d) FAIL: when any Redshift Cluster resources have Encrypted property set to false 
# e) SKIP: when metadata includes the suppression for rule REDSHIFT_CLUSTER_CONFIGURATION_CHECK

#
# Select all Redshift Cluster resources from incoming template (payload)
#
let redhshift_clusters_configuration_check = Resources.*[ Type == 'AWS::Redshift::Cluster' 
	Metadata.guard.SuppressedRules not exists or
    Metadata.guard.SuppressedRules.* != "REDSHIFT_CLUSTER_CONFIGURATION_CHECK"
]

rule REDSHIFT_CLUSTER_CONFIGURATION_CHECK when %redhshift_clusters_configuration_check !empty {
    %redhshift_clusters_configuration_check.Properties.Encrypted == true

    <<
    Guard Rule Set: cis-top-20
    Controls: CIS.5,CIS.6,CIS.13    
			Violation: Amazon Redshift configuration should have encryption enabled
			Fix: Set the Encrypted property to true 
    >>
}

#####################################
# Rule Identifier:
#    REDSHIFT_CLUSTER_MAINTENANCESETTINGS_CHECK
#
# Description:
#    Checks whether Amazon Redshift clusters have the specified maintenance settings (AllowVersionUpgrade, PreferredMaintenanceWindow, AutomatedSnapshotRetentionPeriod) 
#
# Reports on:
#   AWS::Redshift::Cluster
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no Redshift Cluster resource present
# b) PASS: when Redshift Cluster resources have properties PreferredMaintenanceWindow set, AllowVersionUpgrade either not set (default true) or set to true, and AutomatedSnapshotRetentionPeriod either not set (default 1 day) or set to greated than 0. 
# c) FAIL: when any Redshift Cluster resources do not have PreferredMaintenanceWindow property set
# d) FAIL: when any Redshift Cluster resources have AllowVersionUpgrade property set to false 
# e) FAIL: when any Redshift Cluster resources have AutomatedSnapshotRetentionPeriod property set to 0
# f) SKIP: when metadata includes the suppression for rule REDSHIFT_CLUSTER_MAINTENANCESETTINGS_CHECK

#
# Select all Redshift Cluster resources from incoming template (payload)
#
let redhshift_clusters_maintenancesettings_check = Resources.*[ Type == 'AWS::Redshift::Cluster' 
	Metadata.guard.SuppressedRules not exists or
    Metadata.guard.SuppressedRules.* != "REDSHIFT_CLUSTER_MAINTENANCESETTINGS_CHECK"
]

rule REDSHIFT_CLUSTER_MAINTENANCESETTINGS_CHECK when %redhshift_clusters_maintenancesettings_check !empty {
    %redhshift_clusters_maintenancesettings_check.Properties.PreferredMaintenanceWindow exists
    
    %redhshift_clusters_maintenancesettings_check.Properties.AllowVersionUpgrade not exists or 
    %redhshift_clusters_maintenancesettings_check.Properties.AllowVersionUpgrade == true


    %redhshift_clusters_maintenancesettings_check.Properties.AutomatedSnapshotRetentionPeriod not exists or 
    %redhshift_clusters_maintenancesettings_check.Properties.AutomatedSnapshotRetentionPeriod > 0

    <<
    Guard Rule Set: cis-top-20
    Controls: CIS.5    
			Violation: Amazon Redshift maintenance settings must be configured
			Fix: set the PreferredMaintenanceWindow property, remove the AllowVersionUpgrade property (default true) or set it to true, and remove the AutomatedSnapshotRetentionPeriod property (default 1 day) or set it to greated than 0. 
    >>
}

#####################################
# Rule Identifier:
#    API_GW_EXECUTION_LOGGING_ENABLED
#
# Description:
#    Checks that all methods in Amazon API Gateway stage has logging enabled. The rule is NON_COMPLIANT if logging is not enabled.
#
# Reports on:
#    AWS::ApiGateway::Stage
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no API GW Stage present
# b) PASS: when all API GW Stage Methods have logginglevel set to "ERROR" OR "INFO"
# c) FAIL: when API GW Domain Names doesn't have logginglevel set to "ERROR" OR "INFO"
# d) SKIP: when metadata includes the suppression for rule API_GW_EXECUTION_LOGGING_ENABLED

let api_gw_execution_logging_enabled = Resources.*[ Type == 'AWS::ApiGateway::Stage'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "API_GW_EXECUTION_LOGGING_ENABLED"
]

rule API_GW_EXECUTION_LOGGING_ENABLED when %api_gw_execution_logging_enabled !empty {
  when %api_gw_execution_logging_enabled.Properties.MethodSettings !empty {
    %api_gw_execution_logging_enabled.Properties.MethodSettings.*.LoggingLevel == "ERROR" OR
    %api_gw_execution_logging_enabled.Properties.MethodSettings.*.LoggingLevel == "INFO"
    <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6    
      Violation: Logging Level for API GW Method Setting not set
      Fix: API GW Stage Method Setting logging level must be set to "ERROR" or "INFO"
    >>
  }
}

#####################################
# Rule Identifier:
#    CLOUD_TRAIL_CLOUD_WATCH_LOGS_ENABLED
#
# Description:
#   Checks whether AWS CloudTrail trails are configured to send logs to Amazon CloudWatch logs.
#   The trail is non-compliant if the CloudWatchLogsLogGroupArn property of the trail is empty.
#
# Reports on:
#    AWS::CloudTrail::Trail
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no CloudTrail Trails present
# b) PASS: when all CloudTrail Trails have CloudWatchLogsLogGroupArn parameter set
# c) FAIL: when there are CloudTrail Trails with CloudWatchLogsLogGroupArn property not present
# d) SKIP: when metada has rule suppression for CLOUD_TRAIL_CLOUD_WATCH_LOGS_ENABLED

#
# Select all CloudTrail Trail resources from incoming template (payload)
#
let cloudtrail_trails_cw_logs_enabled = Resources.*[ Type == 'AWS::CloudTrail::Trail'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUD_TRAIL_CLOUD_WATCH_LOGS_ENABLED"
]

rule CLOUD_TRAIL_CLOUD_WATCH_LOGS_ENABLED when %cloudtrail_trails_cw_logs_enabled !empty {
  %cloudtrail_trails_cw_logs_enabled.Properties.CloudWatchLogsLogGroupArn exists
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6    
    Violation: CloudTrail Trail should have logs exported to cloudwatch logs.
    Fix: Set the CloudWatchLogsLogGroupArn parameter to enable exporting to CloudWatch Logs.
  >>
}

#####################################
# Rule Identifier:
#    CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED
#
# Description:
#   Checks whether AWS CloudTrail creates a signed digest file with logs.
#
# Reports on:
#    AWS::CloudTrail::Trail
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no CloudTrail Trails present
# b) PASS: when all CloudTrail Trails have EnableLogFileValidation parameter set true
# c) FAIL: when there are CloudTrail Trails with the EnableLogFileValidation parameter is set to false
# d) FAIL: when there are CloudTrail Trails with EnableLogFileValidation property not present
# e) SKIP: when metada has rule suppression for CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED


#
# Select all CloudTrail Trail resources from incoming template (payload)
#
let cloudtrail_trails_log_validation = Resources.*[ Type == 'AWS::CloudTrail::Trail'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED"
]

rule CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED when %cloudtrail_trails_log_validation !empty {
  %cloudtrail_trails_log_validation.Properties.EnableLogFileValidation EXISTS
  %cloudtrail_trails_log_validation.Properties.EnableLogFileValidation == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6    
    Violation: CloudTrail Trail should have Log File Validation enabled.
    Fix: Set the EnableLogFileValidation parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    CLOUDTRAIL_S3_DATAEVENTS_ENABLED
#
# Description:
#   Checks whether at least one AWS CloudTrail trail is logging Amazon S3 data events for all S3 buckets.
#
# Reports on:
#    AWS::CloudTrail::Trail
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no CloudTrail Trails present
# b) PASS: when all CloudTrail Trails have EventSelectors parameter set
# c) FAIL: when there are CloudTrail Trails with EventSelectors property not present
# d) SKIP: when metada has rule suppression for CLOUDTRAIL_S3_DATAEVENTS_ENABLED

#
# Select all CloudTrail Trail resources from incoming template (payload)
#
let cloudtrail_trails_dataevents = Resources.*[ Type == 'AWS::CloudTrail::Trail'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUDTRAIL_S3_DATAEVENTS_ENABLED"
]

rule CLOUDTRAIL_S3_DATAEVENTS_ENABLED when %cloudtrail_trails_dataevents !empty {
  %cloudtrail_trails_dataevents.Properties.EventSelectors EXISTS
  some %cloudtrail_trails_dataevents.Properties.EventSelectors.* == {DataResources:[{Type:'AWS::S3::Object',Values:['arn:aws:s3:::']}],IncludeManagementEvents:true,ReadWriteType:'All'}
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6    
    Violation: CloudTrail Trail should have data events being logged.
    Fix: Set the EventSelectors parameter to enable encryption. The value can be an alias name prefixed by "alias/", a fully specified ARN to an alias, a fully specified ARN to a key, or a globally unique identifier.
  >>
}

#####################################
# Rule Identifier:
#    CLOUDWATCH_ALARM_ACTION_CHECK
#
# Description:
#   Checks whether CloudWatch alarms have at least one alarm action,
#   one Insufficient Data Actions action, or one OK action enabled.
#
# Reports on:
#    AWS::Logs::LogGroup
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no cloudwatch alarm resources present
# b) PASS: when resource Metadata is set with rule suppressed
# c) PASS: when all cloudwatch alarm resources property Alarm Actions, Insufficient Data Actions, or OK Action set
# d) FAIL: when all cloudwatch alarms resources property Alarm Actions, Insufficient Data Actions, or OK Action are not set with valid value
# e) SKIP: when metada has rule suppression for CLOUDWATCH_ALARM_ACTION_CHECK

#
# Select all cloudwatch logs log group resources from incoming template (payload)
#
let cloudwatch_alarm_action_check = Resources.*[ Type == 'AWS::CloudWatch::Alarm'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUDWATCH_ALARM_ACTION_CHECK"
]

rule CLOUDWATCH_ALARM_ACTION_CHECK when %cloudwatch_alarm_action_check !empty {
  %cloudwatch_alarm_action_check.Properties.AlarmActions exists or
  %cloudwatch_alarm_action_check.Properties.OKActions exists or
  %cloudwatch_alarm_action_check.Properties.InsufficientDataActions exists

  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6,CIS.16    
    Violation: CloudWatch Alarms should have at least one Alarm Action, one Insufficient Data Actions action, or one OK Action enabled.
    Fix: Set one Alarm Action, one Insufficient Data Actions action, or one OK Action on the CloudWatch Alarm resource.
  >>
}


## Config Rule Name : elb-logging-enabled
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/elb-logging-enabled.html"

#####################################
# Rule Identifier:
#    S3_BUCKET_LOGGING_ENABLED
#
# Description:
#   Checks whether logging is enabled for your S3 buckets.
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources Logging Configuration exists
# c) FAIL: when all S3 resources have Logging Configuration is not set
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_LOGGING_ENABLED

#
# Select all S3 resources from incoming template (payload)
#

let s3_buckets_bucket_logging_enabled = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_LOGGING_ENABLED"
]

rule S3_BUCKET_LOGGING_ENABLED when %s3_buckets_bucket_logging_enabled  !empty {
  %s3_buckets_bucket_logging_enabled.Properties.LoggingConfiguration exists
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.6    
    Violation: S3 Bucket Logging needs to be configured to enable logging.
    Fix: Set the S3 Bucket property LoggingConfiguration to start logging into S3 bucket.
  >>
}

#####################################
# Rule Identifier:
#    DMS_REPLICATION_NOT_PUBLIC
#
# Description:
#   Checks whether AWS Database Migration Service replication instances are not set to allow public.
#
# Reports on:
#    AWS::DMS::ReplicationInstance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there is no DMS Replication Instance present
# b) FAIL: When DMS Replication Instance is present and PubliclyAccessible property is set to true
# c) PASS: When DMS Replication Instance is present and PubliclyAccessible property is set to false
# c) PASS: When DMS Replication Instance is present and PubliclyAccessible property is not set
# d) SKIP: when metada has rule suppression for DMS_REPLICATION_NOT_PUBLIC

#
# Select all Redshift cluster resources from incoming template
#

let dms_replication_instances = Resources.*[ Type == 'AWS::DMS::ReplicationInstance'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "DMS_REPLICATION_NOT_PUBLIC"
]

rule DMS_REPLICATION_NOT_PUBLIC when %dms_replication_instances !empty {
  %dms_replication_instances.Properties.PubliclyAccessible exists
  %dms_replication_instances.Properties.PubliclyAccessible == false
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    Violation: AWS Database Migration Service replication instances should not be public.
    Fix: Set the DMS Replication Instance property PubliclyAccessible parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    EC2_INSTANCE_NO_PUBLIC_IP
#
# Description:
#    Checks whether Amazon Elastic Compute Cloud (Amazon EC2) instances have a public IP association. 
#
# Reports on:
#    AWS::EC2::Instance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when no EC2 Instance resources are present
# b) SKIP: when no EC2 Instances have network interfaces defined
# c) PASS: when no EC2 Instances with network interfaces have associated public IP addresses
# d) FAIL: when any EC2 Instances with network interfaces have associated public IP addresses
# e) SKIP: hen metadata includes the suppression for rule EC2_INSTANCE_NO_PUBLIC_IP

#
# Select all EC2 Instance resources from incoming template (payload)
#
let ec2_instances_no_public_ip = Resources.*[Type == 'AWS::EC2::Instance'
	Properties.NetworkInterfaces[*] !empty 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "EC2_INSTANCE_NO_PUBLIC_IP"
]

rule EC2_INSTANCE_NO_PUBLIC_IP when %ec2_instances_no_public_ip !empty {
	%ec2_instances_no_public_ip.Properties.NetworkInterfaces[*] {
		AssociatePublicIpAddress !exists OR 
		AssociatePublicIpAddress == false
		<<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    	Violation: EC2 Instances cannot have public IP addresses associated with their network interfaces 
    	Fix: remove the AssociatePublicIpAddress property from NetworkInterfaces list or set it to false
  	>>
	}
}

#####################################
# Rule Identifier:
#    ELASTICSEARCH_IN_VPC_ONLY
#
# Description:
#   Elasticsearch domains must be in a VPC
#
# Reports on:
#    AWS::Elasticsearch::Domain
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there is no elasticsearch domain present
# b) FAIL: when elasticsearch domain does not have VPCOptions or Endpoint properties
# c) PASS: when elasticsearch domain has VPCOptions or Endpoint properties
# d) SKIP: when metada has rule suppression for ELASTICSEARCH_IN_VPC_ONLY

#
# Select all elasticsearch domains from incoming template
#
let elasticsearch_domains_vpc_required = Resources.*[ Type == 'AWS::Elasticsearch::Domain'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "ELASTICSEARCH_IN_VPC_ONLY"
]

rule ELASTICSEARCH_IN_VPC_ONLY when %elasticsearch_domains_vpc_required !empty {
  %elasticsearch_domains_vpc_required.Properties.VPCOptions EXISTS
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
    Violation: Elasticsearch domains must be in a VPC.
    Fix: Provide VPCOptions object to enable opensearch to function in a VPC.
  >>
}
## Config Rule Name : emr-master-no-public-ip
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/emr-master-no-public-ip.html"

#####################################
# Rule Identifier:
#    INCOMING_SSH_DISABLED
#
# Description:
#    Checks if the incoming SSH traffic for the security groups is accessible. 
#
# Reports on:
#    AWS::EC2::SecurityGroup
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when no Security Group resources are present
# b) SKIP: when no SSH ingress is defined (port 22)
# c) PASS: when all Security Groups resources restrict the IP address of the incoming SSH traffic
# d) FAIL: when a Security Group allows SSH traffic from any IP address (0.0.0.0/0). 
# e) SKIP: hen metadata includes the suppression for rule INCOMING_SSH_DISABLED

#
# Select all Security Group resources from incoming template (payload)
#
let aws_security_groups_restricted_ssh = Resources.*[ 
	Type == 'AWS::EC2::SecurityGroup'
	some Properties.SecurityGroupIngress[*] {
		ToPort == 22
		FromPort == 22
		IpProtocol == "tcp"
	}
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "INCOMING_SSH_DISABLED"
]

rule INCOMING_SSH_DISABLED when %aws_security_groups_restricted_ssh !empty {
	%aws_security_groups_restricted_ssh.Properties.SecurityGroupIngress[*] != {CidrIp:"0.0.0.0/0", ToPort:22, FromPort:22, IpProtocol:"tcp"}
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.11,CIS.12    
    Violation: IP addresses of the incoming SSH traffic in the security groups are restricted (CIDR other than 0.0.0.0/0)
    Fix: set SecurityGroupIngress.CidrIp property to a more restrictive CIDR than 0.0.0.0/0
  >>
}

#####################################
# Rule Identifier:
#    EC2_INSTANCES_IN_VPC
#
# Description:
#    Checks if your EC2 instances belong to a virtual private cloud (VPC).
#
# Reports on:
#    AWS::EC2::Instance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no EC2 resource present
# b) PASS: when all EC2 resources have the SubnetId property set
# c) FAIL: when any EC2 resources do not have the SubnetId property set
# d) SKIP: when metadata includes the suppression for rule EC2_INSTANCES_IN_VPC

#
# Select all ECS Instance resources from incoming template (payload)
#
let ec2_instances_in_vpc = Resources.*[ Type == 'AWS::EC2::Instance' 
  Metadata.guard.SuppressedRules not exists or 
  Metadata.guard.SuppressedRules.* != "EC2_INSTANCES_IN_VPC"
]

rule EC2_INSTANCES_IN_VPC when %ec2_instances_in_vpc !empty {
  %ec2_instances_in_vpc.Properties.SubnetId !empty
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
  	Violation: EC2 Instances must belong to a VPC
  	Fix: set the SubnetId property to a subnet ID
  >>
}

#####################################
# Rule Identifier:
#    LAMBDA_FUNCTION_PUBLIC_ACCESS_PROHIBITED
#
# Description:
#    Checks if the AWS Lambda function policy attached to the Lambda resource prohibits public access.
#
# Reports on:
#    AWS::Lambda::Permission
#    AWS::Lambda::LayerVersionPermission
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when no AWS Lambda permission policies are present
# b) PASS: when all AWS Lambda permission policies prohibit public access
# c) FAIL: when any AWS Lambda permission policies allow public access
# d) SKIP: hen metadata includes the suppression for rule LAMBDA_FUNCTION_PUBLIC_ACCESS_PROHIBITED

#
# Select all AWS Lambda Permission resources from incoming template (payload)
#
let aws_lambda_permissions_public_access_prohibited = Resources.*[
  Type in [ /AWS::Lambda::Permission/,
    /AWS::Lambda::LayerVersionPermission/ ]
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "LAMBDA_FUNCTION_PUBLIC_ACCESS_PROHIBITED"
]

rule LAMBDA_FUNCTION_PUBLIC_ACCESS_PROHIBITED when %aws_lambda_permissions_public_access_prohibited !empty {

  # Lambda permission policy where principal is an account id
  %aws_lambda_permissions_public_access_prohibited {
    Type == 'AWS::Lambda::Permission'
    Properties {
      Principal in [ /^\d{12}$/, "AWS::AccountId" ]
      OR Principal > 0
    }
  }

  # Lambda permission policy where principal is a service (not s3)
  OR %aws_lambda_permissions_public_access_prohibited {
    Type == 'AWS::Lambda::Permission'
    Properties {
      Principal != 's3.amazonaws.com'
      PrincipalOrgID !empty
      OR SourceAccount exists
      OR SourceArn !empty
      <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
        Violation: All Lambda permission policies attached to Lambda resources must prohibit public access.
        Fix: Limit permission policies by setting the Principal property to an account ID,
        or limiting a service principal by setting the SourceArn, SourceAccount, or PrincipalOrgID properties.
      >>
    }
  }

  # Lambda permission policy where principal is s3 service
  OR %aws_lambda_permissions_public_access_prohibited {
    Type == 'AWS::Lambda::Permission'
    Properties {
      Principal == 's3.amazonaws.com'
      PrincipalOrgID !empty
      OR SourceAccount exists
      <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
        Violation: All Lambda permission policies attached to Lambda resources must prohibit public access.
        Fix: Limit permission policies by setting the Principal property to an account ID,
        or for S3 as the principal specify either a SourceAccount or PrincipalOrgID.
        Note: It is possible for an S3 bucket to be deleted by its owner and recreated by another account.
      >>
    }
  }

  # Lambda layer version permission policies
  OR %aws_lambda_permissions_public_access_prohibited {
    Type == 'AWS::Lambda::LayerVersionPermission'
    Properties {
      OrganizationId !empty
      OR Principal in [ /^\d{12}$/, "AWS::AccountId" ]
      OR Principal > 0
      <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
        Violation: All Lambda permission policies attached to Lambda resources must prohibit public access.
        Fix: For Lambda layer version permission policies, either limit permissions by the OrganizationId property
        or set the Principal property to an account ID rather than using a wildcard (*).
      >>
    }
  }
}

#####################################
# Rule Identifier:
#    LAMBDA_INSIDE_VPC
#
# Description:
#    Checks whether an AWS Lambda function is allowed access to an Amazon Virtual Private Cloud.
#
# Reports on:
#    AWS::Lambda::Function
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when no AWS Lambda functions are present
# b) PASS: when all AWS Lambda functions are VPC enabled
# c) FAIL: when any AWS Lambda functions are not VPC enabled
# d) SKIP: hen metadata includes the suppression for rule LAMBDA_INSIDE_VPC

#
# Select all AWS Lambda Function resources from incoming template (payload)
#
let aws_lambda_functions_inside_vpc = Resources.*[ Type == 'AWS::Lambda::Function' 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "LAMBDA_INSIDE_VPC"
]

rule  LAMBDA_INSIDE_VPC when %aws_lambda_functions_inside_vpc !empty {
  %aws_lambda_functions_inside_vpc.Properties.VpcConfig.SecurityGroupIds !empty
  %aws_lambda_functions_inside_vpc.Properties.VpcConfig.SubnetIds !empty
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12    
    Violation:  All AWS Lambda Functions must be configured with access to a VPC
    Fix: set the VpcConfig.SecurityGroupIds and VpcConfig.SubnetIds parameters with a list of security groups and subnets.
    Lambda creates an elastic network interface for each combination of security group and subnet in the function's VPC configuration.
  >>
}

#####################################
# Rule Identifier:
#    RDS_INSTANCE_PUBLIC_ACCESS_CHECK
#
# Description:
#    Checks if an RDS instances has Publicly Accessible not set.
#
# Reports on:
#    AWS::RDS::DBInstance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no RDS instances present
# b) PASS: when all RDS instances have PubliclyAccessible set to true
# c) FAIL: when all RDS instances have PubliclyAccessible set to false
# d) FAIL: when there are RDS instances with PubliclyAccessible property is not present
# e) SKIP: when metadata includes the suppression for rule RDS_INSTANCE_PUBLIC_ACCESS_CHECK

#
# Select all RDS instance resources from incoming template (payload)
#
let aws_rds_instances_not_public = Resources.*[ Type == 'AWS::RDS::DBInstance'
  Properties.SourceDBInstanceIdentifier !exists
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "RDS_INSTANCE_PUBLIC_ACCESS_CHECK"
]

rule RDS_INSTANCE_PUBLIC_ACCESS_CHECK when %aws_rds_instances_not_public !empty {
  # ALL RDS instances must have PubliclyAccessible set to false
  %aws_rds_instances_not_public.Properties.PubliclyAccessible == false
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    Violation: All RDS instances must not be publicly accessible.
    Fix: Set the PubliclyAccessible to false.
  >>
}

#####################################
# Rule Identifier:
#    REDSHIFT_CLUSTER_PUBLIC_ACCESS_CHECK
#
# Description:
#   Redshift cluster should not be publicly accessible on the internet.
#
# Reports on:
#    AWS::EKS::Cluster
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there is no Redshift cluster present
# b) PASS: when Redshift Cluster resources do not have the publiclyAccessible property set (default false)
# c) PASS: when Redshift Cluster resources have the PubliclyAccessible property set to false
# d) FAIL: when any Redshift Cluster resources have the PubliclyAccessible property set to true
# e) SKIP: when metada includes the suppression for rule REDSHIFT_CLUSTER_PUBLIC_ACCESS_CHECK

#
# Select all Redshift cluster resources from incoming template
#

let aws_redshift_clusters_resources_public_access_check = Resources.*[ Type == 'AWS::Redshift::Cluster'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "REDSHIFT_CLUSTER_PUBLIC_ACCESS_CHECK"
]


rule REDSHIFT_CLUSTER_PUBLIC_ACCESS_CHECK when %aws_redshift_clusters_resources_public_access_check !empty {
    %aws_redshift_clusters_resources_public_access_check.Properties.PubliclyAccessible  not exists or
    %aws_redshift_clusters_resources_public_access_check.Properties.PubliclyAccessible == false

  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    Violation: Redshift cluster should not be available to public.
    Fix: Set the Redshift property PubliclyAccessible parameter to false.
  >>
}

#####################################
# Rule Identifier:
#    RESTRICTED_INCOMING_TRAFFIC
#
# Description:
#    Checks if the security groups in use do not allow unrestricted incoming TCP traffic to the specified ports. 
#
# Reports on:
#    AWS::EC2::SecurityGroup
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no Security Groups resource present
# b) SKIP when there are no TCP or UDP ingress rules
# c) PASS: when all Security Groups do no allow any of the restricted common ports
# d) FAIL: when a Security Group allows any of the restricted common ports
# e) SKIP: when metadata includes the suppression for rule RESTRICTED_INCOMING_TRAFFIC

#
# Select all Security Group resources from incoming template (payload)
#
let aws_security_groups_restricted_incoming_traffic = Resources.*[ Type == 'AWS::EC2::SecurityGroup' 
	some Properties.SecurityGroupIngress[*] {
		IpProtocol in ['tcp', 'udp']
	}
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "RESTRICTED_INCOMING_TRAFFIC"
]

rule RESTRICTED_INCOMING_TRAFFIC when %aws_security_groups_restricted_incoming_traffic !empty {
	let violations = Resources.*[
		Type == 'AWS::EC2::SecurityGroup'
		some Properties.SecurityGroupIngress[*] {
			FromPort in [ 20, 21, 3389, 3306, 4333 ]
      ToPort in [ 20, 21, 3389, 3306, 4333 ]
		}
	]
	%violations empty 
	<<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.11,CIS.12    
		Violation: Security groups must not allow unrestricted incoming TCP/UDP traffic to the specified ports [20, 21, 3389, 3306, 4333].
		Fix: change the FromPort and ToPort properties in the SecurityGroupIngress list 
	>>
}

#####################################
# Rule Identifier:
#    S3_BUCKET_PUBLIC_READ_PROHIBITED
#
# Description:
#   Checks if your Amazon S3 buckets do not allow public read access. The rule checks the Block Public
#   Access settings, the bucket policy, and the bucket access control list (ACL).
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources Public Access Block Configuration element is present and properties are set to true
# c) FAIL: when all S3 resources do not have the Public Access Block Configuration element present or all properties set to true
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_PUBLIC_READ_PROHIBITED

#
# Select all S3 resources from incoming template (payload)
#
let s3_bucket_public_read_prohibited = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_PUBLIC_READ_PROHIBITED"
]

rule S3_BUCKET_PUBLIC_READ_PROHIBITED when %s3_bucket_public_read_prohibited !empty {
  %s3_bucket_public_read_prohibited.Properties.PublicAccessBlockConfiguration exists
  %s3_bucket_public_read_prohibited.Properties.PublicAccessBlockConfiguration.BlockPublicAcls == true
  %s3_bucket_public_read_prohibited.Properties.PublicAccessBlockConfiguration.BlockPublicPolicy == true
  %s3_bucket_public_read_prohibited.Properties.PublicAccessBlockConfiguration.IgnorePublicAcls == true
  %s3_bucket_public_read_prohibited.Properties.PublicAccessBlockConfiguration.RestrictPublicBuckets == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    Violation: S3 Bucket Public Write Access controls need to be restricted.
    Fix: Set S3 Bucket PublicAccessBlockConfiguration properties for BlockPublicAcls, BlockPublicPolicy, IgnorePublicAcls, RestrictPublicBuckets parameters to true.
  >>
}

#####################################
# Rule Identifier:
#    S3_BUCKET_PUBLIC_WRITE_PROHIBITED
#
# Description:
#   Checks if your Amazon S3 buckets do not allow public write access. The rule checks the Block Public
#   Access settings, the bucket policy, and the bucket access control list (ACL).
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources Public Access Block Configuration element is present and properties are set to true
# c) FAIL: when all S3 resources do not have the Public Access Block Configuration element present or all properties set to true
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_PUBLIC_WRITE_PROHIBITED

#
# Select all S3 resources from incoming template (payload)
#
let s3_buckets_public_write_prohibited = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_PUBLIC_WRITE_PROHIBITED"
]

rule S3_BUCKET_PUBLIC_WRITE_PROHIBITED when %s3_buckets_public_write_prohibited !empty {
  %s3_buckets_public_write_prohibited.Properties.PublicAccessBlockConfiguration exists
  %s3_buckets_public_write_prohibited.Properties.PublicAccessBlockConfiguration.BlockPublicAcls == true
  %s3_buckets_public_write_prohibited.Properties.PublicAccessBlockConfiguration.BlockPublicPolicy == true
  %s3_buckets_public_write_prohibited.Properties.PublicAccessBlockConfiguration.IgnorePublicAcls == true
  %s3_buckets_public_write_prohibited.Properties.PublicAccessBlockConfiguration.RestrictPublicBuckets == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.9,CIS.12,CIS.14    
    Violation: S3 Bucket Public Write Access controls need to be restricted.
    Fix: Set S3 Bucket PublicAccessBlockConfiguration properties for BlockPublicAcls, BlockPublicPolicy, IgnorePublicAcls, RestrictPublicBuckets parameters to true.
  >>
}
## Config Rule Name : sagemaker-notebook-no-direct-internet-access
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/sagemaker-notebook-no-direct-internet-access.html"

#####################################
# Rule Identifier:
#    DB_INSTANCE_BACKUP_ENABLED
#
# Description:
#    Checks if RDS DB instances have backups enabled.
#
# Reports on:
#    AWS::RDS::DBInstance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no RDS instances present
# b) PASS: when all RDS instances have BackupRetentionPeriod set to a positive number
# c) FAIL: when all RDS instances have BackupRetentionPeriod set to 0
# d) FAIL: when there are RDS instances with BackupRetentionPeriod property is not present
# e) SKIP: when metadata includes the suppression for rule DB_INSTANCE_BACKUP_ENABLED

#
# Select all RDS instance resources from incoming template (payload)
#

let aws_rds_instances_db_instance_backup_enabled = Resources.*[ Type == 'AWS::RDS::DBInstance'
  Properties.SourceDBInstanceIdentifier !exists
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "DB_INSTANCE_BACKUP_ENABLED"
]


rule DB_INSTANCE_BACKUP_ENABLED when %aws_rds_instances_db_instance_backup_enabled !empty {
  %aws_rds_instances_db_instance_backup_enabled.Properties.BackupRetentionPeriod EXISTS
  %aws_rds_instances_db_instance_backup_enabled.Properties.BackupRetentionPeriod >= 1
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.10    
    Violation: All RDS instances must have automated backup enabled.
    Fix: Set the BackupRetentionPeriod to values of 1 to 35 to enable backups.
  >>
}

## Config Rule Name : dynamodb-pitr-enabled
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/dynamodb-pitr-enabled.html"

# Rule Intent: All DynamoDB Tables must have Point-In-Time-Recovery enabled

# Expectations:
# a) SKIP: when there are no DynamoDB Tables present
# b) PASS: when all DynamoDB Tables have PITR enabled
# c) FAIL: when all DynamoDB Tables have PITR disabled

#
# Select all DynamoDB Table resources from incoming template (payload)
#
let aws_dynamodb_table_resources = Resources.*[ Type == 'AWS::DynamoDB::Table' 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "DYNAMODB_PITR_ENABLED"
]

rule DYNAMODB_PITR_ENABLED when %aws_dynamodb_table_resources !empty {
    # Ensure ALL DynamoDB Tables have Point-In-Time-Recovery enabled
    %aws_dynamodb_table_resources.Properties.PointInTimeRecoverySpecification.PointInTimeRecoveryEnabled == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.10    
    Violation: All DynamoDB Tables must have Point-In-Time-Recovery enabled.
    Fix: Set the dynamodb table property PointInTimeRecoverySpecification.PointInTimeRecoveryEnabled to true.
  >>
}

## Config Rule Name : elasticache-redis-cluster-automatic-backup-check
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/elasticache-redis-cluster-automatic-backup-check.html"

#####################################
# Rule Identifier:
#    S3_BUCKET_REPLICATION_ENABLED
#
# Description:
#   Checks whether the Amazon S3 buckets have cross-region replication enabled.
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources replication configuration set status is set to Enabled
# c) FAIL: when all S3 resources have Versioning Configuration status property not set or set to Suspended
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_REPLICATION_ENABLED

#
# Select all S3 resources from incoming template (payload)
#

let s3_buckets_replication_enabled = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_REPLICATION_ENABLED"
]

rule S3_BUCKET_REPLICATION_ENABLED when %s3_buckets_replication_enabled !empty {
  %s3_buckets_replication_enabled.Properties.ReplicationConfiguration exists
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.10    
    Violation: S3 Bucket replication should be enabled.
    Fix: Set S3 Bucket ReplicationConfiguration to another S3 Bucket.
  >>
    ## TODO regex to identify cross-region
}

#####################################
# Rule Identifier:
#    S3_BUCKET_VERSIONING_ENABLED
#
# Description:
#   Checks if versioning is enabled for your S3 buckets.
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources Versioning Configuration status is set to Enabled
# c) FAIL: when all S3 resources have Versioning Configuration status property not set or set to Suspended
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_VERSIONING_ENABLED

#
# Select all S3 resources from incoming template (payload)
#
let s3_buckets_versioning_enabled = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_VERSIONING_ENABLED"
]

rule S3_BUCKET_VERSIONING_ENABLED when %s3_buckets_versioning_enabled !empty {
  %s3_buckets_versioning_enabled.Properties.VersioningConfiguration exists
  %s3_buckets_versioning_enabled.Properties.VersioningConfiguration.Status == 'Enabled'
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.10    
    Violation: S3 Bucket Versioning must be enabled.
    Fix: Set the S3 Bucket property VersioningConfiguration.Status to 'Enabled' .
  >>
}

#####################################
# Rule Identifier:
#    API_GW_CACHE_ENABLED_AND_ENCRYPTED
#
# Description:
#    Checks that all methods in Amazon API Gateway stages have cache enabled and cache encrypted.
#
# Reports on:
#    AWS::ApiGateway::Stage
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no API GW Stage Methods present
# b) PASS: when all API Stage Method has caching enabled and encrypted
# c) FAIL: when API Stage Method does not have caching enabled and encrypted
# d) SKIP: when metadata includes the suppression for rule API_GW_CACHE_ENABLED_AND_ENCRYPTED

let api_gw_cache_enabled_encrypted = Resources.*[ Type == 'AWS::ApiGateway::Stage'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "API_GW_CACHE_ENABLED_AND_ENCRYPTED"
]

rule API_GW_CACHE_ENABLED_AND_ENCRYPTED when %api_gw_cache_enabled_encrypted !empty {
  when %api_gw_cache_enabled_encrypted.Properties.MethodSettings exists {
    %api_gw_cache_enabled_encrypted.Properties.MethodSettings.*.CacheDataEncrypted == true
    %api_gw_cache_enabled_encrypted.Properties.MethodSettings.*.CachingEnabled == true
    <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
      Violation: API Gateway Stage Method not set with caching and caching encrypted
      Fix: API GW Stage Method property CacheDataEncrypted and CachingEnabled set to true
    >>
  }
}

#####################################
# Rule Identifier:
#    CLOUD_TRAIL_ENCRYPTION_ENABLED
#
# Description:
#   Checks if AWS CloudTrail is configured to use the server side encryption (SSE)
#   AWS Key Management Service KMS key encryption.
#
# Reports on:
#    AWS::CloudTrail::Trail
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no CloudTrail Trails present
# b) PASS: when all CloudTrail Trails have KMSKeyId parameter set
# c) FAIL: when there are CloudTrail Trails with KMSKeyId property not present
# d) SKIP: when metada has rule suppression for CLOUD_TRAIL_ENCRYPTION_ENABLED

#
# Select all CloudTrail Trail resources from incoming template (payload)
#
let cloudtrail_trails_encryption = Resources.*[ Type == 'AWS::CloudTrail::Trail'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUD_TRAIL_ENCRYPTION_ENABLED"
]

rule CLOUD_TRAIL_ENCRYPTION_ENABLED when %cloudtrail_trails_encryption !empty {
  %cloudtrail_trails_encryption.Properties.KMSKeyId EXISTS
  %cloudtrail_trails_encryption.Properties.KMSKeyId is_string
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: CloudTrail Trail should be used to encrypt logs delivered by CloudTrail.
    Fix: Set the KMSKeyId parameter to enable encryption. The value can be an alias name prefixed by "alias/", a fully specified ARN to an alias, a fully specified ARN to a key, or a globally unique identifier.
  >>
}

#####################################
# Rule Identifier:
#    CLOUDWATCH_LOG_GROUP_ENCRYPTED
#
# Description:
#   Checks if a log group in Amazon CloudWatch Logs is encrypted with a
#   AWS Key Management Service (KMS) managed Customer Master Keys (CMK).
#
# Reports on:
#    AWS::Logs::LogGroup
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no cloudwatch logs log group resources present
# b) PASS: when all cloudwatch logs log group resources property KmsKeyId is set
# c) FAIL: when all cloudwatch logs log group resources property KmsKeyId is not set with valid value
# d) SKIP: when metada has rule suppression for CLOUDWATCH_LOG_GROUP_ENCRYPTED

#
# Select all cloudwatch logs log group resources from incoming template (payload)
#
let cloudwatch_logs = Resources.*[ Type == 'AWS::Logs::LogGroup'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "CLOUDWATCH_LOG_GROUP_ENCRYPTED"
]

rule CLOUDWATCH_LOG_GROUP_ENCRYPTED when %cloudwatch_logs !empty {
  %cloudwatch_logs.Properties.KmsKeyId exists
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: CloudWatch Log LogsGroup does not have KmsKeyId set.
    Fix: Set the KmsKeyId parameter to a ARN.
  >>
}

#####################################
# Rule Identifier:
#    EC2_EBS_ENCRYPTION_BY_DEFAULT
#
# Description:
#    Check that Amazon Elastic Block Store (EBS) encryption is enabled by default
# Reports on:
#    AWS::EC2::Volume
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when no EC2 Volume resources are present
# b) PASS: when all EC2 Volume resources have the Encrypted property set to true
# c) FAIL: when any EC2 Volumes resources do not have the Encrypted property set to true
# e) SKIP: when metadata includes the suppression for rule EC2_EBS_ENCRYPTION_BY_DEFAULT

#
# Select all EC2 Volume resources from incoming template (payload)
#
let ec2_ebs_volumes_encrypted_by_default = Resources.*[ Type == 'AWS::EC2::Volume' 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "EC2_EBS_ENCRYPTION_BY_DEFAULT"
]

rule EC2_EBS_ENCRYPTION_BY_DEFAULT when %ec2_ebs_volumes_encrypted_by_default !empty {
    %ec2_ebs_volumes_encrypted_by_default.Properties.Encrypted == true 
		<<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
			Violation: All EBS Volumes should be encryped 
			Fix: Set Encrypted property to true
		>>
}

#####################################
# Rule Identifier:
#    EFS_ENCRYPTED_CHECK
#
# Description:
#   Checks if Amazon Elastic File System (Amazon EFS) is configured to encrypt the file data
#   using AWS Key Management Service (AWS KMS). The rule is NON_COMPLIANT if the encrypted
#   key is set to false on DescribeFileSystems or if the KmsKeyId key on DescribeFileSystems
#   does not match the KmsKeyId parameter.
#
# Reports on:
#    AWS::EFS::FileSystem
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no EFS resource present
# b) PASS: when all EFS resources have encrypted key property set to true
# c) FAIL: when all EFS resources have encrypted key property not set or set to false
# d) SKIP: when guard metadata states EFS_ENCRYPTED_CHECK to be suppressed

#
# Select all EFS resources from incoming template (payload)
#
let efs_file_systems_encrypted_check = Resources.*[ Type == 'AWS::EFS::FileSystem'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "EFS_ENCRYPTED_CHECK"
]

rule EFS_ENCRYPTED_CHECK when %efs_file_systems_encrypted_check !empty {
  %efs_file_systems_encrypted_check.Properties.Encrypted == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: EFS filesystem must be encrypted.
    Fix: Set the EFS Filesystem property Encrypted parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    ELASTICSEARCH_ENCRYPTED_AT_REST
#
# Description:
#   Elasticsearch domains must enforce server side encryption
#
# Reports on:
#    AWS::Elasticsearch::Domain
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there is no elasticsearch domain present
# b) FAIL: when elasticsearch domain has server side encryption set to false
# c) PASS: when elasticsearch domain has server side encryption set to true
# d) FAIL: when elasticsearch domain has server side encryption property is missing
# e) SKIP: when metada has rule suppression for ELASTICSEARCH_ENCRYPTED_AT_REST

#
# Select all elasticsearch domains from incoming template
#
let elasticsearch_domains_encrypted = Resources.*[ Type == 'AWS::Elasticsearch::Domain'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "ELASTICSEARCH_ENCRYPTED_AT_REST"
]

rule ELASTICSEARCH_ENCRYPTED_AT_REST when %elasticsearch_domains_encrypted !empty {
  %elasticsearch_domains_encrypted.Properties.EncryptionAtRestOptions.Enabled == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: Elasticsearch domains must enforce server side encryption.
    Fix: Set the EncryptionAtRestOptions.Enabled parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    ENCRYPTED_VOLUMES
#
# Description:
#    Checks if the EBS volumes that are in an attached state are encrypted. 
#
# Reports on:
#    AWS::EC2::Volume
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no EBS volume resources present
# b) PASS: when all EBS volumes have the KmsKeyId property set or the Encrypted property set to true 
# c) FAIL: when any EC2 volumes do not have the KmsKeyId or Encrypted property set
# e) SKIP: hen metadata includes the suppression for rule ENCRYPTED_VOLUMES

#
# Select all EC2 Instance resources from incoming template (payload)
#
let ebs_volumes_encrypted = Resources.*[ Type == 'AWS::EC2::Volume' 
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "ENCRYPTED_VOLUMES"
]

rule ENCRYPTED_VOLUMES when %ebs_volumes_encrypted !empty {
  %ebs_volumes_encrypted.Properties.KmsKeyId !empty
	OR %ebs_volumes_encrypted.Properties.Encrypted == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: EBS volumes in an attached state must encrypted.
    Fix: either set the KmsKeyId property to a key ID, key alias, key ARN, or alias ARN 
		or set the Encrypted property to true to encrypt the volume with the account default key or AWS managed key. 
  >>
}
## Config Rule Name : kms-cmk-not-scheduled-for-deletion
## Config Rule URL: https://docs.aws.amazon.com/config/latest/developerguide/kms-cmk-not-scheduled-for-deletion.html"

#####################################
# Rule Identifier:
#    RDS_SNAPSHOT_ENCRYPTED
#
# Description:
#    Checks whether Amazon Relational Database Service (Amazon RDS) DB snapshots are encrypted.
#
#
# Reports on:
#    AWS::RDS::DBInstance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no RDS instances present
# b) PASS: when all RDS instances have StorageEncrypted set to true
# c) FAIL: when all RDS instances have StorageEncrypted set to false
# d) FAIL: when there are RDS instances with StorageEncrypted property is not present
# e) SKIP: when metadata includes the suppression for rule RDS_SNAPSHOT_ENCRYPTED

#
# Select all RDS instance resources from incoming template (payload)
#
let aws_rds_instances_snapshot_encrypted = Resources.*[ Type == 'AWS::RDS::DBInstance'
  Properties.SourceDBInstanceIdentifier !exists
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "RDS_SNAPSHOT_ENCRYPTED"
]


rule RDS_SNAPSHOT_ENCRYPTED when %aws_rds_instances_snapshot_encrypted !empty {
  %aws_rds_instances_snapshot_encrypted.Properties.StorageEncrypted EXISTS
  %aws_rds_instances_snapshot_encrypted.Properties.StorageEncrypted == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: All RDS instances must have snapshots encrypted.
    Fix: Set the StorageEncrypted parameter to true so by default all snapshots are encrypted.
  >>
}

#####################################
# Rule Identifier:
#    RDS_STORAGE_ENCRYPTED
#
# Description:
#    Checks whether storage encryption is enabled for your RDS DB instances.
#
#
# Reports on:
#    AWS::RDS::DBInstance
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no RDS instances present
# b) PASS: when all RDS instances have StorageEncrypted set to true
# c) FAIL: when all RDS instances have StorageEncrypted set to false
# d) FAIL: when there are RDS instances with StorageEncrypted property is not present
# e) SKIP: when metadata includes the suppression for rule RDS_STORAGE_ENCRYPTED

#
# Select all RDS instance resources from incoming template (payload)
#
let aws_rds_instances_storage_encrypted = Resources.*[ Type == 'AWS::RDS::DBInstance'
  Properties.SourceDBInstanceIdentifier !exists
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "RDS_STORAGE_ENCRYPTED"
]


rule RDS_STORAGE_ENCRYPTED when %aws_rds_instances_storage_encrypted !empty {
  %aws_rds_instances_storage_encrypted.Properties.StorageEncrypted EXISTS
  %aws_rds_instances_storage_encrypted.Properties.StorageEncrypted == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: All RDS instances must have encrypted storage.
    Fix: Set the StorageEncrypted parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    S3_BUCKET_DEFAULT_LOCK_ENABLED
#
# Description:
#   Checks whether Amazon S3 bucket has lock enabled, by default
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources ObjectLockEnabled property is set to true
# c) FAIL: when all S3 resources do not have the ObjectLockEnabled property is set to true or is missing
# d) SKIP: when metada has rule suppression for S3_BUCKET_DEFAULT_LOCK_ENABLED

#
# Select all S3 resources from incoming template (payload)
#
let s3_buckets_default_lock_enabled = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_DEFAULT_LOCK_ENABLED"
]

rule S3_BUCKET_DEFAULT_LOCK_ENABLED when %s3_buckets_default_lock_enabled !empty {
  %s3_buckets_default_lock_enabled.Properties.ObjectLockEnabled exists
  %s3_buckets_default_lock_enabled.Properties.ObjectLockEnabled == true
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: S3 Bucket ObjectLockEnabled must be set to true.
    Fix: Set the S3 property ObjectLockEnabled parameter to true.
  >>
}

#####################################
# Rule Identifier:
#    S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED
#
# Description:
#   Checks if your Amazon S3 bucket either has the Amazon S3 default encryption enabled or that the Amazon S3 bucket policy
#   explicitly denies put-object requests without server side encryption that uses AES-256 or AWS Key Management Service.
#
# Reports on:
#    AWS::S3::Bucket
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 resource present
# b) PASS: when all S3 resources Bucket Encryption ServerSideEncryptionByDefault is set to either "aws:kms" or "AES256"
# c) FAIL: when all S3 resources have Bucket Encryption ServerSideEncryptionByDefault is not set or does not have "aws:kms" or "AES256" configurations
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED

#
# Select all S3 resources from incoming template (payload)
#

let s3_buckets_server_side_encryption = Resources.*[ Type == 'AWS::S3::Bucket'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED"
]

rule S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED when %s3_buckets_server_side_encryption !empty {
  %s3_buckets_server_side_encryption.Properties.BucketEncryption exists
  %s3_buckets_server_side_encryption.Properties.BucketEncryption.ServerSideEncryptionConfiguration[*].ServerSideEncryptionByDefault.SSEAlgorithm in ["aws:kms","AES256"]
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: S3 Bucket must enable server-side encryption.
    Fix: Set the S3 Bucket property BucketEncryption.ServerSideEncryptionConfiguration.ServerSideEncryptionByDefault.SSEAlgorithm to either "aws:kms" or "AES256"
  >>
}

#####################################
# Rule Identifier:
#    S3_BUCKET_SSL_REQUESTS_ONLY
#
# Description:
#   Checks if Amazon S3 buckets have policies that require requests to use Secure Socket Layer (SSL).
#
# Reports on:
#    AWS::S3::BucketPolicy
#
# Evaluates:
#    AWS CloudFormation
#
# Rule Parameters:
#    NA
#
# Scenarios:
# a) SKIP: when there are no S3 Bucket Policy Document resource present
# b) PASS: when all S3 Bucket Policy Document set to deny if condition SecureTransport not true
# c) FAIL: when all S3 Bucket Policy Document does not have deny on insecure transport actions
# d) SKIP: when metadata includes the suppression for rule S3_BUCKET_SSL_REQUESTS_ONLY

#
# Select all S3 resources from incoming template (payload)
#
let s3_buckets_policies_ssl_requests_only = Resources.*[ Type == 'AWS::S3::BucketPolicy'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "S3_BUCKET_SSL_REQUESTS_ONLY"
]

let ssl_secure_bucket_policies = %s3_buckets_policies_ssl_requests_only[
  Properties.PolicyDocument {
    some Statement[*] {
      Effect == 'Deny'
      Condition {
        Bool.'aws:SecureTransport' == false
      }
    }
  }
]

rule S3_BUCKET_SSL_REQUESTS_ONLY when %s3_buckets_policies_ssl_requests_only !empty {
  %ssl_secure_bucket_policies !empty
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.13,CIS.14    
    Violation: Bucket policies must feature a statement to enforce TLS usage.
    Fix: Set a bucket policy statement to include "Condition":{"Bool":{"aws:SecureTransport":false}}.
  >>
}

#####################################
# Rule Identifier:
#   IAM_USER_NO_POLICIES_CHECK
#
# Description:
#   Checks that none of your IAM users have policies attached. IAM users must inherit permissions from IAM groups or roles. 
#
# Reports on:
#   AWS::IAM::User
#
# Evaluates:
#   AWS CloudFormation
#
# Rule Parameters:
#   NA
#
# Scenarios:
# a) SKIP: when there are no IAM Users present
# b) PASS: when all IAM Users do not have policies attached
# c) FAIL: when any IAM User have policies attached
# d) SKIP: when metada has rule suppression for IAM_USER_NO_POLICIES_CHECK

#
# Select all IAM User resources from incoming template (payload)
# 
let aws_iam_users_no_policies = Resources.*[ Type == 'AWS::IAM::User'
  Metadata.guard.SuppressedRules not exists or
  Metadata.guard.SuppressedRules.* != "IAM_USER_NO_POLICIES_CHECK" 
]

rule IAM_USER_NO_POLICIES_CHECK when %aws_iam_users_no_policies !empty {
  %aws_iam_users_no_policies.Properties.Policies empty
  <<
    Guard Rule Set: cis-top-20
    Controls: CIS.16    
  	Violation: Inline policies are not allowed on IAM Users. IAM users must inherit permissions from IAM groups or roles.
  	Fix: Remove the Policies list property from any IAM Users. 
  >>
}

let lambda_functions = Resources.*[
    Type == "AWS::Lambda::Function"
]

rule LAMBDA_DEPRECATED_RUNTIME when %lambda_functions !empty {
    %lambda_functions {
        Properties {
            when Runtime exists {
                Runtime !in ["dotnetcore3.1", "nodejs12.x", "python3.6", "python2.7", "dotnet5.0", "dotnetcore2.1", "ruby2.5", "nodejs10.x", "nodejs8.10", "nodejs4.3", "nodejs6.10", "dotnetcore1.0", "dotnetcore2.0", "nodejs4.3-edge", "nodejs"]
                <<
                    Lambda function is using a deprecated runtime.
                >>
            }
        }
    }
}

rule LAMBDA_DEPRECATED_SOON_RUNTIME when %lambda_functions !empty {
    %lambda_functions {
        Properties {
            when Runtime exists {
                Runtime !in ["nodejs16.x", "nodejs14.x", "python3.7", "java8", "dotnet7", "go1.x", "ruby2.7", "provided"]
                <<
                    Lambda function is using a runtime that is targeted for deprecation.
                >>
            }
        }
    }
}