This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
firewall_updater.py
executable file
·149 lines (124 loc) · 5.08 KB
/
firewall_updater.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
#!/usr/bin/python3
# coding: utf-8
import argparse
import socket
import requests
import json
import os.path
from os import path
POLYCUBED_ADDR = 'localhost'
POLYCUBED_PORT = 9000
REQUESTS_TIMEOUT = 5 # seconds
polycubed_endpoint = 'http:https://{}:{}/polycube/v1'
def main():
global polycubed_endpoint
args = parseArguments()
addr = args['address']
port = args['port']
cube_name = args['cube_name']
rule_file = args['rule_file']
show = args['show_rules']
chain = "EGRESS" if args['egress'] else "INGRESS"
polycubed_endpoint = polycubed_endpoint.format(addr, port)
if show:
ingress = getRules(cube_name, "INGRESS")
egress = getRules(cube_name, "EGRESS")
print(f'Ingress rules:')
for x in ingress:
print(f'\t{json.dumps(x)}')
print(f'Egress rules:')
for x in egress:
print(f'\t{json.dumps(x)}')
return
rules = None
'''
Here the rules are loaded from a JSON file, feel free to create the payload of the POST request directly here.
An example could be:
{
"rules": [
{"operation": "insert", "id": 0, "l4proto":"TCP", "src":"10.0.0.100/32", "dst":"10.0.0.150/24", "action":"drop"},
{"operation": "append", "l4proto": "ICMP", "src":"10.0.0.50/32", "dst":"10.0.0.75/24", "action":"drop"},
{"operation": "append", "l4proto": "ICMP", "src":"10.0.0.11/32", "dst":"10.0.0.12/24", "action":"drop"},
{"operation": "update", "id": 0, "l4proto":"TCP", "src":"10.0.0.100/32", "dst":"10.0.0.75/24", "action":"forward"},
{"operation": "delete", "id": 0},
{"operation": "delete", "l4proto":"ICMP", "src":"10.0.0.50/32", "dst":"10.0.0.75/24", "action":"drop"}
]
}
'''
with open(rule_file) as fp:
rules = json.load(fp)
if rules is None:
print('An error occurred reading the JSON file')
return
injectRules(cube_name, rules, chain)
print('All done :)')
def injectRules(cube_name, rules, chain):
try:
response = requests.post(
f'{polycubed_endpoint}/firewall/{cube_name}/chain/{chain}/batch', timeout=REQUESTS_TIMEOUT, json=rules)
if response.status_code == 500:
print(response.content)
return
response.raise_for_status()
print(f'Rule correctly injected')
except requests.exceptions.HTTPError:
print(
f'Unable to inject rule {rule}\n\tError -> {response.status_code}\n\tWhat -> {response.content}')
except requests.exceptions.ConnectionError:
print('Connection error: unable to connect to polycube daemon.')
exit(1)
except requests.exceptions.Timeout:
print('Timeout error: unable to connect to polycube daemon.')
exit(1)
except requests.exceptions.RequestException:
print('Error: unable to connect to polycube daemon.')
exit(1)
except json.JSONDecodeError:
print(f'Unable to decode rule {rule}')
exit(1)
def getRules(cube_name, chain):
try:
response = requests.get(
f'{polycubed_endpoint}/firewall/{cube_name}/chain/{chain}/rule', timeout=REQUESTS_TIMEOUT)
if response.status_code == 500:
print(response.content)
exit(1)
response.raise_for_status()
return json.loads(response.content)[:-1]
except requests.exceptions.HTTPError:
return False, None
except requests.exceptions.ConnectionError:
print('Connection error: unable to connect to polycube daemon.')
exit(1)
except requests.exceptions.Timeout:
print('Timeout error: unable to connect to polycube daemon.')
exit(1)
except requests.exceptions.RequestException:
print('Error: unable to connect to polycube daemon.')
exit(1)
def showVersion():
with open(f'{path.dirname(__file__)}/../VERSION', 'r') as fp:
return '%(prog)s - Version ' + fp.readline()
def parseArguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'cube_name', help='indicates the name of the cube', type=str)
parser.add_argument(
'-r', '--rule-file', help='the file containing the rules to be pushed', type=str, default=None)
parser.add_argument(
'-s', '--show-rules', help='show the rules already stored in firewall', action='store_true')
parser.add_argument(
'-e', '--egress', help='set that the rule is to be inserted in the egress chain', action='store_true')
parser.add_argument(
'-a', '--address', help='set the polycube daemon ip address', type=str, default=POLYCUBED_ADDR)
parser.add_argument(
'-p', '--port', help='set the polycube daemon port', type=int, default=POLYCUBED_PORT)
parser.add_argument('-v', '--version', action='version',
version=showVersion())
args = parser.parse_args().__dict__
if args['rule_file'] is None and args['show_rules'] is False:
parser.error('You need to specify an action (-r / -s)')
return args
if __name__ == '__main__':
main()