-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpcs-inspect.py
executable file
·1137 lines (1040 loc) · 67.5 KB
/
pcs-inspect.py
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
#!/usr/bin/env python3
# pylint: disable=invalid-name
""" Inspect a Prisma Cloud Tenant """
import argparse
import json
import os
import re
from shutil import which
import sys
import pandas as pd
import requests
from requests.exceptions import RequestException
##########################################################################################
# Process arguments / parameters.
##########################################################################################
pc_parser = argparse.ArgumentParser(description='This script collects or processes Policies and Alerts.', prog=os.path.basename(__file__))
pc_parser.add_argument(
'-c', '--customer_name',
type=str, required=True,
help='*Required* Customer Name')
pc_parser.add_argument('-u', '--url',
type=str,
help="(Required with '--mode collect') Prisma Cloud API URL")
pc_parser.add_argument('-a', '--access_key',
type=str,
help="(Required with '--mode collect') API Access Key")
pc_parser.add_argument('-s', '--secret_key',
type=str,
help="(Required with '--mode collect') API Secret Key")
pc_parser.add_argument('-ca', '--cloud_account',
type=str,
help='(Optional) Cloud Account ID to limit the Alert query')
pc_parser.add_argument('-ta', '--time_range_amount',
type=int, default=1, choices=[1, 2, 3],
help="(Optional) Time Range Amount to limit the Alert query. Default: 1")
pc_parser.add_argument('-tu', '--time_range_unit',
type=str, default='month', choices=['day', 'week', 'month', 'year'],
help="(Optional) Time Range Unit to limit the Alert query. Default: 'month'")
pc_parser.add_argument('-m', '--mode',
type=str, default='auto', choices=['collect', 'process'],
help="(Optional) Mode: just collect Policies and Alerts, or just process collected data")
pc_parser.add_argument('-sa', '--support_api',
action='store_true',
help='(Optional) Use the Support API to collect data without needing a Tenant API Key')
pc_parser.add_argument('-d', '--debug',
action='store_true',
help='(Optional) Enable debugging.')
argz = pc_parser.parse_args()
##########################################################################################
# Helpers.
##########################################################################################
def output(output_data=''):
print(output_data)
##########################################################################################
# Configure.
##########################################################################################
def configure(args):
config = {}
config['DEBUG_MODE'] = args.debug
config['RUN_MODE'] = args.mode
config['SUPPORT_API_MODE'] = args.support_api
config['PRISMA_API_ENDPOINT'] = args.url # or os.environ.get('PRISMA_API_ENDPOINT')
config['PRISMA_ACCESS_KEY'] = args.access_key # or os.environ.get('PRISMA_ACCESS_KEY')
config['PRISMA_SECRET_KEY'] = args.secret_key # or os.environ.get('PRISMA_SECRET_KEY')
config['PRISMA_API_HEADERS'] = {
'Accept': 'application/json; charset=UTF-8, text/plain, */*',
'Content-Type': 'application/json'
}
config['API_TIMEOUTS'] = (60, 600) # (CONNECT, READ)
config['CUSTOMER_NAME'] = args.customer_name
config['CLOUD_ACCOUNT_ID'] = args.cloud_account
config['TIME_RANGE_AMOUNT'] = args.time_range_amount
config['TIME_RANGE_UNIT'] = args.time_range_unit
config['TIME_RANGE_LABEL'] = 'Past %s %s' % (config['TIME_RANGE_AMOUNT'], config['TIME_RANGE_UNIT'].capitalize())
config['CUSTOMER_PREFIX'] = re.sub(r'\W+', '', config['CUSTOMER_NAME']).lower()
config['RESULTS_FILE'] = {
'ASSETS': '%s-assets.json' % config['CUSTOMER_PREFIX'],
'POLICIES': '%s-policies.json' % config['CUSTOMER_PREFIX'],
'ALERTS': '%s-alerts.json' % config['CUSTOMER_PREFIX'],
'USERS': '%s-users.json' % config['CUSTOMER_PREFIX'],
'ACCOUNTS': '%s-accounts.json' % config['CUSTOMER_PREFIX'],
'GROUPS': '%s-groups.json' % config['CUSTOMER_PREFIX'],
'RULES': '%s-rules.json' % config['CUSTOMER_PREFIX'],
'INTEGRATIONS': '%s-integrations.json' % config['CUSTOMER_PREFIX']
}
config['OUTPUT_FILE_XLS'] = '%s.xls' % config['CUSTOMER_PREFIX']
if config['RUN_MODE'] in ['auto', 'collect'] :
if not config['PRISMA_API_ENDPOINT']:
output("Error: '--url' is required")
sys.exit(1)
if not config['PRISMA_ACCESS_KEY']:
output("Error: '--access_key' is required")
sys.exit(1)
if not config['PRISMA_SECRET_KEY']:
output("Error: '--secret_key' is required")
sys.exit(1)
return config
##########################################################################################
# File Helpers.
##########################################################################################
def delete_file_if_exists(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def open_sheet(file_name):
# pylint: disable=abstract-class-instantiated
return pd.ExcelWriter(file_name, engine='xlsxwriter')
def write_sheet(panda_writer, this_sheet_name, rows):
dataframe = pd.DataFrame.from_records(rows)
dataframe.to_excel(panda_writer, sheet_name=this_sheet_name, header=False, index=False)
this_sheet = panda_writer.sheets[this_sheet_name]
# Approximate autofit column width.
for idx, column in enumerate(dataframe): # Loop through the columns.
dataframe_series = dataframe[column]
column_width = max(
dataframe_series.astype(str).map(len).max(), # Length of largest cell
len(str(dataframe_series.name)) # Length of column header / name
)
this_sheet.set_column(idx, idx, column_width)
if CONFIG['DEBUG_MODE']:
output(this_sheet_name)
output()
pd.set_option('display.max_rows', None)
output(dataframe)
output()
def save_sheet(panda_writer):
panda_writer.save()
##########################################################################################
# API Helpers.
##########################################################################################
def make_api_call(method, url, requ_data=None):
if CONFIG['DEBUG_MODE']:
output('URL: %s' % url)
output('METHOD: %s' % method)
output('REQUEST DATA: %s' % requ_data)
try:
requ = requests.Request(method, url, data=requ_data, headers=CONFIG['PRISMA_API_HEADERS'])
prep = requ.prepare()
sess = requests.Session()
# GlobalProtect generates 'ignore self signed certificate in certificate chain' errors.
# Set 'REQUESTS_CA_BUNDLE' to a valid CA bundle including the 'Palo Alto Networks Inc Root CA' used by GlobalProtect.
# Hint: Copy the bundle provided by the certifi module (locate via 'python -m certifi') and append the 'Palo Alto Networks Inc Root CA'
if 'REQUESTS_CA_BUNDLE' in os.environ:
resp = sess.send(prep, timeout=(CONFIG['API_TIMEOUTS']), verify="%s" % os.environ['REQUESTS_CA_BUNDLE'])
else:
resp = sess.send(prep, timeout=(CONFIG['API_TIMEOUTS']))
if CONFIG['DEBUG_MODE']:
output(resp.text)
if resp.ok:
return resp.content
# return bytes('[]', 'utf-8')
output('Error with API: Status Code: %s Details: %s' % (resp.status_code, resp.text))
sys.exit(1)
except RequestException as ex:
output()
output('Error with API: URL: %s: Error: %s' % (url, str(ex)))
output()
output('For CERTIFICATE_VERIFY_FAILED errors with GlobalProtect, try setting REQUESTS_CA_BUNDLE to a bundle with the Palo Alto Networks Inc Root CA.')
sys.exit(1)
####
def get_prisma_login():
request_data = json.dumps({
"username": CONFIG['PRISMA_ACCESS_KEY'],
"password": CONFIG['PRISMA_SECRET_KEY']
})
api_response = make_api_call('POST', '%s/login' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
resp_data = json.loads(api_response)
token = resp_data.get('token')
if not token:
output('Error with API Login: %s' % resp_data)
sys.exit(1)
return token
# SUPPORT_API_MODE:
# Using '/_support/timeline/resource' instead of the not-implemented '_support/v2/inventory' endpoint.
def get_assets(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {}
body_params["customerName"] = "%s" % CONFIG['CUSTOMER_NAME']
if CONFIG['CLOUD_ACCOUNT_ID']:
body_params["accountIds"] = ["%s" % CONFIG['CLOUD_ACCOUNT_ID']]
body_params['timeRange'] = {"value": {"unit": "%s" % CONFIG['TIME_RANGE_UNIT'], "amount": CONFIG['TIME_RANGE_AMOUNT']}, "type": "relative"}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/timeline/resource' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
api_response_json = json.loads(api_response)
if api_response_json and 'resources' in api_response_json[0]:
api_response = bytes('{"summary": {"totalResources": %s}}' % api_response_json[0]['resources'], 'utf-8')
else:
api_response = bytes('{"summary": {"totalResources": 0}}', 'utf-8')
else:
if CONFIG['CLOUD_ACCOUNT_ID']:
query_params = 'timeType=%s&timeAmount=%s&timeUnit=%s&cloud.account=%s' % ('relative', CONFIG['TIME_RANGE_AMOUNT'], CONFIG['TIME_RANGE_UNIT'], CONFIG['CLOUD_ACCOUNT_ID'])
else:
query_params = 'timeType=%s&timeAmount=%s&timeUnit=%s' % ('relative', CONFIG['TIME_RANGE_AMOUNT'], CONFIG['TIME_RANGE_UNIT'])
api_response = make_api_call('GET', '%s/v2/inventory?%s' % (CONFIG['PRISMA_API_ENDPOINT'], query_params))
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
# This returns a dictionary instead of a list.
# SUPPORT_API_MODE:
# This script depends upon Open Alert counts for all Policies (as provided by '/policy'), but '/_support/policy' doesn't return open Alert counts.
# And '/_support/alert/policy' does return alertCount, but I cannot tell if that is all (Open or Closed) or just Open Alerts, and returns fewer Policies than '_support/policy' ... given the same parameters.
# Instead, this script merges the results of the '/_support/alert/aggregate' endpoint with the results of the '/_support/policy' endpoint.
def get_policies(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/policy' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
else:
api_response = make_api_call('GET', '%s/policy' % CONFIG['PRISMA_API_ENDPOINT'])
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
# SUPPORT_API_MODE:
# This script depends upon the not implemented '/_support/alert/jobs' endpoint.
# Instead, this script merges the results of the '/_support/alert/aggregate' endpoint with the results of the '/_support/policy' endpoint.
def get_alerts(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
api_response = {}
api_response['by_policy'] = json.loads(get_alerts_aggregate('policy.name'))
api_response['by_policy_type'] = json.loads(get_alerts_aggregate('policy.type'))
api_response['by_policy_severity'] = json.loads(get_alerts_aggregate('policy.severity'))
api_response['by_alert.status'] = json.loads(get_alerts_aggregate('alert.status'))
api_response_json = json.dumps(api_response, indent=2, separators=(', ', ': '))
result_file = open(output_file_name, 'w', encoding='utf8')
result_file.write(api_response_json)
result_file.close()
# This returns a dictionary (of Open Alerts) instead of a list.
else:
body_params = {}
body_params['timeRange'] = {"value": {"unit": "%s" % CONFIG['TIME_RANGE_UNIT'], "amount": CONFIG['TIME_RANGE_AMOUNT']}, "type": "relative"}
if CONFIG['CLOUD_ACCOUNT_ID']:
body_params["filters"] = [{"name": "cloud.accountId","value": "%s" % CONFIG['CLOUD_ACCOUNT_ID'], "operator": "="}]
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/alert/jobs' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
api_response_json = json.loads(api_response)
if not 'id' in api_response_json:
output("Error with '/alert/jobs' API: 'id' missing from response: %s" % api_response_json)
return
alert_job_id = api_response_json['id']
api_response = make_api_call('GET', '%s/alert/jobs/%s/status' % (CONFIG['PRISMA_API_ENDPOINT'], alert_job_id))
api_response_json = json.loads(api_response)
if not 'status' in api_response_json:
output("Error with '/alert/jobs' API: 'status' missing from response: %s" % api_response_json)
return
alert_job_status = api_response_json['status']
while alert_job_status == 'IN_PROGRESS':
output('Checking: %s' % alert_job_status)
if CONFIG['DEBUG_MODE']:
output(api_response_json)
output()
api_response = make_api_call('GET', '%s/alert/jobs/%s/status' % (CONFIG['PRISMA_API_ENDPOINT'], alert_job_id))
api_response_json = json.loads(api_response)
if not 'status' in api_response_json:
output("Error with '/alert/jobs' API: 'status' missing from response: %s" % api_response_json)
return
alert_job_status = api_response_json['status']
if alert_job_status == 'READY_TO_DOWNLOAD':
api_response = make_api_call('GET', '%s/alert/jobs/%s/download' % (CONFIG['PRISMA_API_ENDPOINT'], alert_job_id))
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
else:
output("Error with '/alert/jobs' API: 'status' in response not in ('IN_PROGRESS','READY_TO_DOWNLOAD'): %s" % api_response_json)
# This returns a list (of Open and Closed Alerts).
## Valid filter options: policy.name, policy.type, policy.severity, or alert.status.
def get_alerts_aggregate(group_by_field):
body_params = {}
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
if CONFIG['CLOUD_ACCOUNT_ID']:
body_params["accountIds"] = ["%s" % CONFIG['CLOUD_ACCOUNT_ID']]
body_params['timeRange'] = {"value": {"unit": "%s" % CONFIG['TIME_RANGE_UNIT'], "amount": CONFIG['TIME_RANGE_AMOUNT']}, "type": "relative"}
body_params['groupBy'] = group_by_field
body_params['limit'] = 9999
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/alert/aggregate' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
return api_response
####
def get_users(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/v2/_support/user' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
else:
api_response = make_api_call('GET', '%s/v2/user' % CONFIG['PRISMA_API_ENDPOINT'])
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
####
def get_accounts(output_file_name):
delete_file_if_exists(output_file_name)
account_list = []
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/cloud' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
api_response_json = json.loads(api_response)
for account in api_response_json:
if account['numberOfChildAccounts'] > 0: # > Or account['accountType'] == 'organization'
api_response_children = make_api_call('POST', '%s/_support/cloud/%s/%s/project' % (CONFIG['PRISMA_API_ENDPOINT'], account['cloudType'], account['accountId']), request_data)
account_list.extend(parse_account_children(account, api_response_children))
else:
account_list.append(account)
else:
api_response = make_api_call('GET', '%s/cloud' % CONFIG['PRISMA_API_ENDPOINT'])
api_response_json = json.loads(api_response)
for account in api_response_json:
if account['accountType'] == 'organization': # ? Or account['numberOfChildAccounts'] > 0
api_response_children = make_api_call('GET', '%s/cloud/%s/%s/project' % (CONFIG['PRISMA_API_ENDPOINT'], account['cloudType'], account['accountId']))
account_list.extend(parse_account_children(account, api_response_children))
else:
account_list.append(account)
result_file = open(output_file_name, 'w', encoding='utf8')
result_file.write(json.dumps(account_list))
result_file.close()
##
def parse_account_children(account, api_response_children):
children = []
api_response_children_json = json.loads(api_response_children)
for child_account in api_response_children_json:
# Children of an organization include the parent, but numberOfChildAccounts is always reported as zero by the endpoint.
if account['accountId'] == child_account['accountId']:
child_account['numberOfChildAccounts'] = account['numberOfChildAccounts']
children.append(child_account)
return children
####
def get_account_groups(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/cloud/group' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
else:
api_response = make_api_call('GET', '%s/cloud/group' % CONFIG['PRISMA_API_ENDPOINT'])
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
####
def get_alert_rules(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/alert/rule' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
else:
api_response = make_api_call('GET', '%s/v2/alert/rule' % CONFIG['PRISMA_API_ENDPOINT'])
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
####
def get_integrations(output_file_name):
delete_file_if_exists(output_file_name)
if CONFIG['SUPPORT_API_MODE']:
body_params = {"customerName": "%s" % CONFIG['CUSTOMER_NAME']}
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/_support/integration' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
else:
api_response = make_api_call('GET', '%s/integration' % CONFIG['PRISMA_API_ENDPOINT'])
result_file = open(output_file_name, 'wb')
result_file.write(api_response)
result_file.close()
#### WIP
def get_cloud_resources(output_file_name, cloud_accounts_list):
delete_file_if_exists(output_file_name)
if not cloud_accounts_list:
cloud_accounts_list = []
resource_list = []
for cloud_account in cloud_accounts_list:
body_params = {
'filters':[
{'operator':'=', 'name':'includeEventForeignEntities', 'value': 'false'},
{'operator':'=', 'name':'asset.severity', 'value': 'all'},
{'operator':'=', 'name':'cloud.account', 'value': '%s' % cloud_account['name']},
{'operator':'=', 'name':'cloud.type', 'value': '%s' % cloud_account['deploymentType']},
{'operator':'=', 'name':'scan.status', 'value': 'all'}],
'limit': 1000,
'timeRange': {'type': 'to_now'}
}
if CONFIG['SUPPORT_API_MODE']:
body_params['customerName'] = CONFIG['CUSTOMER_NAME']
request_data = json.dumps(body_params)
# api_response = make_api_call('POST', '%s/_support/WIP' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
api_response = []
else:
request_data = json.dumps(body_params)
api_response = make_api_call('POST', '%s/resource' % CONFIG['PRISMA_API_ENDPOINT'], request_data)
resource_list.append(api_response)
result_file = open(output_file_name, 'wb')
result_file.write(resource_list)
result_file.close()
##########################################################################################
# Collect mode: Query the API and write the results to files.
##########################################################################################
def collect_data():
output('Generating Prisma Cloud API Token')
token = get_prisma_login()
if CONFIG['DEBUG_MODE']:
output()
output(token)
output()
CONFIG['PRISMA_API_HEADERS']['x-redlock-auth'] = token
output()
output('Querying Policies (please wait)')
get_policies(CONFIG['RESULTS_FILE']['POLICIES'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['POLICIES'])
output()
output('Generating Prisma Cloud API Token')
token = get_prisma_login()
if CONFIG['DEBUG_MODE']:
output()
output(token)
output()
CONFIG['PRISMA_API_HEADERS']['x-redlock-auth'] = token
output('Querying Alerts: Time Range: %s (please wait)' % CONFIG['TIME_RANGE_LABEL'])
get_alerts(CONFIG['RESULTS_FILE']['ALERTS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['ALERTS'])
output()
output('Generating Prisma Cloud API Token')
token = get_prisma_login()
if CONFIG['DEBUG_MODE']:
output()
output(token)
output()
CONFIG['PRISMA_API_HEADERS']['x-redlock-auth'] = token
output('Querying Assets: Time Range: %s' % CONFIG['TIME_RANGE_LABEL'])
get_assets(CONFIG['RESULTS_FILE']['ASSETS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['ASSETS'])
output()
output('Querying Users')
get_users(CONFIG['RESULTS_FILE']['USERS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['USERS'])
output()
output('Querying Accounts')
get_accounts(CONFIG['RESULTS_FILE']['ACCOUNTS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['ACCOUNTS'])
output()
output('Querying Account Groups')
get_account_groups(CONFIG['RESULTS_FILE']['GROUPS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['GROUPS'])
output()
output('Querying Alert Rules')
get_alert_rules(CONFIG['RESULTS_FILE']['RULES'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['RULES'])
output()
output('Querying Integrations')
get_integrations(CONFIG['RESULTS_FILE']['INTEGRATIONS'])
output('Results saved as: %s' % CONFIG['RESULTS_FILE']['INTEGRATIONS'])
output()
##########################################################################################
# Collect mode: Pretty the input files ... using jq to avoid encoding errors.
##########################################################################################
def format_collected_data():
if which('jq') is None:
return
for this_result_file in CONFIG['RESULTS_FILE']:
this_file = CONFIG['RESULTS_FILE'][this_result_file]
temp_file = '%s.temp' % this_file
if not os.path.isfile(this_file):
output('Error: Query result file does not exist: %s' % this_file)
sys.exit(1)
os.system('cat %s | jq > %s' % (this_file, temp_file))
os.system('mv %s %s' % (temp_file, this_file))
output('Formatting: %s' % this_file)
output()
##########################################################################################
# Process mode: Read the input files.
##########################################################################################
def read_collected_data():
for this_result_file in CONFIG['RESULTS_FILE']:
this_file = CONFIG['RESULTS_FILE'][this_result_file]
if not os.path.isfile(this_file):
output('Error: Query result file does not exist: %s' % this_file)
sys.exit(1)
with open(this_file, 'r', encoding='utf8') as json_file:
DATA[this_result_file] = json.load(json_file)
##########################################################################################
# Process mode: Process the data.
##########################################################################################
def cloud_types():
return dict({'all': 0, 'aws': 0, 'azure': 0, 'gcp': 0, 'alibaba_cloud': 0, 'oci': 0})
def policy_modes():
return dict({'default': 0, 'custom': 0})
def policy_severities():
return dict({'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'informational': 0})
def policy_types():
return dict({'anomaly': 0, 'audit_event': 0, 'config': 0, 'data': 0, 'iam': 0, 'network': 0, 'workload_incident': 0, 'workload_vulnerability': 0, 'attack_path': 0})
def policy_states():
return dict({'disabled': 0, 'deleted': 0})
def policy_features():
return dict({'shiftable': 0, 'remediable': 0, 'shiftable_and_remediable': 0})
def resource_states():
return dict({'updated': 0, 'deleted': 0})
def alert_statuses():
return dict({'open': 0, 'dismissed': 0, 'snoozed': 0, 'resolved': 0})
##
def process_collected_data():
# SUPPORT_API_MODE saves a dictionary (of Open) Alerts instead of a list.
# Use that to override any '--support_api' argument.
if isinstance(DATA['ALERTS'], dict):
CONFIG['SUPPORT_API_MODE'] = True
RESULTS['alerts_aggregated_by'] = process_aggregated_alerts(DATA['ALERTS'])
# POLICIES
RESULTS['compliance_standards_from_policies'] = {}
RESULTS['policies_by_name'] = {}
RESULTS['policies'] = {}
RESULTS['alert_counts_from_policies'] = {
'cloud_type': cloud_types(),
'feature': policy_features(),
'mode': policy_modes(),
'severity': policy_severities(),
'status': alert_statuses(),
'type': policy_types(),
}
process_policies(DATA['POLICIES'])
# ALERTS
RESULTS['compliance_standards_from_alerts'] = {}
RESULTS['policies_from_alerts'] = {}
RESULTS['policy_counts_from_alerts'] = {
'cloud_type': cloud_types(),
'severity': policy_severities(),
'type': policy_types(),
}
RESULTS['alert_counts_from_alerts'] = {
'cloud_type': cloud_types(),
'feature': policy_features(),
'mode': policy_modes(),
'policy': policy_states(),
'status_by_feature': {
'remediable': alert_statuses(),
},
'severity': policy_severities(),
'status': alert_statuses(),
'severity_by_status': {
'open': policy_severities(),
'dismissed': policy_severities(),
'snoozed': policy_severities(),
'resolved': policy_severities(),
},
'type': policy_types(),
'resolved_by_policy': policy_states(),
'resolved_by_resource': resource_states(),
}
RESULTS['deleted_policies_from_alerts'] = {}
RESULTS['disabled_policies_from_alerts'] = {}
RESULTS['resources_from_alerts'] = {}
process_alerts(DATA['ALERTS'])
# SUMMARY
RESULTS['summary'] = {}
RESULTS['summary']['count_of_assets'] = 0
RESULTS['summary']['count_of_aggregated_open_alerts'] = 0
RESULTS['summary']['count_of_resources_with_alerts_from_alerts'] = 0
RESULTS['summary']['count_of_compliance_standards_with_alerts_from_policies'] = 0
RESULTS['summary']['count_of_compliance_standards_with_alerts_from_alerts'] = 0
RESULTS['summary']['count_of_policies_with_alerts_from_policies'] = 0
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud'] = cloud_types()
RESULTS['summary']['count_of_policies_with_alerts_from_alerts'] = 0
process_summary()
##########################################################################################
# SUPPORT_API_MODE: Loop through '/_support/alert/aggregate' results and collect the details.
# Alert counts from that endpoint include Open Alerts and are scoped to a time range.
# Valid filter options: policy.name, policy.type, policy.severity, or alert.status.
##########################################################################################
def process_aggregated_alerts(alerts):
alerts_by = {
'policy': {},
'type': policy_types(),
'severity': policy_severities(),
'status': {'open': 0, 'resolved': 0}
}
for item in alerts['by_policy']:
alerts_by['policy'][item['policyName']] = item['alerts']
for item in alerts['by_policy_type']:
alerts_by['type'][item['policyType']] = item['alerts']
for item in alerts['by_policy_severity']:
alerts_by['severity'][item['severity']] = item['alerts']
for item in alerts['by_alert.status']:
alerts_by['status'][item['status']] = item['alerts']
return alerts_by
##########################################################################################
# Loop through all Policies and collect the details.
# Alert counts from this endpoint include Open Alerts and are not scoped to a time range.
# SUPPORT_API_MODE: Substitute aggregated Alerts (as '/_support/policy' does not return openAlertsCount).
##########################################################################################
def process_policies(policies):
for this_policy in policies:
this_policy_id = this_policy['policyId']
RESULTS['policies_by_name'][this_policy['name']] = {'policyId': this_policy_id}
RESULTS['policies'][this_policy_id] = {'policyName': this_policy['name']}
RESULTS['policies'][this_policy_id]['policyEnabled'] = this_policy['enabled']
RESULTS['policies'][this_policy_id]['policySeverity'] = this_policy['severity']
RESULTS['policies'][this_policy_id]['policyType'] = this_policy['policyType']
RESULTS['policies'][this_policy_id]['policySubTypes'] = this_policy['policySubTypes']
RESULTS['policies'][this_policy_id]['policyCategory'] = this_policy['policyCategory']
RESULTS['policies'][this_policy_id]['policyClass'] = this_policy['policyClass']
RESULTS['policies'][this_policy_id]['policyCloudType'] = this_policy['cloudType'].lower()
RESULTS['policies'][this_policy_id]['policyShiftable'] = 'build' in this_policy['policySubTypes']
RESULTS['policies'][this_policy_id]['policyRemediable'] = this_policy['remediable']
#
RESULTS['policies'][this_policy_id]['policyShiftableRemediable'] = 'build' in this_policy['policySubTypes'] and this_policy['remediable']
#
RESULTS['policies'][this_policy_id]['policySystemDefault'] = this_policy['systemDefault']
RESULTS['policies'][this_policy_id]['policyLabels'] = this_policy['labels']
if 'policyUpi' in this_policy:
RESULTS['policies'][this_policy_id]['policyUpi'] = this_policy['policyUpi']
else:
RESULTS['policies'][this_policy_id]['policyUpi'] = 'UNKNOWN'
# Alerts
if CONFIG['SUPPORT_API_MODE']:
if this_policy['name'] in RESULTS['alerts_aggregated_by']['policy']:
RESULTS['policies'][this_policy_id]['alertCount'] = RESULTS['alerts_aggregated_by']['policy'][this_policy['name']]
else:
RESULTS['policies'][this_policy_id]['alertCount'] = 0
else:
RESULTS['policies'][this_policy_id]['alertCount'] = this_policy['openAlertsCount']
RESULTS['alert_counts_from_policies']['status']['open'] += RESULTS['policies'][this_policy_id]['alertCount']
RESULTS['alert_counts_from_policies']['severity'][this_policy['severity']] += RESULTS['policies'][this_policy_id]['alertCount']
RESULTS['alert_counts_from_policies']['type'][this_policy['policyType']] += RESULTS['policies'][this_policy_id]['alertCount']
RESULTS['alert_counts_from_policies']['cloud_type'][this_policy['cloudType'].lower()] += RESULTS['policies'][this_policy_id]['alertCount']
if RESULTS['policies'][this_policy_id]['policyRemediable']:
RESULTS['alert_counts_from_policies']['feature']['remediable'] += RESULTS['policies'][this_policy_id]['alertCount']
if RESULTS['policies'][this_policy_id]['policyShiftable']:
RESULTS['alert_counts_from_policies']['feature']['shiftable'] += RESULTS['policies'][this_policy_id]['alertCount']
if RESULTS['policies'][this_policy_id]['policyShiftableRemediable']:
RESULTS['alert_counts_from_policies']['feature']['shiftable_and_remediable'] += RESULTS['policies'][this_policy_id]['alertCount']
if RESULTS['policies'][this_policy_id]['policySystemDefault'] == True:
RESULTS['alert_counts_from_policies']['mode']['default'] += RESULTS['policies'][this_policy_id]['alertCount']
else:
RESULTS['alert_counts_from_policies']['mode']['custom'] += RESULTS['policies'][this_policy_id]['alertCount']
# Create sets and lists of Compliance Standards to create a sorted, unique list of counters for each Compliance Standard.
RESULTS['policies'][this_policy_id]['complianceStandards'] = []
if 'complianceMetadata' in this_policy:
compliance_standards_set = set()
for standard in this_policy['complianceMetadata']:
compliance_standards_set.add(standard['standardName'])
compliance_standards_list = list(compliance_standards_set)
compliance_standards_list.sort()
RESULTS['policies'][this_policy_id]['complianceStandards'] = compliance_standards_list
for compliance_standard_name in compliance_standards_list:
RESULTS['compliance_standards_from_policies'].setdefault(compliance_standard_name, policy_severities())
RESULTS['compliance_standards_from_policies'][compliance_standard_name][this_policy['severity']] += RESULTS['policies'][this_policy_id]['alertCount']
##########################################################################################
# Loop through all Alerts and collect the details of each Alert.
# Alert data includes Open and Closed Alerts.
# Some details come from the Alert, some from the related Policy and Compliance Standards.
# Alerts can contain a reference to a Policy that has been deleted.
# SUPPORT_API_MODE: Substitute aggregated Alerts (as '/_support/policy' does not return openAlertsCount).
##########################################################################################
def process_alerts(alerts):
if CONFIG['SUPPORT_API_MODE']:
RESULTS['policy_counts_from_alerts']['severity']['critical'] = RESULTS['alerts_aggregated_by']['severity']['critical']
RESULTS['policy_counts_from_alerts']['severity']['high'] = RESULTS['alerts_aggregated_by']['severity']['high']
RESULTS['policy_counts_from_alerts']['severity']['medium'] = RESULTS['alerts_aggregated_by']['severity']['medium']
RESULTS['policy_counts_from_alerts']['severity']['low'] = RESULTS['alerts_aggregated_by']['severity']['low']
RESULTS['policy_counts_from_alerts']['severity']['informational'] = RESULTS['alerts_aggregated_by']['severity']['informational']
RESULTS['policy_counts_from_alerts']['type']['anomaly'] = RESULTS['alerts_aggregated_by']['type']['anomaly']
RESULTS['policy_counts_from_alerts']['type']['audit_event'] = RESULTS['alerts_aggregated_by']['type']['audit_event']
RESULTS['policy_counts_from_alerts']['type']['config'] = RESULTS['alerts_aggregated_by']['type']['config']
RESULTS['policy_counts_from_alerts']['type']['data'] = RESULTS['alerts_aggregated_by']['type']['data']
RESULTS['policy_counts_from_alerts']['type']['iam'] = RESULTS['alerts_aggregated_by']['type']['iam']
RESULTS['policy_counts_from_alerts']['type']['network'] = RESULTS['alerts_aggregated_by']['type']['network']
RESULTS['policy_counts_from_alerts']['type']['workload_incident'] = RESULTS['alerts_aggregated_by']['type']['workload_incident']
RESULTS['policy_counts_from_alerts']['type']['workload_vulnerability'] = RESULTS['alerts_aggregated_by']['type']['workload_vulnerability']
RESULTS['alert_counts_from_alerts']['status']['open'] = RESULTS['alerts_aggregated_by']['status']['open']
RESULTS['alert_counts_from_alerts']['status']['resolved'] = RESULTS['alerts_aggregated_by']['status']['resolved']
else:
for this_alert in alerts:
this_policy_id = this_alert['policy']['policyId']
if this_alert['policy']['systemDefault'] == True:
RESULTS['alert_counts_from_alerts']['mode']['default'] += 1
else:
RESULTS['alert_counts_from_alerts']['mode']['custom'] += 1
RESULTS['alert_counts_from_alerts']['type'][this_alert['policy']['policyType']] += 1
if this_alert['policy']['remediable']:
RESULTS['alert_counts_from_alerts']['feature']['remediable'] += 1
RESULTS['alert_counts_from_alerts']['status_by_feature']['remediable'][this_alert['status']] += 1
RESULTS['alert_counts_from_alerts']['status'][this_alert['status']] += 1
if 'reason' in this_alert:
if this_alert['reason'] == 'RESOURCE_DELETED':
RESULTS['alert_counts_from_alerts']['resolved_by_resource']['deleted'] += 1
if this_alert['reason'] == 'RESOURCE_UPDATED':
RESULTS['alert_counts_from_alerts']['resolved_by_resource']['updated'] += 1
if 'resource' in this_alert:
if 'rrn' in this_alert['resource']:
RESULTS['resources_from_alerts'][this_alert['resource']['rrn']] = this_alert['resource']['rrn']
#
# This is all of the data we can collect without a reference to a Policy.
#
if not this_policy_id in RESULTS['policies']:
if 'reason' in this_alert:
if this_alert['reason'] == 'POLICY_DELETED':
RESULTS['deleted_policies_from_alerts'].setdefault(this_policy_id, 0)
RESULTS['deleted_policies_from_alerts'][this_policy_id] += 1
RESULTS['alert_counts_from_alerts']['resolved_by_policy']['deleted'] += 1
if CONFIG['DEBUG_MODE']:
output('Skipping Alert: Related Policy Not Found: Policy ID: %s' % this_policy_id)
continue
# Policy data from the related Policy.
policy_name = RESULTS['policies'][this_policy_id]['policyName']
RESULTS['policies_from_alerts'].setdefault(policy_name, {'policyId': this_policy_id, 'alertCount': 0})
RESULTS['policies_from_alerts'][policy_name]['alertCount'] += 1
RESULTS['policy_counts_from_alerts']['severity'][RESULTS['policies'][this_policy_id]['policySeverity']] += 1
RESULTS['policy_counts_from_alerts']['type'][RESULTS['policies'][this_policy_id]['policyType']] += 1
if RESULTS['policies'][this_policy_id]['policyEnabled'] == False:
RESULTS['disabled_policies_from_alerts'].setdefault(policy_name, 0)
RESULTS['disabled_policies_from_alerts'][policy_name] += 1
RESULTS['alert_counts_from_alerts']['policy']['disabled'] += 1
# Compliance Standard data from the related Policy.
for compliance_standard_name in RESULTS['policies'][this_policy_id]['complianceStandards']:
RESULTS['compliance_standards_from_alerts'].setdefault(compliance_standard_name, policy_severities())
RESULTS['compliance_standards_from_alerts'][compliance_standard_name][RESULTS['policies'][this_policy_id]['policySeverity']] += 1
# Alert data from the related Policy.
RESULTS['alert_counts_from_alerts']['cloud_type'][RESULTS['policies'][this_policy_id]['policyCloudType']] += 1
if RESULTS['policies'][this_policy_id]['policyShiftable']:
RESULTS['alert_counts_from_alerts']['feature']['shiftable'] += 1
if RESULTS['policies'][this_policy_id]['policyRemediable']:
RESULTS['alert_counts_from_alerts']['feature']['remediable'] += 1
if RESULTS['policies'][this_policy_id]['policyShiftableRemediable']:
RESULTS['alert_counts_from_alerts']['feature']['shiftable_and_remediable'] += 1
RESULTS['alert_counts_from_alerts']['severity_by_status'][this_alert['status']][RESULTS['policies'][this_policy_id]['policySeverity']] += 1
##########################################################################################
# Process mode: Summarize the data.
##########################################################################################
def process_summary():
RESULTS['summary']['count_of_assets'] = DATA['ASSETS']['summary']['totalResources']
if CONFIG['SUPPORT_API_MODE']:
RESULTS['summary']['count_of_policies_with_alerts_from_policies'] = len(RESULTS['alerts_aggregated_by']['policy'])
RESULTS['summary']['count_of_aggregated_open_alerts'] = RESULTS['alerts_aggregated_by']['status']['open']
else:
RESULTS['summary']['count_of_resources_with_alerts_from_alerts'] = len(RESULTS['resources_from_alerts'].keys())
RESULTS['summary']['count_of_policies_with_alerts_from_policies'] = sum(v['alertCount'] != 0 for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_open_closed_alerts'] = len(DATA['ALERTS'])
RESULTS['summary']['count_of_compliance_standards_with_alerts_from_policies'] = sum(v != policy_severities() for k,v in RESULTS['compliance_standards_from_policies'].items())
RESULTS['summary']['count_of_compliance_standards_with_alerts_from_alerts'] = len(RESULTS['compliance_standards_from_alerts'])
RESULTS['summary']['count_of_policies_with_alerts_from_alerts'] = len(RESULTS['policies_from_alerts'])
#
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['aws'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'aws' for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['azure'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'azure' for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['gcp'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'gcp' for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['alibaba_cloud'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'alibaba_cloud' for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['oci'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'oci' for k,v in RESULTS['policies'].items())
RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['all'] = sum(v['alertCount'] != 0 and v['policyCloudType'].lower() == 'all' for k,v in RESULTS['policies'].items())
##########################################################################################
# Process mode: Output the data.
##########################################################################################
def output_collected_data():
panda_writer = open_sheet(CONFIG['OUTPUT_FILE_XLS'])
output_utilization(panda_writer)
output_alerts_by_compliance_standard(panda_writer)
output_alerts_by_policy(panda_writer)
output_alerts_summary(panda_writer)
save_sheet(panda_writer)
output('Results saved as: %s' % CONFIG['OUTPUT_FILE_XLS'])
##
def upi_group(policy_upi = ''):
# pylint: disable=anomalous-backslash-in-string
upi_search = re.search('^(.*?)\-(\d+)$', policy_upi)
if upi_search:
return upi_search.group(1)
return policy_upi
##
def output_utilization(panda_writer):
output('Saving Utilization Worksheet')
output()
rows = [
('Number of Assets', RESULTS['summary']['count_of_assets']),
('',''),
('Number of Cloud Accounts', len(DATA['ACCOUNTS'])),
('',''),
('Cloud Accounts Disabled', sum(x.get('enabled') == False for x in DATA['ACCOUNTS'])),
('Cloud Accounts Enabled', sum(x.get('enabled') == True for x in DATA['ACCOUNTS'])),
('',''),
('Cloud Accounts AWS', sum(x.get('cloudType').lower() == 'aws' for x in DATA['ACCOUNTS'])),
('Cloud Accounts Azure', sum(x.get('cloudType').lower() == 'azure' for x in DATA['ACCOUNTS'])),
('Cloud Accounts Google', sum(x.get('cloudType').lower() == 'gcp' for x in DATA['ACCOUNTS'])),
('Cloud Accounts Alibaba', sum(x.get('cloudType').lower() == 'alibaba_cloud' for x in DATA['ACCOUNTS'])),
('Cloud Accounts Oracle', sum(x.get('cloudType').lower() == 'oci' for x in DATA['ACCOUNTS'])),
('',''),
('Number of Cloud Account Groups', len(DATA['GROUPS'])),
('',''),
('Number of Alert Rules', len(DATA['RULES'])),
('',''),
('Alert Rules Disabled', sum(x.get('enabled') == False for x in DATA['RULES'])),
('Alert Rules Enabled', sum(x.get('enabled') == True for x in DATA['RULES'])),
('',''),
('Number of Integrations', len(DATA['INTEGRATIONS'])),
('',''),
('Integrations Disabled', sum(x.get('enabled') == False for x in DATA['INTEGRATIONS'])),
('Integrations Enabled', sum(x.get('enabled') == True for x in DATA['INTEGRATIONS'])),
('',''),
('Number of Policies', len(DATA['POLICIES'])),
('',''),
('Policies Disabled', sum(x.get('enabled') == False for x in DATA['POLICIES'])),
('Policies Enabled', sum(x.get('enabled') == True for x in DATA['POLICIES'])),
('',''),
('Policies Custom', sum(x.get('systemDefault') == False for x in DATA['POLICIES'])),
('Policies Default', sum(x.get('systemDefault') == True for x in DATA['POLICIES'])),
('',''),
('Number of Users', len(DATA['USERS'])),
('',''),
('Users Disabled', sum(x.get('enabled') == False for x in DATA['USERS'])),
('Users Enabled', sum(x.get('enabled') == True for x in DATA['USERS'])),
]
if CONFIG['SUPPORT_API_MODE']:
rows.append(('',''))
rows.append(('Data Collected using the Support API',''))
write_sheet(panda_writer, 'Utilization Summary', rows)
##
def output_alerts_by_compliance_standard(panda_writer):
output('Saving Alerts by Compliance Standard Worksheet(s)')
output()
rows = []
rows.append(('Compliance Standard', 'Alerts Critical', 'Alerts High', 'Alerts Medium', 'Alerts Low', 'Alerts Informational'))
if CONFIG['SUPPORT_API_MODE']:
for compliance_standard_name in sorted(RESULTS['compliance_standards_from_policies']):
alert_count_critical = RESULTS['compliance_standards_from_policies'][compliance_standard_name]['critical']
alert_count_high = RESULTS['compliance_standards_from_policies'][compliance_standard_name]['high']
alert_count_medium = RESULTS['compliance_standards_from_policies'][compliance_standard_name]['medium']
alert_count_low = RESULTS['compliance_standards_from_policies'][compliance_standard_name]['low']
alert_count_informational = RESULTS['compliance_standards_from_policies'][compliance_standard_name]['informational']
rows.append((compliance_standard_name, alert_count_critical, alert_count_high, alert_count_medium, alert_count_low, alert_count_informational))
write_sheet(panda_writer, 'Open Alerts by Standard', rows)
else:
for compliance_standard_name in sorted(RESULTS['compliance_standards_from_alerts']):
alert_count_critical = RESULTS['compliance_standards_from_alerts'][compliance_standard_name]['critical']
alert_count_high = RESULTS['compliance_standards_from_alerts'][compliance_standard_name]['high']
alert_count_medium = RESULTS['compliance_standards_from_alerts'][compliance_standard_name]['medium']
alert_count_low = RESULTS['compliance_standards_from_alerts'][compliance_standard_name]['low']
alert_count_informational = RESULTS['compliance_standards_from_alerts'][compliance_standard_name]['informational']
rows.append((compliance_standard_name, alert_count_critical, alert_count_high, alert_count_medium, alert_count_low, alert_count_informational))
rows.append((''))
rows.append((''))
rows.append(('Time Range: %s' % CONFIG['TIME_RANGE_LABEL'], ''))
write_sheet(panda_writer, 'Alerts by Standard', rows)
##
def output_alerts_by_policy(panda_writer):
output('Saving Alerts by Policy Worksheet(s)')
output()
rows = []
rows.append(('Policy', 'UPI', 'UPI Group', 'Default', 'Alert Count', 'Enabled', 'Severity', 'Type', 'SubTypes', 'Category', 'Class', 'Cloud Provider', 'With IAC', 'With Remediation', 'Labels', 'Compliance Standards'))
if CONFIG['SUPPORT_API_MODE']:
# Consider replacing sorted(RESULTS['policies_by_name']) with sorted(RESULTS['policies'], key=lambda x: (RESULTS['policies'][x]['name'])
for policy_name in sorted(RESULTS['policies_by_name']):
this_policy_id = RESULTS['policies_by_name'][policy_name]['policyId']
policy_upi = RESULTS['policies'][this_policy_id]['policyUpi']
policy_upi_group = upi_group(policy_upi)
policy_default = RESULTS['policies'][this_policy_id]['policySystemDefault']
policy_alert_count = RESULTS['policies'][this_policy_id]['alertCount']
policy_enabled = RESULTS['policies'][this_policy_id]['policyEnabled']
policy_severity = RESULTS['policies'][this_policy_id]['policySeverity'].title()
policy_subtypes = ', '.join(RESULTS['policies'][this_policy_id]['policySubTypes']).upper()
policy_type = RESULTS['policies'][this_policy_id]['policyType'].title()
policy_category = RESULTS['policies'][this_policy_id]['policyCategory'].title()
policy_class = RESULTS['policies'][this_policy_id]['policyClass'].title()
policy_cloud_type = RESULTS['policies'][this_policy_id]['policyCloudType'].upper()
policy_is_shiftable = RESULTS['policies'][this_policy_id]['policyShiftable']
policy_is_remediable = RESULTS['policies'][this_policy_id]['policyRemediable']
policy_labels = ', '.join(RESULTS['policies'][this_policy_id]['policyLabels'])
policy_standards_list = ', '.join(map(str, RESULTS['policies'][this_policy_id]['complianceStandards']))
rows.append((policy_name, policy_upi, policy_upi_group, policy_default, policy_alert_count, policy_enabled, policy_severity, policy_type, policy_subtypes, policy_category, policy_class, policy_cloud_type, policy_is_shiftable, policy_is_remediable, policy_labels, policy_standards_list))
write_sheet(panda_writer, 'Open Alerts by Policy', rows)
else:
for policy_name in sorted(RESULTS['policies_from_alerts']):
this_policy_id = RESULTS['policies_from_alerts'][policy_name]['policyId']
policy_upi = RESULTS['policies'][this_policy_id]['policyUpi']
policy_upi_group = upi_group(policy_upi)
policy_default = RESULTS['policies'][this_policy_id]['policySystemDefault']
policy_alert_count = RESULTS['policies_from_alerts'][policy_name]['alertCount'] # Not RESULTS['policies'][this_policy_id]['openAlertsCount']
policy_enabled = RESULTS['policies'][this_policy_id]['policyEnabled']
policy_severity = RESULTS['policies'][this_policy_id]['policySeverity'].title()
policy_type = RESULTS['policies'][this_policy_id]['policyType'].title()
policy_subtypes = ', '.join(RESULTS['policies'][this_policy_id]['policySubTypes']).upper()
policy_category = RESULTS['policies'][this_policy_id]['policyCategory'].title()
policy_class = RESULTS['policies'][this_policy_id]['policyClass'].title()
policy_cloud_type = RESULTS['policies'][this_policy_id]['policyCloudType'].upper()
policy_is_shiftable = RESULTS['policies'][this_policy_id]['policyShiftable']
policy_is_remediable = RESULTS['policies'][this_policy_id]['policyRemediable']
policy_labels = ', '.join(RESULTS['policies'][this_policy_id]['policyLabels'])
policy_standards_list = ', '.join(map(str, RESULTS['policies'][this_policy_id]['complianceStandards']))
rows.append((policy_name, policy_upi, policy_upi_group, policy_default, policy_alert_count, policy_enabled, policy_severity, policy_type, policy_subtypes, policy_category, policy_class, policy_cloud_type, policy_is_shiftable, policy_is_remediable, policy_labels, policy_standards_list))
rows.append((''))
rows.append((''))
rows.append(('Time Range: %s' % CONFIG['TIME_RANGE_LABEL'], ''))
write_sheet(panda_writer, 'Alerts by Policy', rows)
##
def output_alerts_summary(panda_writer):
output('Saving Alerts Summary Worksheet(s)')
output()
if CONFIG['SUPPORT_API_MODE']:
rows = [
('Number of Compliance Standards with Open Alerts', RESULTS['summary']['count_of_compliance_standards_with_alerts_from_policies']),
('',''),
('Number of Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies']),
('',''),
('AWS Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['aws']),
('Azure Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['azure']),
('GCP Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['gcp']),
('Alibaba Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['alibaba_cloud']),
('OCI Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['oci']),
('Cross-Cloud Policies with Open Alerts', RESULTS['summary']['count_of_policies_with_alerts_from_policies_by_cloud']['all']),
('',''),
('Number of Open Alerts', RESULTS['alert_counts_from_policies']['status']['open']),
('',''),
('Open Alerts Critical-Severity', RESULTS['alert_counts_from_policies']['severity']['critical']),
('Open Alerts High-Severity', RESULTS['alert_counts_from_policies']['severity']['high']),
('Open Alerts Medium-Severity', RESULTS['alert_counts_from_policies']['severity']['medium']),
('Open Alerts Low-Severity', RESULTS['alert_counts_from_policies']['severity']['low']),
('Open Alerts Informational-Severity', RESULTS['alert_counts_from_policies']['severity']['informational']),
('',''),