-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCxPy.py
More file actions
1500 lines (1256 loc) · 60.6 KB
/
CxPy.py
File metadata and controls
1500 lines (1256 loc) · 60.6 KB
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
# coding=utf-8
# Python Dependencies
import base64
import re
import json
import time
import logging
import os
from suds.client import Client
from suds.sudsobject import asdict
from suds.cache import NoCache
dir_path = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(filename=dir_path + '/checkmarx_soap_api.log',
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
class CxPy(object):
# Internal Variables for the Class
DEBUG = False
configPath = dir_path + "/etc/"
errorLog = []
ttlReport = 6
timeWaitReport = 3
#
# Init Function
#
def __init__(self):
# Get Configuration
self.user_name, self.password, self.url, self.api_type = self.get_config()
# Open Connection With Checkmarx
self.init_client = self.open_connection()
# Get the Service URL
self.service_url = self.get_service_url(self.init_client)
# Get the Session Id and Client Object
self.session_id, self.client = self.get_session_id(self.init_client, self.service_url)
pass
##########################################
#
# Functions Related to Opening session with Checkmarx
#
##########################################
#
# Get Configuration
#
def get_config(self):
try:
with open(self.configPath + "config.json", "r") as outfile:
tmp_json = json.load(outfile)["checkmarx"]
username = str(tmp_json["username"])
password = str(tmp_json["password"])
url = str(tmp_json["url"])
api_type = tmp_json["APIType"]
return username, password, url, api_type
except Exception as e:
logger.error("Unable to get configuration: {} ".format(e.message))
raise Exception("Unable to get configuration: {} ".format(e.message))
#
# Open Connection
#
def open_connection(self):
try:
tmp_client = Client(self.url)
if self.DEBUG:
print(dir(tmp_client))
return tmp_client
except Exception as e:
logger.error("Unable to establish connection "
"with WSDL [{}]: {} ".format(self.url, e.message))
raise Exception("Unable to establish connection "
"with WSDL [{}]: {} ".format(self.url, e.message))
#
# Get Service URL
#
def get_service_url(self, client):
"""
https://checkmarx.atlassian.net/wiki/display/KC/Getting+the+SDK+Web+Service+URL
Create an instance of the Resolver generated proxy client,
and set its URL to: http://<server>/Cxwebinterface/CxWsResolver.asmx
where <server> is the IP address or resolvable name of the CxSAST server
(in a distributed architecture: the CxManager server).
Call the Resolver's single available method (GetWebServiceUrl) as below.
The returned CxWSResponseDiscovery object's .ServiceURL field will
contain the SDK web service URL.
The service url example: http://192.168.31.121/cxwebinterface/SDK/CxSDKWebService.asmx
:param client:
:return: Checkmarx web service url
"""
try:
cx_client = client.factory.create('CxClientType')
response = client.service.GetWebServiceUrl(cx_client.SDK, self.api_type)
if response.IsSuccesfull:
service_url = response.ServiceURL
else:
logger.error("Error establishing connection:"
"{}".format(response.ErrorMessage))
raise Exception("Error establishing connection:"
" {}".format(response.ErrorMessage))
if self.DEBUG:
print("Response Discovery Object:", dir(response))
print("Service Url:", service_url)
service_url = service_url or None
return service_url
except Exception as e:
logger.error("GetWebServiceUrl, "
"Unable to get Service URL: {} ".format(e.message))
raise Exception("GetWebServiceUrl, "
"Unable to get Service URL: {} ".format(e.message))
#
# Login in Checkmarx and retrieve the Session ID
#
def get_session_id(self, client, service_url, lcid=2052):
"""
https://checkmarx.atlassian.net/wiki/display/KC/Initiating+a+Session
The login web service parameters are as follows:
public CxWSResponseLoginData Login(
Credentials applicationCredentials,
int lcid
);
applicationCredentials: A Credentials object, with fields:
User: The username for login
Pass: The password for login
lcid: ID# of the language for web service responses.
The current API version supports the following values:
1033: English
1028: Chinese Taiwan
1041: Japanese
2052: Chinese
Log in Checkmarx and retrieve the session id.
The Checkmarx server session timeout is 24 hours.
:param client:
:param service_url:
:param lcid:
:return:
"""
try:
client_sdk = Client(service_url + "?wsdl", cache=NoCache(), prettyxml=True)
cx_login = client_sdk.factory.create("Credentials")
cx_login.User = self.user_name
cx_login.Pass = self.password
cx_sdk = client_sdk.service.Login(cx_login, lcid)
if not cx_sdk.IsSuccesfull:
logger.error("Unable to Login > "
"{}".format(cx_sdk.ErrorMessage))
raise Exception("Unable to Login > "
"{}".format(cx_sdk.ErrorMessage))
if self.DEBUG:
print("Service Object:", dir(client))
print("Login Object:", dir(cx_sdk))
print("Session ID:", cx_sdk.SessionId)
return cx_sdk.SessionId, client_sdk
except Exception as e:
logger.error("Unable to get SessionId from "
"[{}] : {} ".format(service_url, e.message))
raise Exception("Unable to get SessionId from "
"[{}] : {} ".format(service_url, e.message))
##########################################
#
# Functions Related to the functionality of the WSDL
#
##########################################
#
# Get data from the Projects
#
def get_project_scanned_display_data(self, filter_on=False):
"""
The API client can get a list of all public projects in the system with
a risk level and summary of results by severity (high, medium, low).
:param filter_on:
:return: CxWSResponseProjectScannedDisplayData
"""
try:
tmp = self.client.service.GetProjectScannedDisplayData(self.session_id)
if not tmp.IsSuccesfull:
logger.error("GetProjectScannedDisplayData, "
"Unable to get data from the server.")
raise Exception("GetProjectScannedDisplayData, "
"Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
if not filter_on:
return self.convert_to_json(tmp)
else:
return tmp.ProjectScannedList[0]
except Exception as e:
logger.error("Unable to GetProjectScannedDisplayData: "
"{} ".format(e.message))
raise Exception("Unable to GetProjectScannedDisplayData: "
"{} ".format(e.message))
#
# Get Project Display Data
#
def get_projects_display_data(self, filter_on=False):
"""
The API client can get a list of CxSAST projects available to the current user.
This is used primarily for display purposes.
:param filter_on:
:return: Array of projects. Each project contains data for display.
"""
try:
tmp = self.client.service.GetProjectsDisplayData(self.session_id)
if not tmp.IsSuccesfull:
logger.error("GetProjectsDisplayData, "
"Unable to get data from the server.")
raise Exception("GetProjectsDisplayData, "
"Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
if not filter_on:
return self.convert_to_json(tmp)
else:
return tmp.projectList[0]
except Exception as e:
logger.error("Unable to GetProjectsDisplayData: "
"{} ".format(e.message))
raise Exception("Unable to GetProjectsDisplayData: "
"{} ".format(e.message))
#
# Get Scan Info For All Projects
#
def get_scan_info_for_all_projects(self, filter_on=False):
"""
get scan info for all projects
:param filter_on:
:return:
"""
try:
tmp = self.client.service.GetScansDisplayDataForAllProjects(self.session_id)
if not tmp.IsSuccesfull:
logger.error("GetScansDisplayDataForAllProjects,"
" Unable to get data from the server.")
raise Exception("GetScansDisplayDataForAllProjects, "
"Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
if not filter_on:
return self.convert_to_json(tmp)
else:
return tmp
except Exception as e:
logger.error("Unable to GetScansDisplayDataForAllProjects: "
"{} ".format(e.message))
raise Exception("Unable to GetScansDisplayDataForAllProjects: "
"{} ".format(e.message))
#
# Get Preset List
#
def get_preset_list(self):
"""
get preset list from server
:return:
"""
try:
tmp = self.client.service.GetPresetList(self.session_id)
if not tmp.IsSuccesfull:
logger.error("GetPresetList, Unable to get data from the server.")
raise Exception("GetPresetList, Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
return self.convert_to_json(tmp)
except Exception as e:
logger.error("Unable to GetPresetList: {} ".format(e.message))
raise Exception("Unable to GetPresetList: {} ".format(e.message))
def get_preset_id_by_name(self, preset_name):
"""
get preset list from server, and search it in the preset list.
Checkmarx default preset list:
preset name : preset id
"Checkmarx Default": 36,
"All": 1,
"Android": 9,
"Apple Secure Coding Guide": 19,
"Default": 7,
"Default 2014": 17,
"Empty preset": 6,
"Error handling": 2,
"High and Medium": 3,
"High and Medium and Low": 13,
"HIPAA": 12,
"JSSEC": 20,
"MISRA_C": 10,
"MISRA_CPP": 11,
"Mobile": 14,
"OWASP Mobile TOP 10 - 2016": 37,
"OWASP TOP 10 - 2010": 4,
"OWASP TOP 10 - 2013": 15,
"PCI": 5,
"SANS top 25": 8,
"WordPress": 16,
"XS": 35
:param preset_name:
:return: preset id
"""
try:
preset_id = None
tmp = self.client.service.GetPresetList(self.session_id)
if not tmp.IsSuccesfull:
logger.error("In get_preset_id_by_name unable to getPresetList:"
"{}".format(tmp.ErrorMessage))
raise Exception("In get_preset_id_by_name unable to getPresetList:"
" {}".format(tmp.ErrorMessage))
preset_list = tmp.PresetList.Preset
for preset in preset_list:
if preset.PresetName == preset_name:
preset_id = preset.ID
break
if not preset_id:
logger.error(" get_preset_id_by_name >>> "
"please check your preset name again, "
"the following preset does not exist: "
"{}".format(preset_name))
raise Exception(' get_preset_id_by_name >>>'
' please check your preset name again,'
'the following preset does not exist: '
'{}'.format(preset_name))
return preset_id
except Exception as e:
logger.error("Unable to GetPresetList: {} ".format(e.message))
raise Exception("Unable to GetPresetList: {} ".format(e.message))
#
# Get Configuration List
#
def get_configuration_list(self):
"""
The API client can get the list of available encoding options
(for scan configuration).
:return: Available encoding options.
"""
try:
tmp = self.client.service.GetConfigurationSetList(self.session_id)
if not tmp.IsSuccesfull:
logger.error("get_configuration_list, Unable to get data from the server.")
raise Exception("get_configuration_list, Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
return self.convert_to_json(tmp)
except Exception as e:
logger.error("Unable to get_configuration_list: {} ".format(e.message))
raise Exception("Unable to get_configuration_list: {} ".format(e.message))
#
# Get Associated Groups List
#
def get_associated_groups(self):
"""
The API client can get information on all groups related to the current user.
:return: CxWSResponseGroupList.GroupList contains an array of group data.
"""
try:
tmp = self.client.service.GetAssociatedGroupsList(self.session_id)
if not tmp.IsSuccesfull:
logger.error("get_associated_groups, Unable to get data from the server.")
raise Exception("get_associated_groups, Unable to get data from the server.")
if self.DEBUG:
print dir(tmp)
return self.convert_to_json(tmp)
except Exception as e:
logger.error("get_associated_groups, Unable to GetAssociatedGroupsList: {} ".format(e.message))
raise Exception("get_associated_groups, Unable to GetAssociatedGroupsList: {} ".format(e.message))
#
# Filter For get_project_scanned_display_data
#
def filter_project_scanned_display_data(self, project_id):
"""
filter for get_project_scanned_display_data
:param project_id:
:return:
"""
tmp_projects = self.get_project_scanned_display_data(True)
for project in tmp_projects:
if project.ProjectID == project_id:
return self.convert_to_json(project)
logger.error("filter_project_scanned_display_data, "
"Could not find ProjectID: {} ".format(project_id))
raise Exception("filter_project_scanned_display_data ,"
"Could not find ProjectID: {} ".format(project_id))
#
# Filter for get_projects_display_data
#
def filter_projects_display_data(self, project_id):
"""
filter for get_projects_display_data
:param project_id:
:return:
"""
tmp_projects = self.get_projects_display_data(True)
for project in tmp_projects:
if project.projectID == project_id:
return self.convert_to_json(project)
logger.error("filter_projects_display_data, "
"Could not find ProjectID: {} ".format(project_id))
raise Exception("filter_projects_display_data,"
"Could not find ProjectID: {} ".format(project_id))
#
# Filter for get_scan_info_for_all_projects
#
def filter_scan_info_for_all_projects(self, project_id):
"""
filter for get_scan_info_for_all_projects
:param project_id:
:return:
"""
tmp_projects = self.get_scan_info_for_all_projects(True).ScanList[0]
for project in tmp_projects:
if project.ProjectId == project_id:
return self.convert_to_json(project)
logger.error("filter_scan_info_for_all_projects, "
"Could not find ProjectID: {} ".format(project_id))
raise Exception("filter_scan_info_for_all_projects, "
"Could not find ProjectID: {} ".format(project_id))
#
# Get Suppressed Issues
#
def get_suppressed_issues(self, scan_id):
cx_ws_report_type = self.client.factory.create("CxWSReportType")
cx_report_request = self.client.factory.create("CxWSReportRequest")
cx_report_request.ScanID = scan_id
cx_report_request.Type = cx_ws_report_type.XML
create_report_response = self.client.service.CreateScanReport(self.session_id,
cx_report_request)
if create_report_response.IsSuccesfull:
if self.DEBUG:
print create_report_response
print "Success. Creating Get Scan Report Status"
inc = 0
while inc < self.ttlReport:
inc += 1
r_status = self.client.service.GetScanReportStatus(self.session_id,
create_report_response.ID)
if r_status.IsSuccesfull and r_status.IsReady:
break
if self.DEBUG:
print "fail"
time.sleep(self.timeWaitReport)
if self.DEBUG:
print "Success. Creating Get Scan Report"
r_scan_results = self.client.service.GetScanReport(self.session_id,
create_report_response.ID)
if r_scan_results.IsSuccesfull and r_scan_results.ScanResults:
xml_data = base64.b64decode(r_scan_results.ScanResults)
issues = re.findall('FalsePositive="([a-zA-Z]+)" Severity="([a-zA-Z]+)"',
xml_data)
if self.DEBUG:
print r_scan_results
print issues
medium_suppress_issues = 0
low_suppress_issues = 0
high_suppress_issues = 0
other_suppress_issues = 0
for a, b in issues:
if a == "True":
if b == "Medium":
medium_suppress_issues += 1
elif b == "High":
high_suppress_issues += 1
elif b == "Low":
low_suppress_issues += 1
else:
other_suppress_issues += 1
if self.DEBUG:
print high_suppress_issues
print medium_suppress_issues
print low_suppress_issues
return {"highSuppressIssues": high_suppress_issues,
"mediumSuppressIssues": medium_suppress_issues,
"lowSuppressIssues": low_suppress_issues}
else:
raise Exception("Unable to Get Report")
else:
raise Exception("Unable to get Suppressed")
#
# Convert Suds object into serializable format.
#
def recursive_asdict(self, d):
out = {}
for k, v in asdict(d).iteritems():
if hasattr(v, '__keylist__'):
out[k] = self.recursive_asdict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(self.recursive_asdict(item))
else:
out[k].append(item)
else:
out[k] = v
return out
#
# Return Subs Object into Serializable format Handler
#
def convert_to_json(self, data):
try:
tmp = self.recursive_asdict(data)
# return json.dumps(tmp)
return tmp
except Exception as e:
logger.error("Unable to convert to JSON: {} ".format(e.message))
raise Exception("Unable to convert to JSON: {} ".format(e.message))
def get_project_id_by_name(self, project_name):
"""
get project id by name
:param project_name:
:type project_name: string
:return: project_id
"""
try:
tmp = self.client.service.GetProjectsDisplayData(self.session_id)
if tmp.IsSuccesfull:
project_id = None
project_data_list = tmp.projectList.ProjectDisplayData
for projectData in project_data_list:
if projectData.ProjectName == project_name:
project_id = projectData.projectID
break
if not project_id:
logger.error(' get_project_id_by_name >>> '
'please check your projectName again,'
'the following project does not exist: '
'{}'.format(project_name))
raise Exception(' get_project_id_by_name >>> '
'please check your projectName again,'
'the following project does not exist: '
'{}'.format(project_name))
logger.info(" project {} has project id {}".format(project_name, project_id))
return project_id
else:
logger.error(' Fail to GetProjectsDisplayData: '
'{} '.format(tmp.ErrorMessage))
raise Exception(' Fail to GetProjectsDisplayData: '
'{} '.format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to GetProjectsDisplayData: "
"{} ".format(e.message))
raise Exception("Unable to GetProjectsDisplayData: "
"{} ".format(e.message))
def delete_projects(self, project_names):
"""
delete projects by project names
:param project_names:
:return:
"""
project_ids_number = []
for projectName in project_names:
project_id = self.get_project_id_by_name(projectName)
if project_id:
project_ids_number.append(project_id)
logger.warning(" deleting_projects >>> project names {} : "
"project ids {} ".format(', '.join(project_names), project_ids_number))
project_ids = self.client.factory.create('ArrayOfLong')
project_ids.long = project_ids_number
try:
tmp = self.client.service.DeleteProjects(self.session_id, project_ids)
if not tmp.IsSuccesfull:
logger.error(' Fail to delete projects: '
'{} '.format(tmp.ErrorMessage))
raise Exception(' Fail to delete projects: '
'{} '.format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to DeleteProjects: "
"{} ".format(e.message))
raise Exception("Unable to DeleteProjects: "
"{} ".format(e.message))
def branch_project_by_id(self, project_name, new_branch_project_name):
"""
This API client can create a branch for an existing project.
To create a new project, first run a scan with a new project name,
and then branch the existing project as described here.
:param project_name: The name of the project that will be branched.
:type project_name: String
:param new_branch_project_name: The new project name of the branched project.
:type new_branch_project_name: String
:return: project_id
"""
try:
origin_project_id = self.get_project_id_by_name(project_name)
if origin_project_id:
tmp = self.client.service.BranchProjectById(self.session_id,
origin_project_id,
new_branch_project_name)
if tmp.IsSuccesfull:
project_id = tmp.ProjectID
logger.info('branch_project_by_id, project {} '
'has project id {}'.format(project_name, project_id))
return project_id
else:
logger.error("Error establishing connection: "
"{} ".format(tmp.ErrorMessage))
raise Exception("Error establishing connection: "
"{} ".format(tmp.ErrorMessage))
else:
logger.error("branch_project_by_id, Project does not exist.")
raise Exception("branch_project_by_id, Project does not exist.")
except Exception as e:
logger.error("Unable to BranchProjectById: "
"{} ".format(e.message))
raise Exception("Unable to BranchProjectById: "
"{} ".format(e.message))
def cancel_scan(self, scan_run_id):
"""
The API client can cancel a scan in progress.
The scan can be canceled while waiting in the queue or during a scan.
:param scan_run_id:
:type scan_run_id: string
:return:
"""
try:
logger.warning("cancel_scan, scan run id {}".format(scan_run_id))
response = self.client.service.CancelScan(self.session_id,
scan_run_id)
if not response.IsSuccesfull:
logger.error(" Fail to CancelScan: {} ".format(response.ErrorMessage))
raise Exception(" Fail to CancelScan: "
"{} ".format(response.ErrorMessage))
except Exception as e:
logger.error("Unable to CancelScan: {} ".format(e.message))
raise Exception("Unable to CancelScan: "
"{} ".format(e.message))
def create_scan_report(self, scan_id, report_type="PDF"):
"""
The API client can generate a result report for a scan, by Scan ID.
:param scan_id:
:param report_type: report_type should be member of the list: ["PDF", "RTF", "CSV", "XML"]
:return: report_id
"""
report_request = self.client.factory.create('CxWSReportRequest')
ws_report_type = self.client.factory.create('CxWSReportType')
report_request.ScanID = scan_id
if report_type == "PDF":
report_request.Type = ws_report_type.PDF
elif report_type == "RTF":
report_request.Type = ws_report_type.RTF
elif report_type == "CSV":
report_request.Type = ws_report_type.CSV
elif report_type == "XML":
report_request.Type = ws_report_type.XML
else:
logger.error(' Report type not supported, report_type should be '
'member of the list: ["PDF", "RTF", "CSV", "XML"] ')
raise Exception(' Report type not supported, report_type should be'
' member of the list: ["PDF", "RTF", "CSV", "XML"] ')
try:
tmp = self.client.service.CreateScanReport(self.session_id, report_request)
if tmp.IsSuccesfull:
report_id = tmp.ID
logger.info("begin to create report, "
"scan_id {} has report_id {}".format(scan_id, report_id))
return report_id
else:
raise Exception(' Fail to CreateScanReport %s'.format(tmp.ErrorMessage))
except Exception as e:
raise Exception("Unable to CreateScanReport: {} ".format(e.message))
def delete_scans(self, scan_ids_number):
"""
The API client can delete requested scans.
Scans that are currently running won't be deleted.
If there's even a single scan that the user can't delete (due to security reasons)
the operation will fail and an error message is returned.
:return:
"""
scan_ids_number = scan_ids_number or []
scan_ids = self.client.factory.create('ArrayOfLong')
scan_ids.long = scan_ids_number
try:
logger.warning('delete_scans, scan_ids {}'.format(scan_ids_number))
tmp = self.client.service.DeleteScans(self.session_id, scan_ids)
if not tmp.IsSuccesfull:
logger.error(' Fail to DeleteScans {} '.format(tmp.ErrorMessage))
raise Exception(' Fail to DeleteScans {} '.format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to DeleteScans: {} ".format(e.message))
raise Exception("Unable to DeleteScans: {} ".format(e.message))
def get_user_id_by_name(self, user_name):
"""
get user id by name.
:param user_name:
:return: user id
"""
user_id = None
users = self.get_all_users()
for user in users:
if user.UserName == user_name:
user_id = user.ID
break
if not user_id:
logger.error("user {} does not exist in Checkmarx server".format(user_name))
raise Exception("user {} does not exist in Checkmarx server".format(user_name))
logger.info('user {} has id {}'.format(user_name, user_id))
return user_id
def delete_user(self, user_name):
"""
delete user from Checkmarx server.
:param user_name:
:return:
"""
user_id = self.get_user_id_by_name(user_name)
try:
logger.warning("deleting user {}".format(user_name))
tmp = self.client.service.DeleteUser(self.session_id, user_id)
if not tmp.IsSuccesfull:
logger.error(' Fail to DeleteUser {} '.format(tmp.ErrorMessage))
raise Exception(' Fail to DeleteUser {} '.format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to DeleteUser: {} ".format(e.message))
raise Exception("Unable to DeleteUser: {} ".format(e.message))
def get_scan_report(self, report_id):
"""
Once a scan result report has been generated and the report is ready,
the API client can retrieve the report's content.
:param report_id:
:return:
"""
try:
tmp = self.client.service.GetScanReport(self.session_id, report_id)
if tmp.IsSuccesfull:
scan_results = tmp.ScanResults
contain_all_results = tmp.containsAllResults
logger.info("getting report {} data, containsAllResults: {}".format(report_id, contain_all_results))
return scan_results, contain_all_results
else:
logger.error(" unable to GetScanReport: {} ".format(tmp.ErrorMessage))
raise Exception(" unable to GetScanReport: {} ".format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to GetScanReport: {} ".format(e.message))
raise Exception("Unable to GetScanReport: {} ".format(e.message))
def get_status_of_single_scan(self, run_id):
"""
After running a scan, The API client can get the scan status and its details.
To do this, the API will first need the scan's Run ID.
The obtained details include the scan's Scan ID, which can be subsequently
used for commenting and reports.
:param run_id:
:return:
"""
try:
tmp = self.client.service.GetStatusOfSingleScan(self.session_id, run_id)
if tmp.IsSuccesfull:
current_status = tmp.CurrentStatus
scan_id = tmp.ScanId
return current_status, scan_id
else:
logger.error(" unable to GetStatusOfSingleScan: {} ".format(tmp.ErrorMessage))
raise Exception(" unable to GetStatusOfSingleScan: {} ".format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to GetScanReport: {} ".format(e.message))
raise Exception("Unable to GetScanReport: {} ".format(e.message))
def get_scan_report_status(self, report_id):
"""
The API client can track the status of a report generation request.
:param report_id:
:return:
"""
try:
tmp = self.client.service.GetScanReportStatus(self.session_id, report_id)
if tmp.IsSuccesfull:
is_ready = tmp.IsReady
is_failed = tmp.IsFailed
logger.info("report {} status, IsReady: {}, IsFailed: {}".format(report_id, is_ready, is_failed))
return is_ready, is_failed
else:
logger.error(" unable to GetScanReportStatus: {} ".format(tmp.ErrorMessage))
raise Exception(" unable to GetScanReportStatus: {} ".format(tmp.ErrorMessage))
except Exception as e:
raise Exception("Unable to GetScanReport: {} ".format(e.message))
def get_all_users(self):
"""
get all users from the Checkmarx server.
:return: user list
"""
try:
tmp = self.client.service.GetAllUsers(self.session_id)
if tmp.IsSuccesfull:
user_data_list = tmp.UserDataList.UserData
return user_data_list
else:
logger.error('Fail to GetAllUsers: {}'.format(tmp.ErrorMessage))
raise Exception('Fail to GetAllUsers: '
'{}'.format(tmp.ErrorMessage))
except Exception as e:
logger.error("Unable to GetAllUsers: {} ".format(e.message))
raise Exception("Unable to GetAllUsers: {} ".format(e.message))
def get_project_configuration(self, project_name):
"""
get project configuration
:param project_name:
:return:
"""
try:
project_id = self.get_project_id_by_name(project_name)
if project_id:
tmp = self.client.service.GetProjectConfiguration(self.session_id,
project_id)
if tmp.IsSuccesfull:
project_config = tmp.ProjectConfig
permission = tmp.Permission
return project_config, permission
else:
logger.error(' unable to GetProjectConfiguration : '
'{}'.format(tmp.ErrorMessage))
raise Exception(' unable to GetProjectConfiguration :'
' {}'.format(tmp.ErrorMessage))
else:
logger.error(' project not exists: {}'.format(project_name))
raise Exception(' project not exists: {}'.format(project_name))
except Exception as e:
logger.error("Unable to GetProjectConfiguration: {} ".format(e.message))
raise Exception("Unable to GetProjectConfiguration: "
"{} ".format(e.message))
def get_scan_summary(self, scan_id):
"""
get scan summary
:param scan_id:
:return:
"""
try:
tmp = self.client.service.GetScanSummary(self.session_id, scan_id)
if tmp.IsSuccesfull:
scan_summary_result = tmp
return scan_summary_result
else:
logger.error('Fail to GetScanSummaryResult:'
'{} '.format(tmp.ErrorMessage))
raise Exception('Fail to GetScanSummaryResult: '