Created
January 31, 2014 14:25
-
-
Save flaviocdc/8732974 to your computer and use it in GitHub Desktop.
Working IPTables NAT QEMU hook
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
#!/usr/bin/env python | |
import sys | |
import os | |
import errno | |
from time import sleep | |
FIFO_PATH = "/etc/scripts/ipc" | |
MESSAGE="libvirtd-restart\n" | |
SLEEP_SECS=2 | |
MY_IP="146.164.248.216" | |
GW_IP="192.168.122.1" | |
def main(): | |
fd = os.open(FIFO_PATH, os.O_RDONLY | os.O_NONBLOCK) | |
while True: | |
try: | |
msg = os.read(fd, len(MESSAGE)) | |
if len(msg) == 0: | |
sleep(SLEEP_SECS) | |
continue | |
wait_for_libvirtd_firewall() | |
apply_rules() | |
except OSError, e: | |
if e.errno == errno.EAGAIN: | |
sleep(SLEEP_SECS) | |
pass | |
raise | |
def ipt_forward(src_port, dst_ip, dst_port): | |
os.system("/sbin/iptables -I PREROUTING -t nat -d %s -p tcp --dport %d -j DNAT --to-destination %s:%d" % (MY_IP, src_port, dst_ip, dst_port)) | |
os.system("/sbin/iptables -I FORWARD 1 -p tcp -d %s --dport %d -j ACCEPT" % (dst_ip, dst_port)) | |
os.system("/sbin/iptables -I POSTROUTING -t nat -d %s -p tcp -s 192.168.122.0/24 --dport %d -j SNAT --to %s" % (dst_ip, dst_port, GW_IP)) | |
def wait_for_libvirtd_firewall(): | |
print "libvirtd restartado, esperando para poder aplicar regras do firewall" | |
ret = -1 | |
while (ret != 0): | |
ret = os.system("iptables -L -n | grep \"reject-with icmp-port-unreachable\"") | |
print "libvirtd firewall nao esta pronto ainda..." | |
sleep(0.5) | |
print "libvirtd firewall ready" | |
def apply_rules(): | |
print "Aplicando regras de NAT" | |
ipt_forward(22022, "192.168.122.128", 22) | |
ipt_forward(22023, "192.168.122.128", 9000) | |
ipt_forward(23022, "192.168.122.129", 22) | |
ipt_forward(5667, "192.168.122.129", 5666) | |
ipt_forward(55901, "192.168.122.129", 5900) | |
main() |
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
#!/usr/bin/env python | |
import sys | |
import os | |
import errno | |
from time import sleep | |
FIFO_PATH = "/etc/scripts/ipc" | |
MESSAGE="libvirtd-restart\n" | |
operation = sys.argv[2] | |
if operation == "start": | |
while True: | |
try: | |
fd = os.open(FIFO_PATH, os.O_WRONLY | os.O_NONBLOCK) | |
os.write(fd, MESSAGE) | |
os.close(fd) | |
break | |
except OSError, e: | |
if e.errno == errno.ENXIO: | |
sleep(1) | |
continue | |
raise e | |
if operation == "shutdown": | |
os.system("iptables -F -t nat") | |
os.system("iptables -F") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment