/
utils.py
1270 lines (1108 loc) · 52.9 KB
/
utils.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
import os
import re
import sys
import copy
import json
import yaml
import logging
import dateutil.parser
import struct
import textwrap
import base64
try:
from urllib.parse import quote_plus,unquote_plus
except:
from urllib import quote_plus,unquote_plus
from prettytable import PrettyTable, PLAIN_COLUMNS, ALL
from collections import OrderedDict
import anchorecli.clients.apiexternal
_logger = logging.getLogger(__name__)
def setup_config(cli_opts):
ret = {
'user':None,
'pass':None,
'url':"http://localhost:8228/v1",
'hub-url':"https://hub.anchore.io/",
'api-version': None,
'ssl_verify':True,
'jsonmode':False,
'debug':False,
'as_account': None
}
settings = {}
# load up credentials file if present
try:
home = os.path.expanduser('~')
credential_file = os.path.join(home, '.anchore', 'credentials.yaml')
if os.path.exists(credential_file):
ydata = {}
with open(credential_file, 'r') as FH:
try:
ydata = yaml.safe_load(FH)
except Exception as err:
raise Exception("YAML load failed: " + str(err))
if ydata:
try:
if type(ydata) != type(dict()):
raise Exception("invalid credentials file format")
default_creds = ydata.get('default', {})
for e in ['ANCHORE_CLI_USER', 'ANCHORE_CLI_PASS', 'ANCHORE_CLI_URL', 'ANCHORE_CLI_HUB_URL', 'ANCHORE_CLI_API_VERSION', 'ANCHORE_CLI_SSL_VERIFY']:
if e in default_creds:
settings[e] = default_creds[e]
except Exception as err:
raise Exception("credentials file exists and has data, but cannot parse: " + str(err))
except Exception as err:
raise Exception("error while processing credentials file, please check format and read permissions - exception: " + str(err))
# load environment if present
try:
for e in ['ANCHORE_CLI_USER', 'ANCHORE_CLI_PASS', 'ANCHORE_CLI_URL', 'ANCHORE_CLI_HUB_URL', 'ANCHORE_CLI_API_VERSION', 'ANCHORE_CLI_SSL_VERIFY', 'ANCHORE_CLI_JSON', 'ANCHORE_CLI_DEBUG', 'ANCHORE_CLI_ACCOUNT']:
if e in os.environ:
settings[e] = os.environ[e]
except Exception as err:
raise err
# load cmdline options
try:
if cli_opts['u']:
settings['ANCHORE_CLI_USER'] = cli_opts['u']
if cli_opts['p']:
settings['ANCHORE_CLI_PASS'] = cli_opts['p']
if cli_opts['url']:
settings['ANCHORE_CLI_URL'] = cli_opts['url']
if cli_opts['hub-url']:
settings['ANCHORE_CLI_HUB_URL'] = cli_opts['hub-url']
if cli_opts['api-version']:
settings['ANCHORE_CLI_API_VERSION'] = cli_opts['api-version']
if cli_opts['insecure']:
settings['ANCHORE_CLI_SSL_VERIFY'] = "n"
if cli_opts['json']:
settings['ANCHORE_CLI_JSON'] = "y"
if cli_opts['debug']:
settings['ANCHORE_CLI_DEBUG'] = "y"
if cli_opts.get('as_account') is not None:
settings['ANCHORE_CLI_ACCOUNT'] = cli_opts['as_account']
except Exception as err:
raise err
try:
if 'ANCHORE_CLI_USER' in settings:
ret['user'] = settings['ANCHORE_CLI_USER']
if 'ANCHORE_CLI_PASS' in settings:
ret['pass'] = settings['ANCHORE_CLI_PASS']
if 'ANCHORE_CLI_URL' in settings:
ret['url'] = settings['ANCHORE_CLI_URL']
if 'ANCHORE_CLI_HUB_URL' in settings:
ret['hub-url'] = settings['ANCHORE_CLI_HUB_URL']
if 'ANCHORE_CLI_API_VERSION' in settings:
ret['api-version'] = settings['ANCHORE_CLI_API_VERSION']
if 'ANCHORE_CLI_SSL_VERIFY' in settings:
if settings['ANCHORE_CLI_SSL_VERIFY'].lower() == 'n':
ret['ssl_verify'] = False
if 'ANCHORE_CLI_JSON' in settings:
if settings['ANCHORE_CLI_JSON'].lower() == 'y':
ret['jsonmode'] = True
if 'ANCHORE_CLI_DEBUG' in settings:
if settings['ANCHORE_CLI_DEBUG'].lower() == 'y':
ret['debug'] = True
if 'ANCHORE_CLI_ACCOUNT' in settings:
ret['as_account'] = settings['ANCHORE_CLI_ACCOUNT']
except Exception as err:
raise err
return(ret)
def doexit(ecode):
try:
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass
sys.exit(ecode)
def group_list_of_dicts(indict, bykey):
ret = []
gdict = {}
for el in indict:
elkey = el[bykey]
if elkey not in gdict:
gdict[elkey] = []
gdict[elkey].append(el)
for k in list(gdict.keys()):
for el in gdict[k]:
ret.append(el)
return(ret)
def format_error_output(config, op, params, payload):
try:
errdata = json.loads(str(payload))
except:
errdata = {'message': str(payload)}
if config['jsonmode']:
ret = json.dumps(errdata, indent=4, sort_keys=True)
return(ret)
# error message overrides
#if op == 'image_add':
#if 'httpcode' in errdata and errdata['httpcode'] == 404:
# errdata['message'] = "image cannot be found/fetched from registry"
obuf = ""
try:
outdict = OrderedDict()
if 'message' in errdata:
outdict['Error'] = str(errdata['message'])
if 'httpcode' in errdata:
outdict['HTTP Code'] = str(errdata['httpcode'])
if 'detail' in errdata and errdata['detail']:
outdict['Detail'] = str(errdata['detail'])
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
if not obuf:
raise Exception("not JSON output could be parsed from error response")
#obuf = obuf + "\n"
except Exception as err:
obuf = str(payload)
# operation-specific output postfixes
if op in ['account_delete']:
if "Invalid account state change requested" in errdata.get('message', ""):
obuf = obuf + "\nNOTE: accounts must be disabled (anchore-cli account disable <account>) in order to be deleted\n"
ret = obuf
return(ret)
def format_output(config, op, params, payload):
if config['jsonmode']:
try:
ret = json.dumps(payload, indent=4, sort_keys=True)
except:
ret = json.dumps({'payload': str(payload)}, indent=4, sort_keys=True)
return(ret)
ret = ""
try:
if op == 'image_list':
if params['show_all']:
filtered_records = payload
else:
# this creates a filtered list w only the latest image records of any found tags
latest_tag_details = {}
latest_records = {}
for image_record in payload:
for image_detail in image_record['image_detail']:
fulltag = image_detail['fulltag']
tagts = dateutil.parser.parse(image_detail['created_at'])
if fulltag not in latest_tag_details:
latest_tag_details[fulltag] = image_detail
latest_records[fulltag] = image_record
else:
lasttagts = dateutil.parser.parse(latest_tag_details[fulltag]['created_at'])
if tagts >= lasttagts:
latest_tag_details[fulltag] = image_detail
latest_records[fulltag] = image_record
filtered_records = list(latest_records.values())
if params['full']:
header = ['Full Tag', 'Image Digest', 'Analysis Status', 'Image ID']
else:
header = ['Full Tag', 'Image Digest', 'Analysis Status']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
add_rows = []
for image_record in filtered_records:
for image_detail_record in image_record['image_detail']:
image_detail = copy.deepcopy(image_detail_record)
dockerpresent = imageId = fulltag = registy = "None"
dockerfile = image_detail.pop('dockerfile', None)
if dockerfile:
dockerpresent = "Present"
imageId = image_detail.pop('imageId', "None")
fulltag = image_detail.pop('registry', "None") + "/" + image_detail.pop('repo', "None") + ":" + image_detail.pop('tag', "None")
#registry = image_detail.pop('registry', "None")
if params['full']:
row = [fulltag, image_record['imageDigest'], image_record['analysis_status'], imageId]
else:
row = [fulltag, image_record['imageDigest'], image_record['analysis_status']]
if row not in add_rows:
add_rows.append(row)
for row in add_rows:
t.add_row(row)
ret = t.get_string(sortby='Full Tag')
elif op == 'image_vuln':
obuf = ""
if 'query_type' not in params or not params['query_type']:
outdict = OrderedDict()
for t in payload:
outdict[t] = "available"
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
else:
if params['query_type'] in ['os', 'non-os', 'all']:
header = ['Vulnerability ID', 'Package', 'Severity', 'Fix', 'CVE Refs', 'Vulnerability URL']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['vulnerabilities']:
cve_refs = {}
if el.get('nvd_data', []):
for nvd_record in el.get('nvd_data'):
cve_refs[nvd_record.get('id')] = True
cve_ref_str = ','.join(cve_refs.keys())
row = [el['vuln'], el['package'], el['severity'], el['fix'], cve_ref_str, el['url']]
t.add_row(row)
obuf = obuf + t.get_string(sortby='Severity')
else:
try:
if payload['vulnerabilities']:
el = payload['vulnerabilities'][0]
header = list(el.keys())
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['vulnerabilities']:
row = []
for k in header:
row.append(el[k])
t.add_row(row)
obuf = obuf + t.get_string()
else:
raise Exception("no vulnerabilities available for input type ("+str(params['query_type']) + ")")
except Exception as err:
raise Exception("could not parse content result - exception: " + str(err))
ret = obuf
elif op in ['image_content', 'image_metadata']:
obuf = ""
if 'query_type' not in params or not params['query_type']:
outdict = OrderedDict()
for t in payload:
outdict[t] = "available"
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
else:
if params['query_type'] == 'os':
header = ['Package', 'Version', 'License']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['content']:
row = [el['package'], el['version'], el['license']]
t.add_row(row)
obuf = obuf + t.get_string(sortby='Package')
elif params['query_type'] == 'files':
header = ['Filename', 'Size']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['content']:
row = [el['filename'], el['size']]
t.add_row(row)
obuf = obuf + t.get_string(sortby='Size', reversesort=True)
elif params['query_type'] in ['npm', 'gem', 'python']:
header = ['Package', 'Version', 'Location']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['content']:
row = [el['package'], el['version'], el['location']]
t.add_row(row)
obuf = obuf + t.get_string(sortby='Package')
elif params['query_type'] in ['java']:
header = ['Package', 'Specification-Version', 'Implementation-Version', 'Location']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['content']:
row = [el['package'], el['specification-version'], el['implementation-version'], el['location']]
t.add_row(row)
obuf = obuf + t.get_string(sortby='Package')
elif params['query_type'] in ['manifest', 'dockerfile', 'docker_history']:
try:
obuf = base64.b64decode(payload.get('metadata', "")).decode('utf-8')
except Exception as err:
obuf = ""
else:
try:
if payload['content']:
el = payload['content'][0]
header = list(el.keys())
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload['content']:
row = []
for k in header:
row.append(el[k])
t.add_row(row)
obuf = obuf + t.get_string()
else:
raise Exception("no content available for input type ("+str(params['query_type']) + ")")
except Exception as err:
raise Exception("could not parse content result - exception: " + str(err))
ret = obuf
elif op in ['image_add', 'image_get', 'image_import']:
obuf = ""
for image_record in payload:
outdict = OrderedDict()
outdict['Image Digest'] = str(image_record['imageDigest'])
if image_record.get('parentDigest', None):
outdict['Parent Digest'] = str(image_record['parentDigest'])
outdict['Analysis Status'] = str(image_record['analysis_status'])
outdict['Image Type'] = str(image_record['image_type'])
outdict['Analyzed At'] = str(image_record['analyzed_at'])
image_detail = copy.deepcopy(image_record['image_detail'][0])
dockerfile = image_detail.pop('dockerfile', None)
dockerpresent = "None"
if dockerfile:
dockerpresent = "Present"
imageId = image_detail.pop('imageId', "None")
outdict['Image ID'] = str(imageId)
#outdict['Dockerfile'] = str(dockerpresent)
if 'image_content' in image_record and image_record['image_content']:
image_content = image_record['image_content']
if 'metadata' in image_content and image_content['metadata']:
image_content_metadata = image_content['metadata']
outdict['Dockerfile Mode'] = str(image_content_metadata['dockerfile_mode'])
outdict['Distro'] = str(image_content_metadata['distro'])
outdict['Distro Version'] = str(image_content_metadata['distro_version'])
outdict['Size'] = str(image_content_metadata['image_size'])
outdict['Architecture'] = str(image_content_metadata['arch'])
outdict['Layer Count'] = str(image_content_metadata['layer_count'])
if 'annotations' in image_record and image_record['annotations']:
outdict['Annotations'] = ', '.join([str(x)+"="+str(y) for x,y in list(image_record['annotations'].items())])
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
for image_detail_record in image_record['image_detail']:
image_detail = copy.deepcopy(image_detail_record)
outdict = OrderedDict()
outdict['Full Tag'] = str(image_detail.pop('fulltag', "None"))
outdict['Tag Detected At'] = str(image_detail.pop('tag_detected_at', "None"))
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
ret = obuf
elif op in ['registry_add', 'registry_get', 'registry_update']:
obuf = ""
for registry_record in payload:
outdict = OrderedDict()
outdict['Registry'] = str(registry_record['registry'])
outdict['Name'] = str(registry_record.get('registry_name', "N/A"))
outdict['User'] = str(registry_record['registry_user'])
outdict['Type'] = str(registry_record['registry_type'])
outdict['Verify TLS'] = str(registry_record['registry_verify'])
outdict['Created'] = str(registry_record['created_at'])
outdict['Updated'] = str(registry_record['last_updated'])
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
ret = obuf
elif op == 'registry_list':
header = ['Registry', 'Name', 'Type', 'User']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for registry_record in payload:
row = [registry_record['registry'], registry_record.get('registry_name', "N/A"), registry_record['registry_type'], registry_record['registry_user']]
t.add_row(row)
ret = t.get_string(sortby='Registry')
elif op == 'subscription_list':
header = ['Tag', 'Subscription Type', 'Active']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for subscription_record in payload:
row = [subscription_record['subscription_key'], subscription_record['subscription_type'], str(subscription_record['active'])]
t.add_row(row)
ret = t.get_string(sortby='Tag')
elif op == 'repo_list':
header = ['Repository', 'Watched', 'TagCount']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for subscription_record in payload:
try:
sval = json.loads(subscription_record['subscription_value'])
tagcount = str(sval['tagcount'])
except:
tagcount = 'N/A'
row = [subscription_record['subscription_key'], str(subscription_record['active']), str(tagcount)]
t.add_row(row)
ret = t.get_string(sortby='Repository')
elif op in ['repo_get', 'repo_watch', 'repo_unwatch', 'repo_add']:
header = ['Repository', 'Watched', 'TagCount']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for subscription_record in payload:
sval = json.loads(subscription_record['subscription_value'])
try:
tagcount = str(sval['tagcount'])
except:
tagcount = 'N/A'
row = [subscription_record['subscription_key'], str(subscription_record['active']), str(tagcount)]
t.add_row(row)
ret = t.get_string(sortby='Repository')
elif op in ['policy_add', 'policy_get']:
if 'detail' in params and params['detail']:
try:
ret = json.dumps(payload[0]['policybundle'], indent=4, sort_keys=True)
except:
ret = json.dumps(payload, indent=4, sort_keys=True)
else:
obuf = ""
if op == 'policy_add':
payload = [payload]
else:
pass
for policy_record in payload:
outdict = OrderedDict()
outdict['Policy ID'] = str(policy_record['policyId'])
outdict['Active'] = str(policy_record['active'])
outdict['Source'] = str(policy_record['policy_source'])
outdict['Created'] = str(policy_record['created_at'])
outdict['Updated'] = str(policy_record['last_updated'])
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
ret = obuf
elif op == 'policy_list':
header = ['Policy ID', 'Active', 'Created', 'Updated']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for policy_record in payload:
row = [policy_record['policyId'], str(policy_record['active']), policy_record['created_at'], policy_record['last_updated']]
t.add_row(row)
ret = t.get_string(sortby='Active', reversesort=True)
elif op == 'policy_hub_list':
header = ['Name', 'Description']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
last_updated = payload['metadata']['last_updated']
for record in payload['content']:
if record.get('type', None) == 'bundle':
row = [textwrap.fill(record['name'], width=40), textwrap.fill(record['description'], width=60)]
t.add_row(row)
ret = t.get_string(sortby='Name', reversesort=True)
elif op == 'policy_hub_get':
obuf = ""
outdict = OrderedDict()
outdict['Policy Bundle ID'] = str(payload['id'])
outdict['Name'] = str(payload['name'])
outdict['Description'] = str(payload.get('description', payload.get('comment', "N/A")))
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
id_to_name = {}
for record in payload['policies']:
outdict = OrderedDict()
outdict['Policy Name'] = record['name']
#outdict['Policy ID'] = record['id']
outdict['Policy Description'] = str(record.get('description', record.get('comment', "N/A")))
id_to_name[record['id']] = record['name']
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
for record in payload['whitelists']:
outdict = OrderedDict()
outdict['Whitelist Name'] = record['name']
#outdict['Whitelist ID'] = record['id']
outdict['Whitelist Description'] = str(record.get('description', record.get('comment', "N/A")))
id_to_name[record['id']] = record['name']
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
for record in payload['mappings']:
outdict = OrderedDict()
outdict['Mapping Name'] = record['name']
outdict['Mapping Rule'] = "{}/{}:{}".format(record['registry'],record['repository'],record['image']['value'])
pids = []
pid = record.get('policy_id', None)
if pid:
pids.append(pid)
pids = [str(id_to_name[x]) for x in pids + record.get('policy_ids', [])]
outdict['Mapping Policies'] = ",".join(pids)
wids = [str(id_to_name[x]) for x in record.get('whitelist_ids', [])]
outdict['Mapping Whitelists'] = ",".join(wids)
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
ret = obuf
#ret = json.dumps(payload, indent=4, sort_keys=True)
elif op == 'evaluate_check':
obuf = ""
for eval_record in payload:
outdict = OrderedDict()
for imageDigest in list(eval_record.keys()):
for fulltag in eval_record[imageDigest]:
if not eval_record[imageDigest][fulltag]:
outdict['Image Digest'] = str(imageDigest)
outdict['Full Tag'] = str(fulltag)
outdict['Status'] = 'no_eval_available'
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
else:
for evaldata in eval_record[imageDigest][fulltag]:
outdict['Image Digest'] = str(imageDigest)
outdict['Full Tag'] = str(fulltag)
if 'detail' in params and params['detail']:
evaldetail = evaldata['detail']
outdict['Image ID'] = str(evaldetail['result']['image_id'])
outdict['Status'] = str(evaldata['status'])
outdict['Last Eval'] = str(evaldata['last_evaluation'])
outdict['Policy ID'] = str(evaldata['policyId'])
t = None
if 'detail' in params and params['detail']:
evaldetail = evaldata['detail']
imageId = evaldetail['result']['image_id']
try:
outdict['Final Action'] = str(evaldetail['result']['final_action'])
outdict['Final Action Reason'] = str(evaldetail['result']['final_action_reason'])
except:
pass
evalresults = evaldetail['result']['result'][imageId]['result']
header = ['Gate', 'Trigger', 'Detail', 'Status']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for row in evalresults['rows']:
if 'full' in params and params['full']:
detailrow = row[5]
else:
detailrow = row[5]
status_detail = row[6]
try:
if row[7]:
eval_whitelist_detail = row[7]
status_detail = "whitelisted("+eval_whitelist_detail['whitelist_name']+")"
except:
status_detail = row[6]
newrow = [row[3], row[4], detailrow, status_detail]
t.add_row(newrow)
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
if t:
obuf = obuf + "\n"
obuf = obuf + t.get_string() + "\n"
ret = obuf
elif op == 'policy_activate':
try:
ret = "Success: " + str(params['policyId']) + " activated"
except:
ret = 'Success'
elif op == 'system_status':
try:
obuf = ""
outlist = []
db_version = code_version = None
for service_record in payload['service_states']:
service_status = "N/A"
if service_record['status']:
service_status = "up"
else:
service_status = "down ({})".format(service_record['status_message'])
outlist.append("Service "+service_record['servicename']+" ("+service_record['hostid']+", " +service_record['base_url'] +"): " + str(service_status))
if not db_version:
try:
db_version = service_record['service_detail']['db_version']
except:
pass
if not code_version:
try:
code_version = service_record['service_detail']['version']
except:
pass
# override with any discovered API service that is up
try:
if service_record['servicename'] == 'apiext' and service_status == 'up':
api_code_version = service_record['service_detail']['version']
code_version = api_code_version
except:
pass
for k in outlist:
obuf = obuf + k + "\n"
obuf = obuf + "\n"
obuf = obuf + "Engine DB Version: {}\n".format(db_version)
obuf = obuf + "Engine Code Version: {}\n".format(code_version)
ret = obuf
except Exception as err:
raise err
elif op == 'event_delete':
if payload is not None and isinstance(payload, list):
ret = 'Deleted {} events'.format(len(payload)) if payload else 'No matching events found'
else:
ret = 'Success'
elif op in ['describe_gates']:
ret = _format_gates(payload, all=params.get('all', False))
elif op in ['describe_gate_triggers']:
ret = _format_triggers(payload, params.get('gate', '').lower(), all=params.get('all', False))
elif op in ['describe_gate_trigger_params']:
ret = _format_trigger_params(payload, params.get('gate', '').lower(), params.get('trigger', '').lower(), all=params.get('all', False))
elif op in ['system_describe_error_codes']:
header = ['Error Code', 'Description']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload:
error_name = el.get('name', "N/A")
error_description = textwrap.fill(el.get('description', "N/A"), width=60)
t.add_row([error_name, error_description])
ret = t.get_string(sortby="Error Code")+"\n"
elif op in ['system_feeds_list']:
try:
header = ['Feed', 'Group', 'LastSync', 'RecordCount']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for el in payload:
feed = el.get('name', "N/A")
for gel in el['groups']:
last_sync = gel.get('last_sync', None)
if not last_sync:
last_sync = "pending"
t.add_row([feed, gel.get('name', "N/A"), last_sync, gel.get('record_count', "N/A")])
ret = t.get_string(sortby='Feed')+"\n"
except Exception as err:
raise err
elif op in ['system_feeds_flush']:
ret = 'Success'
if type(payload) == list:
header = ['Feed', 'Group', 'Status', 'Records Updated', 'Sync Duration']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for feed in payload:
for group in feed.get('groups'):
row = [feed['feed'], group['group'], group['status'], group['updated_record_count'], '{:.2f}s'.format(group['total_time_seconds'])]
t.add_row(row)
ret = t.get_string(sortby='Feed')
elif op == 'event_list':
header = ['Timestamp', 'Level', 'Event', 'Resource', 'ID']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for event_res in payload['results']:
event = event_res['event']
row = [event['timestamp'], event['level'], event['type'], event['resource'].get('id'), event_res['generated_uuid']]
t.add_row(row)
ret = t.get_string()
elif op == 'event_list_full':
header = ['Timestamp', 'Level', 'Event', 'ResourceType', 'Resource', 'Service', 'Host', 'ID']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for event_res in payload['results']:
event = event_res['event']
row = [event['timestamp'], event['level'], event['type'], event['resource'].get('type'), event['resource'].get('id'), event['source']['servicename'], event['source']['hostid'], event_res['generated_uuid']]
t.add_row(row)
ret = t.get_string()
elif op == 'event_get':
ret = yaml.safe_dump(payload['event'], default_flow_style=False)
elif op == 'query_images_by_vulnerability':
vulnerability_id = params.get('vulnerability_id')
#header = ['Severity', 'Full Tag', 'Package', 'Package Type', 'Namespace', 'Digest']
header = ['Full Tag', 'Severity', 'Package', 'Package Type', 'Namespace', 'Digest']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload.get('images', []):
for tag_record in record.get('image', {}).get('tag_history', []):
for package_record in record.get('vulnerable_packages', []):
row = [tag_record.get('fulltag', "N/A"), package_record.get('severity', "N/A"), "{}-{}".format(package_record.get("name"), package_record.get("version")), package_record.get("type"), package_record.get('namespace', "N/A"), record.get('image', {}).get('imageDigest', "N/A")]
t.add_row(row)
ret = t.get_string()
elif op == 'query_images_by_package':
vulnerability_id = params.get('vulnerability_id')
header = ['Full Tag', 'Package', 'Package Type', 'Digest']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload.get('images', []):
for tag_record in record.get('image', {}).get('tag_history', []):
for package_record in record.get('packages', []):
row = [tag_record.get('fulltag', "N/A"), "{}-{}".format(package_record.get("name"), package_record.get("version")), package_record.get("type"), record.get('image', {}).get('imageDigest', "N/A")]
t.add_row(row)
ret = t.get_string()
elif op == 'account_whoami':
outdict = OrderedDict()
outdict['Username'] = str(payload.get('user', {}).get('username', "N/A"))
outdict['AccountName'] = str(payload.get('account', {}).get('name', "N/A"))
outdict['AccountEmail'] = str(payload.get('account', {}).get('email', "N/A"))
outdict['AccountType'] = str(payload.get('account', {}).get('type', "N/A"))
obuf = ""
for k in list(outdict.keys()):
obuf = obuf + k + ": " + outdict[k] + "\n"
obuf = obuf + "\n"
ret = obuf
elif op in ['account_add', 'account_get']:
outdict = OrderedDict()
outdict['Name'] = str(payload.get('name', "N/A"))
outdict['Email'] = str(payload.get('email', "N/A"))
outdict['Type'] = str(payload.get('type', "N/A"))
outdict['State'] = str(payload.get('state', "N/A"))
outdict['Created'] = str(payload.get('created_at', "N/A"))
obuf = ""
for k in list(outdict.keys()):
obuf = obuf + "{}: {}\n".format(k, outdict[k])
obuf = obuf + "\n"
ret = obuf
elif op in ['account_list']:
header = ['Name', 'Email', 'Type', 'State', 'Created']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record.get('name', "N/A")), str(record.get('email', "N/A")), str(record.get('type', "N/A")), str(record.get('state', "N/A")), str(record.get('created_at', "N/A"))]
t.add_row(row)
#ret = t.get_string()
ret = t.get_string(sortby='Created')+"\n"
elif op in ['user_add', 'user_get']:
outdict = OrderedDict()
outdict['Name'] = str(payload.get('username', "N/A"))
outdict['Type'] = str(payload.get('type', "N/A"))
outdict['Source'] = str(payload.get('source', "N/A"))
outdict['Created'] = str(payload.get('created_at', "N/A"))
obuf = ""
for k in list(outdict.keys()):
obuf = obuf + "{}: {}\n".format(k, outdict[k])
obuf = obuf + "\n"
ret = obuf
elif op in ['user_list']:
header = ['Name', 'Type', 'Source', 'Created']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record.get('username', "N/A")), str(record.get('type', "N/A")), str(record.get('source', "N/A")), str(record.get('created_at', "N/A"))]
t.add_row(row)
ret = t.get_string(sortby='Created')+"\n"
elif op in ['user_setpassword']:
ret = "Password (re)set success"
elif op in ['delete_system_service'] or re.match(".*_delete$", op) or re.match(".*_activate$", op) or re.match(".*_deactivate$", op) or re.match(".*_enable$", op) or re.match(".*_disable$", op):
# NOTE this should always be the last in the if/elif conditional
ret = 'Success'
elif op in ['analysis_archive_list']:
header = ['Digest', 'Tags', 'Analyzed At', 'Archived At', 'Status', 'Archive Size Bytes']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record['imageDigest']), str(','.join([x['pullstring'] for x in record.get('image_detail', [])])), str(record['analyzed_at']), str(record['created_at']), str(record['status']), str(record['archive_size_bytes'])]
t.add_row(row)
ret = t.get_string(sortby='Archived At', reversesort=True)+"\n"
elif op in ['archived_analysis']:
header = ['Digest', 'Tags', 'Analyzed At', 'Archived At', 'Status', 'Archive Size Bytes']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record['imageDigest']), str(','.join([x['pullstring'] for x in record.get('image_detail', [])])), str(record['analyzed_at']), str(record['created_at']), str(record['status']), str(record['archive_size_bytes'])]
t.add_row(row)
ret = t.get_string(sortby='Archived At', reversesort=True) + "\n"
elif op in ['archive_analysis']:
header = ['Image Digest', 'Archive Status', 'Details']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record['digest']), str(record['status']), str(record['detail'])]
t.add_row(row)
ret = t.get_string(sortby='Archive Status')+"\n"
elif op in ['transition_rules']:
header = ['Rule Id', 'Global', 'Transition', 'Analysis Age (Days)', 'Tag Versions Newer', 'Registry', 'Repository', 'Tag', 'Last Updated']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
if type(payload) != list:
payload = [payload]
for record in payload:
row = [str(record['rule_id']),
str(record['system_global']),
str(record['transition']),
str(record['analysis_age_days']),
str(record['tag_versions_newer']),
str(record['selector']['registry']),
str(record['selector']['repository']),
str(record['selector']['tag']),
str(record['last_updated'])]
t.add_row(row)
ret = t.get_string(sortby='Last Updated', reversesort=True) + "\n"
elif op in ['transition_rule_history']:
header = ['Rule Id', 'Image Digest', 'Transition', 'Transition Date']
t = PrettyTable(header)
t.set_style(PLAIN_COLUMNS)
t.align = 'l'
for record in payload:
row = [str(record['rule_id']),
str(record['imageDigest']),
str(record['transition']),
str(record['created_at'])
]
t.add_row(row)
ret = t.get_string(sortby='Transition Date', reversesort=True) + "\n"
else:
raise Exception("no output handler for this operation ({})".format(op))
except Exception as err:
print("WARNING: failed to format output (returning raw output) - exception: " + str(err))
try:
ret = json.dumps(payload, indent=4, sort_keys=True)
except:
ret = str(payload)
return(ret)
def string_splitter(input_str, max_length=40):
"""
Returns a string that is the input string but with \n inserted every max_length chars
:param input_str:
:param max_length: int num of chars between \n
:return: string
"""
chunks = []
chunk = ''
pieces = input_str.split(' ')
for piece in pieces:
if len(chunk) + len(piece) < max_length:
chunk = ' '.join([chunk, piece])
else:
chunks.append(chunk)
chunk = piece
chunks.append(chunk)
return '\n'.join(chunks).strip()
def _format_gates(payload, all=False):
try:
if not all:
header = ['Gate', 'Description']
else:
header = ['Gate', 'Description', 'State', 'Superceded By']
t = PrettyTable(header, hrules=ALL)
t.align = 'l'
if payload:
for gate in payload:
desc = string_splitter(gate.get('description', ''), 60)
if all:
t.add_row([gate['name'].lower(), desc, gate.get('state', ''), gate.get('superceded_by', '')])
elif gate.get('state') in [None, 'active']:
t.add_row([gate['name'].lower(), desc])