Last active
September 23, 2017 03:45
-
-
Save spdkils/c7f8c45f944aa6e968e17ca1819bd2a3 to your computer and use it in GitHub Desktop.
Dissect Cisco ACEs for flipping for whatever...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# flip ace | |
import re | |
def ace_elements(ace): | |
ace = ace.strip() | |
'''Dissect ACE statement into it's parts. | |
returns and array of each part as follows | |
[action protocol src_address src_ports dst_address dst_ports established] | |
Any empty element returns None. For example: | |
[permit, tcp, host 10.10.10.1, None, Host 20.20.20.1, None, None] ''' | |
statement = re.match('(?:permit|deny)', ace) | |
if not statement: | |
return ace | |
'''statement protocol src_address src_ports dst_address dst_ports established | |
The search array follows that order, and I create a search for each element. | |
''' | |
ACESearchs = [r'\b(?:permit|deny)\b', | |
r'\b(?:ip|tcp|udp|[0-9]+)\b', | |
r'\b(?:any|host (?:\d+\.){3}\d+|(?:(?:\d+\.){3}\d+ (?:\d+\.){3}\d+))\b', | |
r'\b(?:range \d+ \d+\b|eq(?: \d+\b)+(?= \d+\.| host| any)|(?:lt|gt) \d+\b)', | |
r'\b(?:any|host (?:\d+\.){3}\d+|(?:(?:\d+\.){3}\d+ (?:\d+\.){3}\d+))\b', | |
r'\b(?:range \d+ \d+\b|eq(?: \d+\b)+|(?:lt|gt) \d+\b)', | |
r'(?:\bestablished$)'] | |
res = [] | |
loc = 0 | |
for search in ACESearchs: | |
append = re.match(search, ace[loc:]) | |
if append: | |
loc += append.end() + 1 | |
res.append(append.group()) | |
else: | |
res.append(append) | |
return res | |
def valACE(ace): | |
if ace.__class__ is not list or len(ace) != 7: | |
raise ValueError | |
if ace[1] != 'tcp' and ace[6]: | |
return False, 'established without tcp' | |
if ace[3] and ace[5]: | |
return False, 'ports both sides' | |
if ace[3] and ace[1] == 'tcp' and not ace[6]: | |
return False, 'missing established' | |
if ace[5] and ace[6]: | |
return False, 'established wrong side' | |
if ace[1] == 'ip' and (ace[5] or ace[3]): | |
return False, 'ports with ip' | |
return True, '' | |
def flipACE(ace): | |
if ace.__class__ is not list or len(ace) != 7: | |
raise ValueError | |
if ace[6]: | |
return [ace[0], ace[1], ace[4], ace[5], ace[2], ace[3], None] | |
elif ace[1] == 'tcp' and not ace[6] and not ace[3] and ace[5]: | |
return [ace[0], ace[1], ace[4], ace[5], ace[2], ace[3], 'established'] | |
else: | |
return [ace[0], ace[1], ace[4], ace[5], ace[2], ace[3], None] | |
data = ace_elements('permit ip host 10.10.10.1 eq 80 10.0.0.0 0.255.255.255') | |
print(data) | |
print(flipACE(data)) | |
print(valACE(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment