-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathise.py
1458 lines (1266 loc) · 53.1 KB
/
ise.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
"""Class to configure Cisco ISE via the ERS API."""
import json
import os
import re
from furl import furl
from datetime import datetime, timedelta
import requests
from urllib3.exceptions import HeaderParsingError
import time
base_dir = os.path.dirname(__file__)
class InvalidMacAddress(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ERS(object):
def __init__(self, ise_node, ers_user, ers_pass, verify=False, disable_warnings=False, use_csrf=False, timeout=2,
protocol='https'):
"""
Class to interact with Cisco ISE via the ERS API.
:param ise_node: IP Address of the primary admin ISE node
:param ers_user: ERS username
:param ers_pass: ERS password
:param verify: Verify SSL cert
:param disable_warnings: Disable requests warnings
:param timeout: Query timeout
"""
self.ise_node = ise_node
self.user_name = ers_user
self.user_pass = ers_pass
self.protocol = protocol
self.url_base = '{0}://{1}:9060/ers'.format(self.protocol, self.ise_node)
self.ise = requests.sessions.Session()
self.ise.auth = (self.user_name, self.user_pass)
# http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification
self.ise.verify = verify
self.disable_warnings = disable_warnings
self.use_csrf = use_csrf
self.csrf = None
self.csrf_expires = None
self.timeout = timeout
self.ise.headers.update({'Connection': 'keep_alive'})
if self.disable_warnings:
requests.packages.urllib3.disable_warnings()
@staticmethod
def _mac_test(mac):
"""
Test for valid mac address.
:param mac: MAC address in the form of AA:BB:CC:00:11:22
:return: True/False
"""
if mac and re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]){2}', mac.upper()) is not None:
return True
else:
return False
@staticmethod
def _sgt_name_test(name):
"""
Test for valid name.
:param name: Name; must not be null, must be <= 32 char, alphanumeric + _ only.
:return: True/False
"""
if name and re.search(r'^[a-zA-Z0-9_]*$', name) is not None and len(name) <= 32:
return True
else:
return False
@staticmethod
def _sgacl_name_test(name):
"""
Test for valid name.
:param name: Name; must start with letter; alphanumeric + _ only.
:return: True/False
"""
if name and re.search(r'^[a-zA-Z][a-zA-Z0-9_]*$', name) is not None:
return True
else:
return False
@staticmethod
def _oid_test(id):
"""
Test for a valid OID
:param id: OID in the form of abcd1234-ef56-7890-abcd1234ef56
:return: True/False
"""
try:
if id and re.match(r'^([a-f0-9]{8}-([a-f0-9]{4}-){3}[a-z0-9]{12})$', id):
return True
else:
return False
except Exception:
return False
@staticmethod
def _pass_ersresponse(result, resp):
try:
rj = resp.json()
if "SearchResult" in rj:
result['response'] = None
else:
result['response'] = rj['ERSResponse']['messages'][0]['title']
result['error'] = resp.status_code
return result
except ValueError:
if '<title>HTTP Status 401 – Unauthorized</title>' in resp.text:
result['response'] = 'Unauthorized'
result['error'] = resp.status_code
return result
else:
result['error'] = resp.status_code
return result
def _request(self, url, method="get", data=None):
if self.use_csrf:
if not self.csrf_expires or not self.csrf or datetime.utcfromtimestamp(0) > self.csrf_expires:
self.ise.headers.update({'ACCEPT': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-TOKEN': 'fetch'})
resp = self.ise.get('{0}/config/deploymentinfo/versioninfo'.format(self.url_base))
self.csrf = resp.headers["X-CSRF-Token"]
self.csrf_expires = datetime.utcfromtimestamp(0) + timedelta(seconds=60)
self.ise.headers.update({'ACCEPT': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-TOKEN': self.csrf})
try:
req = self.ise.request(method, url, data=data, timeout=self.timeout)
except HeaderParsingError:
print("Received HeaderParsingError; Trying again...")
time.sleep(5)
req = self.ise.request(method, url, data=data, timeout=self.timeout)
else:
try:
req = self.ise.request(method, url, data=data, timeout=self.timeout)
except HeaderParsingError:
print("Received HeaderParsingError; Trying again...")
time.sleep(5)
req = self.ise.request(method, url, data=data, timeout=self.timeout)
return req
def _get_groups(self, url, filter: str = None, size: int = 20, page: int = 1):
"""
Get generic group lists.
:param url: Base URL for requesting lists
:param size: size of the page to return. Default: 20
:param page: page to return. Default: 1
:return: result dictionary
"""
result = {
'success': False,
'response': '',
'error': '',
}
# https://github.com/gruns/furl
f = furl(url)
# TODO test for valid size 1<=x>=100
f.args['size'] = size
# TODO test for valid page number?
f.args['page'] = page
# TODO add filter valication
if filter:
f.args['filter'] = filter
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
resp = self.ise.get(f.url)
if resp.status_code == 200:
result['success'] = True
result['response'] = [(i['name'], i['id'], i['description'])
for i in resp.json()['SearchResult']['resources']]
result['total'] = resp.json()['SearchResult']['total']
return result
else:
return ERS._pass_ersresponse(result, resp)
def _get_objects(self, url, filter: str = None, size: int = 20, page: int = 1):
"""
Generic method for requesting objects lists.
:param url: Base URL for requesting lists
:param filter: argument side of a ERS filter string. Default: None
:param size: size of the page to return. Default: 20
:param page: page to return. Default: 1
:return: result dictionary
"""
result = {
'success': False,
'response': [],
'error': '',
}
self.ise.headers.update(
{'Accept': 'application/json', 'Content-Type': 'application/json'})
f = furl(url)
# TODO test for valid size 1<=x>=100
f.args['size'] = size
# TODO test for valid page number?
f.args['page'] = page
# TODO add filter valication
if filter:
f.args['filter'] = filter
pageurl = f.url
while True:
resp = self.ise.get(pageurl)
if resp.status_code == 200:
json_res = resp.json()['SearchResult']
if int(json_res['total']) >= 1:
result['success'] = True
if json_res.get('nextPage'):
result['nextPage'] = json_res['nextPage']['href'].split('=')[-1]
result['nextHref'] = json_res['nextPage']['href'].split('=')
if json_res.get('previousPage'):
result['previousPage'] = json_res['previousPage']['href'].split('=')[-1]
result['previousHref'] = json_res['previousPage']['href'].split('=')
result['total'] = json_res['total']
for i in json_res['resources']:
result['response'].append((i['name'], i['id']))
pageurl = json_res.get('nextPage', {}).get('href')
if not pageurl:
break
elif int(json_res['total']) == 0:
result['success'] = True
result['response'] = []
result['total'] = json_res['total']
return result
else:
return ERS._pass_ersresponse(result, resp)
return result
def get_endpoint_groups(self, size=20, page=1):
"""
Get all endpoint identity groups.
:param size: Size of the number of identity groups before pagination starts
:return: result dictionary
"""
return self._get_groups('{0}/config/endpointgroup'.format(self.url_base), size=size, page=page)
def get_endpoint_group(self, group):
"""
Get endpoint identity group details.
:param group: Name of the identity group
:return: result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
# If it's a valid OID, perform a more direct GET-call
if self._oid_test(group):
result = self.get_object(
'{0}/config/endpointgroup'.format(self.url_base),
group,
'EndPointGroup'
)
return result
# If not valid OID, perform regular search
else:
resp = self.ise.get(
'{0}/config/endpointgroup?filter=name.EQ.{1}'.format(self.url_base, group))
found_group = resp.json()
if found_group['SearchResult']['total'] == 1:
result = self.get_object('{0}/config/endpointgroup'.format(self.url_base), found_group['SearchResult']['resources'][0]['id'], "EndPointGroup") # noqa E501
return result
else:
return ERS._pass_ersresponse(result, resp)
def get_endpoints(self, groupID=None, size=20, page=1):
"""
Get all endpoints.
:param groupID: List only endpoints in a specific GroupID. Default: None
:return: result dictionary
"""
if groupID:
filter = f"groupId.EQ.{groupID}"
else:
filter = None
return self._get_objects('{0}/config/endpoint'.format(self.url_base), filter=filter, size=size, page=page)
def get_sgts(self, sgtNum=None, detail=False, size=20, page=1):
"""
Get all Secure Group Tags.
:param sgtNum: retrieve sgt configuration for given SGT Number
:param detail: recursively retrieve all data for all SGTs in list (rather than just summary data)
:return: result dictionary
"""
if sgtNum:
filter = f"value.EQ.{sgtNum}"
else:
filter = None
if detail:
out_objs = []
objs = self._get_objects('{0}/config/sgt'.format(self.url_base), filter=filter, size=size, page=page)
for o in objs["response"]:
if len(o) > 1:
sgt = self.get_object('{0}/config/sgt'.format(self.url_base), o[1], 'Sgt')
out_objs.append(sgt["response"])
return {"success": objs["success"], "response": out_objs, "error": objs["error"]}
else:
return self._get_objects('{0}/config/sgt'.format(self.url_base), filter=filter, size=size, page=page)
def get_sgt(self, sgt):
"""
Get Secure Group Tag details.
:param sgt: name or Object ID of the Secure Group Tag
:return: result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
# If it's a valid OID, perform a more direct GET-call
if self._oid_test(sgt):
result = self.get_object(
'{0}/config/sgt'.format(self.url_base),
sgt,
'Sgt'
)
return result
# If not valid OID, perform regular search
else:
if isinstance(sgt, int):
resp = self.ise.get(
'{0}/config/sgt?filter=value.EQ.{1}'.format(self.url_base, sgt))
else:
resp = self.ise.get(
'{0}/config/sgt?filter=name.EQ.{1}'.format(self.url_base, sgt))
found_group = resp.json()
if found_group['SearchResult']['total'] == 1:
result = self.get_object('{0}/config/sgt'.format(self.url_base),
found_group['SearchResult']['resources'][0]['id'], "Sgt")
return result
else:
return ERS._pass_ersresponse(result, resp)
def add_sgt(self,
name,
description,
value,
propogate_to_apic=False,
return_object=False):
"""
Add a SGT to TrustSec Components
:param name: Name
:param description: Description
:param value: SGT Number
:param propogate_to_apic: Specific to ACI
:param return_object: Look up object after creation and return in response
"""
is_valid = ERS._sgt_name_test(name)
if not is_valid:
result = {
'success': False,
'response': '',
'error': '{0}. Invalid Security Group name, name may not be null and longer than 32 characters and '
'only contain the alphanumeric or underscore characters.'.format(name)
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
data = {"Sgt": {'name': name, 'description': description, 'value': value,
'propogateToApic': propogate_to_apic}}
resp = self._request('{0}/config/sgt'.format(self.url_base), method='post', data=json.dumps(data))
if resp.status_code == 201:
result['success'] = True
if return_object:
result['response'] = self.get_sgt(name)["response"]
else:
result['response'] = '{0} Added Successfully'.format(name)
return result
else:
return ERS._pass_ersresponse(result, resp)
def update_sgt(self,
sgt,
name,
description,
value,
propogate_to_apic=False,
return_object=False):
"""
Update SGT in TrustSec Components
:param sgt: Object ID of sgt
:param name: Name
:param description: Description
:param value: SGT Number
:param propogate_to_apic: Specific to ACI
:param return_object: Look up object after update and return in response
"""
is_valid = ERS._sgt_name_test(name)
if not is_valid:
result = {
'success': False,
'response': '',
'error': '{0}. Invalid Security Group name, name may not be null and longer than 32 characters and '
'only contain the alphanumeric or underscore characters.'.format(name)
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
data = {"Sgt": {'name': name, 'description': description, 'value': value,
'propogateToApic': propogate_to_apic}}
resp = self._request(('{0}/config/sgt/' + sgt).format(self.url_base), method='put', data=json.dumps(data))
if resp.status_code == 200:
result['success'] = True
if return_object:
result['response'] = self.get_sgt(sgt)["response"]
else:
result['response'] = resp.json()
return result
else:
return ERS._pass_ersresponse(result, resp)
def delete_sgt(self, sgt):
"""
Delete SGT in TrustSec Components
:param sgt: Object ID of sgt
:return: Result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
resp = self._request('{0}/config/sgt/{1}'.format(self.url_base, sgt), method='delete')
if resp.status_code == 204:
result['success'] = True
result['response'] = '{0} Deleted Successfully'.format(sgt)
return result
elif resp.status_code == 404:
result['response'] = '{0} not found'.format(sgt)
result['error'] = resp.status_code
return result
else:
return ERS._pass_ersresponse(result, resp)
def get_sgacls(self, detail=False, size=20, page=1):
"""
Get all Secure Group ACLs.
:param detail: recursively retrieve all data for all SGACLs in list (rather than just summary data)
:return: result dictionary
"""
filter = None
if detail:
out_objs = []
objs = self._get_objects('{0}/config/sgacl'.format(self.url_base), filter=filter, size=size, page=page)
for o in objs["response"]:
if len(o) > 1:
sgacl = self.get_object('{0}/config/sgacl'.format(self.url_base), o[1], 'Sgacl')
out_objs.append(sgacl["response"])
return {"success": objs["success"], "response": out_objs, "error": objs["error"]}
else:
return self._get_objects('{0}/config/sgacl'.format(self.url_base), filter=filter, size=size, page=page)
def get_sgacl(self, sgacl):
"""
Get Secure Group ACL details.
:param sgacl: name or Object ID of the Secure Group ACL
:return: result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
# If it's a valid OID, perform a more direct GET-call
if self._oid_test(sgacl):
result = self.get_object(
'{0}/config/sgacl'.format(self.url_base),
sgacl,
'Sgacl'
)
return result
# If not valid OID, perform regular search
else:
resp = self.ise.get(
'{0}/config/sgacl?filter=name.EQ.{1}'.format(self.url_base, sgacl))
found_group = resp.json()
if found_group['SearchResult']['total'] == 1:
result = self.get_object('{0}/config/sgacl'.format(self.url_base),
found_group['SearchResult']['resources'][0]['id'], "Sgacl")
return result
else:
return ERS._pass_ersresponse(result, resp)
def add_sgacl(self,
name,
description,
ip_version,
acl_content,
return_object=False):
"""
Add a SG ACL to TrustSec Components
:param name: Name
:param description: Description
:param ip_version: IPV4, IPV6, or IP_AGNOSTIC
:param acl_content: List of ACLs
:param return_object: Look up object after creation and return in response
"""
is_valid = ERS._sgacl_name_test(name)
if not is_valid:
result = {
'success': False,
'response': '',
'error': '{0}. Invalid SGACL name, name should start with a letter and can only contain the '
'alphanumeric or underscore characters.'.format(name)
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
data = {"Sgacl": {'name': name, 'description': description, 'ipVersion': ip_version,
'aclcontent': "\n".join(acl_content)}}
resp = self._request('{0}/config/sgacl'.format(self.url_base), method='post', data=json.dumps(data))
if resp.status_code == 201:
result['success'] = True
if return_object:
result['response'] = self.get_sgacl(name)["response"]
else:
result['response'] = '{0} Added Successfully'.format(name)
return result
else:
return ERS._pass_ersresponse(result, resp)
def update_sgacl(self,
sgacl,
name,
description,
ip_version,
acl_content,
return_object=False):
"""
Update a SG ACL from TrustSec Components
:param sgacl: Object ID of sgacl
:param name: Name
:param description: Description
:param ip_version: IPV4, IPV6, or IP_AGNOSTIC
:param acl_content: List of ACLs
:param return_object: Look up object after creation and return in response
"""
is_valid = ERS._sgacl_name_test(name)
if not is_valid:
result = {
'success': False,
'response': '',
'error': '{0}. Invalid SGACL name, name should start with a letter and can only contain the '
'alphanumeric or underscore characters.'.format(name)
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
data = {"Sgacl": {'name': name, 'description': description, 'ipVersion': ip_version,
'aclcontent': "\n".join(acl_content)}}
resp = self._request(('{0}/config/sgacl/' + sgacl).format(self.url_base), method='put',
data=json.dumps(data))
if resp.status_code == 200:
result['success'] = True
if return_object:
result['response'] = self.get_sgacl(sgacl)["response"]
else:
result['response'] = resp.json()
return result
else:
return ERS._pass_ersresponse(result, resp)
def delete_sgacl(self, sgacl):
"""
Delete SGACL in TrustSec Components
:param sgacl: Object ID of sgacl
:return: Result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
resp = self._request('{0}/config/sgacl/{1}'.format(self.url_base, sgacl), method='delete')
if resp.status_code == 204:
result['success'] = True
result['response'] = '{0} Deleted Successfully'.format(sgacl)
return result
elif resp.status_code == 404:
result['response'] = '{0} not found'.format(sgacl)
result['error'] = resp.status_code
return result
else:
return ERS._pass_ersresponse(result, resp)
def get_egressmatrixcells(self, detail=False, size=20, page=1, filter=None):
"""
Get all TrustSec Egress Matrix Cells.
:param detail: recursively retrieve all data for all egress cells in list (rather than just summary data)
:return: result dictionary
"""
if detail:
out_objs = []
objs = self._get_objects('{0}/config/egressmatrixcell'.format(self.url_base), filter=filter, size=size,
page=page)
for o in objs["response"]:
if len(o) > 1:
emc = self.get_object('{0}/config/egressmatrixcell'.format(self.url_base), o[1], 'EgressMatrixCell')
out_objs.append(emc["response"])
return {"success": objs["success"], "response": out_objs, "error": objs["error"]}
else:
return self._get_objects('{0}/config/egressmatrixcell'.format(self.url_base), filter=filter, size=size,
page=page)
def get_egressmatrixcell(self, emc, src_sgt=None, dst_sgt=None):
"""
Get TrustSec Egress Matrix Cell Policy details.
:param emc: name or Object ID of the TrustSec Egress Matrix Cell Policy
:param src_sgt: name or Object ID of the Source SGT in the Policy
:param src_sgt: name or Object ID of the Dest SGT in the Policy
:return: result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
# If it's a valid OID, perform a more direct GET-call
if self._oid_test(emc):
result = self.get_object(
'{0}/config/egressmatrixcell'.format(self.url_base),
emc,
'EgressMatrixCell'
)
return result
# If not valid OID, perform regular search
else:
if emc:
resp = self.ise.get(
'{0}/config/egressmatrixcell?filter=description.EQ.{1}'.format(
self.url_base, emc))
found_group = resp.json()
elif src_sgt and dst_sgt:
srcsgtval = self.get_sgt(src_sgt)["response"]["value"]
dstsgtval = self.get_sgt(dst_sgt)["response"]["value"]
resp = self.ise.get(
'{0}/config/egressmatrixcell?filter=sgtSrcValue.EQ.{1}&filter=sgtDstValue.EQ.{2}'.format(
self.url_base, srcsgtval, dstsgtval))
found_group = resp.json()
else:
return result
if found_group['SearchResult']['total'] == 1:
result = self.get_object('{0}/config/egressmatrixcell'.format(self.url_base),
found_group['SearchResult']['resources'][0]['id'], "EgressMatrixCell")
return result
else:
return ERS._pass_ersresponse(result, resp)
def add_egressmatrixcell(self,
source_sgt,
destination_sgt,
default_rule,
acls=None,
description=None,
return_object=False):
"""
Add TrustSec Egress Matrix Cell Policy.
:param description: Description
:param source_sgt: Source SGT name or Object ID
:param destination_sgt: Destination SGT name or Object ID
:param default_rule: "NONE", "PERMIT_IP", "DENY_IP"
:param acls: list of SGACL Object IDs. Can be None.
:param return_object: Look up object after creation and return in response
"""
# ISE will actually allow you to post duplicate polices, so before we execute the post, double check to
# make sure a policy doesn't already exist
src_sgt_r = self.get_sgt(source_sgt)["response"]
dst_sgt_r = self.get_sgt(destination_sgt)["response"]
if src_sgt_r and dst_sgt_r:
src_sgt = src_sgt_r.get("id", None)
dst_sgt = dst_sgt_r.get("id", None)
celldata = self.get_egressmatrixcell(None, src_sgt=src_sgt, dst_sgt=dst_sgt)["response"]
else:
celldata = src_sgt = dst_sgt = None
if celldata:
result = {
'success': False,
'response': '',
'error': 'There is already a policy present for this source and destination. Please use update to make '
'policy changes.'
}
return result
elif default_rule == "NONE" and acls is None:
result = {
'success': False,
'response': '',
'error': 'You must specify one or more acls as a list, or a default_rule; both cannot be blank'
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
newacls = []
if acls:
for a in acls:
if self._oid_test(a):
newacls.append(a)
else:
newacl = self.get_sgacl(a)["response"].get("id", None)
if newacl:
newacls.append(newacl)
data = {"EgressMatrixCell": {'description': description,
'sourceSgtId': src_sgt,
'destinationSgtId': dst_sgt,
'defaultRule': default_rule, "matrixCellStatus": "ENABLED",
'sgacls': newacls}}
resp = self._request('{0}/config/egressmatrixcell'.format(self.url_base), method='post',
data=json.dumps(data))
if resp.status_code == 201:
result['success'] = True
if return_object:
result['response'] = self.get_egressmatrixcell(None, src_sgt=src_sgt, dst_sgt=dst_sgt)["response"]
else:
result['response'] = '{0} Added Successfully'.format(description)
return result
else:
return ERS._pass_ersresponse(result, resp)
def update_egressmatrixcell(self,
emc,
source_sgt,
destination_sgt,
default_rule,
acls=None,
description=None,
return_object=False):
"""
Update TrustSec Egress Matrix Cell Policy.
:param emc: Object ID of egress matrix cell
:param description: Description
:param source_sgt: Source SGT name or Object ID
:param destination_sgt: Destination SGT name or Object ID
:param default_rule: "NONE", "PERMIT_IP", "DENY_IP"
:param acls: list of SGACL Object IDs. Can be None.
:param return_object: Look up object after creation and return in response
"""
if not emc:
result = {
'success': False,
'response': '',
'error': 'You must provide the egress matrix cell object id in order to update it.'
}
return result
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
newacls = []
if acls:
for a in acls:
if self._oid_test(a):
newacls.append(a)
else:
newacl = self.get_sgacl(a)["response"].get("id", None)
if newacl:
newacls.append(newacl)
src_sgt = self.get_sgt(source_sgt)["response"]
dst_sgt = self.get_sgt(destination_sgt)["response"]
if src_sgt and dst_sgt:
data = {"EgressMatrixCell": {'id': emc, 'description': description,
'sourceSgtId': src_sgt["id"],
'destinationSgtId': dst_sgt["id"],
'defaultRule': default_rule, "matrixCellStatus": "ENABLED",
'sgacls': newacls}}
resp = self._request(('{0}/config/egressmatrixcell/' + emc).format(self.url_base), method='put',
data=json.dumps(data))
if resp.status_code == 200:
result['success'] = True
if return_object:
result['response'] = self.get_egressmatrixcell(emc)["response"]
else:
result['response'] = resp.json()
return result
else:
return ERS._pass_ersresponse(result, resp)
else:
return {
'success': False,
'response': None,
'error': '',
}
def delete_egressmatrixcell(self, emc):
"""
Delete TrustSec Egress Matrix Cell Policy.
:param emc: Object ID of egress matrix cell policy
:return: Result dictionary
"""
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
resp = self._request('{0}/config/egressmatrixcell/{1}'.format(self.url_base, emc), method='delete')
if resp.status_code == 204:
result['success'] = True
result['response'] = '{0} Deleted Successfully'.format(emc)
return result
elif resp.status_code == 404:
result['response'] = '{0} not found'.format(emc)
result['error'] = resp.status_code
return result
else:
return ERS._pass_ersresponse(result, resp)
def get_object(self, url: str, objectid: str, objecttype: str):
"""
Get generic object lists.
:param url: Base URL for requesting lists
:param objectid: ID retreved from previous search.
:param objecttype: "ERSEndPoint", etc...
:return: result dictionary
"""
result = {
'success': False,
'response': '',
'error': '',
}
self.ise.headers.update(
{'Accept': 'application/json', 'Content-Type': 'application/json'})
f = furl(url)
f.path /= objectid
resp = self.ise.get(f.url)
if resp.status_code == 200:
result['success'] = True
result['response'] = resp.json()[objecttype]
return result
else:
return ERS._pass_ersresponse(result, resp)
def get_endpoint(self, mac_address):
"""
Get endpoint details.
:param mac_address: MAC address of the endpoint
:return: result dictionary
"""
is_valid = ERS._mac_test(mac_address)
if not is_valid:
raise InvalidMacAddress(
'{0}. Must be in the form of AA:BB:CC:00:11:22'.format(mac_address))
else:
self.ise.headers.update(
{'ACCEPT': 'application/json', 'Content-Type': 'application/json'})
result = {
'success': False,
'response': '',
'error': '',
}
resp = self.ise.get(
'{0}/config/endpoint?filter=mac.EQ.{1}'.format(self.url_base, mac_address))
found_endpoint = resp.json()