This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
forked from saschpe/libvirt-hook-qemu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qemu
executable file
·188 lines (150 loc) · 7.68 KB
/
qemu
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
#!/usr/bin/python
"""Libvirt port-forwarding hook.
Libvirt hook for setting up iptables port-forwarding rules when using NAT-ed
networking.
"""
__author__ = "Sascha Peilicke <[email protected]>"
__version__ = "0.1.1"
import os
import json
import re
import subprocess
import sys
CONFIG_PATH = os.getenv('CONFIG_PATH') or os.path.dirname(os.path.abspath(__file__))
CONFIG_FILENAME = os.getenv('CONFIG_FILENAME') or os.path.join(CONFIG_PATH, "qemu.json")
CONFIG_SCHEMA_FILENAME = os.getenv('CONFIG_SCHEMA_FILENAME') or os.path.join(CONFIG_PATH, "qemu.schema.json")
IPTABLES_BINARY = os.getenv('IPTABLES_BINARY') or subprocess.check_output(["which", "iptables"]).strip()
# Allow comments in json, copied from https://github.com/getify/JSON.minify
def json_minify(string, strip_space=True):
tokenizer = re.compile('"|(/\*)|(\*/)|(//)|\n|\r')
end_slashes_re = re.compile(r'(\\)*$')
in_string = False
in_multi = False
in_single = False
new_str = []
index = 0
for match in re.finditer(tokenizer, string):
if not (in_multi or in_single):
tmp = string[index:match.start()]
if not in_string and strip_space:
# replace white space as defined in standard
tmp = re.sub('[ \t\n\r]+', '', tmp)
new_str.append(tmp)
index = match.end()
val = match.group()
if val == '"' and not (in_multi or in_single):
escaped = end_slashes_re.search(string, 0, match.start())
# start of string or unescaped quote character to end string
if not in_string or (escaped is None or len(escaped.group()) % 2 == 0): # noqa
in_string = not in_string
index -= 1 # include " character in next catch
elif not (in_string or in_multi or in_single):
if val == '/*':
in_multi = True
elif val == '//':
in_single = True
elif val == '*/' and in_multi and not (in_string or in_single):
in_multi = False
elif val in '\r\n' and not (in_multi or in_string) and in_single:
in_single = False
elif not ((in_multi or in_single) or (val in ' \r\n\t' and strip_space)): # noqa
new_str.append(val)
new_str.append(string[index:])
return ''.join(new_str)
def host_ip():
"""Returns the default route interface IP (if any).
In other words, the public IP used to access the virtualization host. It
is used as default public IP for guest forwarding rules should they not
specify a different public IP to forward from.
"""
if not hasattr(host_ip, "_host_ip"):
cmd = "ip route | grep default | cut -d' ' -f5"
default_route_interface = subprocess.check_output(cmd, shell=True).decode().strip()
cmd = "ip addr show {0} | grep -E 'inet .*{0}' | cut -d' ' -f6 | cut -d'/' -f1".format(default_route_interface)
host_ip._host_ip = subprocess.check_output(cmd, shell=True).decode().strip()
return host_ip._host_ip.split('\n')[0]
def config(validate=True):
"""Returns the hook configuration.
Assumes that the file /etc/libvirt/hooks/qemu.json exists and contains
JSON-formatted configuration data. Optionally tries to validate the
configuration if the 'jsonschema' module is available.
Args:
validate: Use JSON schema validation
"""
if not hasattr(config, "_conf"):
with open(CONFIG_FILENAME, "r") as f:
config._conf = json.loads(json_minify(f.read()))
if validate:
# Try schema validation but avoid hard 'jsonschema' requirement:
try:
import jsonschema
with open(CONFIG_SCHEMA_FILENAME, "r") as f:
config._schema = json.load(f)
jsonschema.validate(config._conf,
config._schema,
format_checker=jsonschema.FormatChecker())
except ImportError:
pass
return config._conf
def create_chain(table, name):
""" Creates the named chain. """
subprocess.call([IPTABLES_BINARY, "-t", table, "-N", name])
def delete_chain(table, name):
""" Flushes and deletes the named chain. """
subprocess.call([IPTABLES_BINARY, "-t", table, "-F", name])
subprocess.call([IPTABLES_BINARY, "-t", table, "-X", name])
def populate_chains(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip, domain):
""" Fills the two custom chains with the port mappings. """
port_map = domain["port_map"]
for protocol in port_map:
for ports in port_map[protocol]:
# a single integer 80 is equivalent to [80, 80]
public_port, private_port = ports if isinstance(ports, list) else [ports, ports]
dest = "{0}:{1}".format(private_ip, str(private_port))
subprocess.call([IPTABLES_BINARY, "-t", "nat", "-A", dnat_chain, "-p", protocol,
"-d", public_ip, "--dport", str(public_port), "-j", "DNAT", "--to", dest])
subprocess.call([IPTABLES_BINARY, "-t", "nat", "-A", snat_chain, "-p", protocol,
"-s", private_ip, "-d", private_ip, "--dport", str(public_port), "-j", "MASQUERADE"])
interface = ["-o", domain["interface"]] if "interface" in domain else []
subprocess.call([IPTABLES_BINARY, "-t", "filter", "-A", fwd_chain, "-p", protocol,
"-d", private_ip, "--dport", str(private_port), "-j", "ACCEPT"] + interface)
def insert_chains(action, dnat_chain, snat_chain, fwd_chain, public_ip, private_ip):
""" inserts (action='-I') or removes (action='-D') the custom chains."""
subprocess.call([IPTABLES_BINARY, "-t", "nat", action, "OUTPUT", "-d", public_ip, "-j", dnat_chain])
subprocess.call([IPTABLES_BINARY, "-t", "nat", action, "PREROUTING", "-d", public_ip, "-j", dnat_chain])
subprocess.call([IPTABLES_BINARY, "-t", "nat", action, "POSTROUTING", "-s", private_ip, "-d", private_ip, "-j", snat_chain])
subprocess.call([IPTABLES_BINARY, "-t", "filter", action, "FORWARD", "-d", private_ip, "-j", fwd_chain])
# the snat_chain doesn't work unless we turn off filtering bridged packets
def disable_bridge_filtering():
proc_file = '/proc/sys/net/bridge/bridge-nf-call-iptables'
if(os.path.isfile(proc_file)):
with open(proc_file, 'w') as brnf:
brnf.write('0\n')
def start_forwarding(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip, domain):
""" sets up iptables port-forwarding rules based on the port_map. """
disable_bridge_filtering()
create_chain("nat", dnat_chain)
create_chain("nat", snat_chain)
create_chain("filter", fwd_chain)
populate_chains(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip, domain)
insert_chains("-I", dnat_chain, snat_chain, fwd_chain, public_ip, private_ip)
def stop_forwarding(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip):
""" tears down the iptables port-forwarding rules. """
insert_chains("-D", dnat_chain, snat_chain, fwd_chain, public_ip, private_ip)
delete_chain("nat", dnat_chain)
delete_chain("nat", snat_chain)
delete_chain("filter", fwd_chain)
if __name__ == "__main__":
vir_domain, action = sys.argv[1:3]
domain = config().get(vir_domain)
if domain is None:
sys.exit(0)
dnat_chain = "DNAT-{0}".format(vir_domain)
snat_chain = "SNAT-{0}".format(vir_domain)
fwd_chain = "FWD-{0}".format(vir_domain)
public_ip = domain.get("public_ip", host_ip())
private_ip = domain["private_ip"]
if action in ["stopped", "reconnect"]:
stop_forwarding(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip)
if action in ["start", "reconnect"]:
start_forwarding(dnat_chain, snat_chain, fwd_chain, public_ip, private_ip, domain)