You are here: Home / Debian GNU/Linux / System / Xen / Opening the ports of a Xen domU using NAT

Opening the ports of a Xen domU using NAT

by Pierre-Yves Landuré last modified Mar 31, 2014 09:51

When Xen is setted up with a NAT network, iptables is needed to associate domU's ports to dom0 ones. This howto helps you to configure the needed iptables' rules.

This howto is tested on :

  • Debian 5.0 Lenny
  • Debian 6.0 Squeeze
  • Debian 7.0 Wheezy

Parameters

Provide the IP address of the domU which ports are to be opened :

DOMU_IP="10.0.0.1"

Provide the domU's port number to open :

DOMU_PORT=80

Note : you can provide a port range :

# DOMU_PORT=49160-49299

Provide the network interface to which bind the domU's port (optionnal, eth0 is used by default) :

# DOM0_NET="eth0"

Provide the protocol (optionnal, by default tcp) :

# DOMU_PROTO="udp"

Installation

Prerequisites

Create the iptables rules file. The rules presents in this file are applied at network interfaces startup :

if [ ! -e '/etc/network/if-up.d/iptables' ]; then
  command echo '#!/bin/sh
# IpTables rules.

# Purging prerouting rules before reloading them
iptables -t nat -F PREROUTING' \
> '/etc/network/if-up.d/iptables' fi command chmod +x '/etc/network/if-up.d/iptables'

Allow iptables to use NAT :

command sed -i -e 's/[# ]*\(net\.ipv4\.conf\.default\.forwarding=\).*/\11/g' \
               -e 's/[# ]*\(net\.ipv4\.ip_forward=\).*/\11/g' \
    '/etc/sysctl.conf'
command sysctl -p

Setup

Detectez the IP address IP of the binded network interface :

test -z "${DOM0_NET}" && DOM0_NET="eth0"
DOM0_IP=$(command ifconfig ${DOM0_NET} \
| command grep "inet adr" \
| command sed -e 's/.*inet adr:\([^ ]*\) .*/\1/')

Detect the protocol :

test -z "${DOMU_PROTO}" && DOMU_PROTO="tcp"

Load the new NAT rule :

command iptables -C PREROUTING -t nat \
-p ${DOMU_PROTO} -d ${DOM0_IP} --dport $(echo ${DOMU_PORT} | command tr '-' ':') \
 -j DNAT --to ${DOMU_IP}:${DOMU_PORT} 2>'/dev/null' \
|| command iptables -A PREROUTING -t nat \
-p ${DOMU_PROTO} -d ${DOM0_IP} --dport $(echo ${DOMU_PORT} | command tr '-' ':') \
 -j DNAT --to ${DOMU_IP}:${DOMU_PORT}

Add the NAT rule to the permanent iptables configuration :

CLEAN_DOMU_PORT=$(echo ${DOMU_PORT} | command tr '-' ':')
echo " # Opening port ${DOMU_PORT} from ${DOM0_IP} to IP address ${DOMU_IP} :
command iptables -C PREROUTING -t nat -p ${DOMU_PROTO} \\
    -d ${DOM0_IP} --dport ${CLEAN_DOMU_PORT} \\
    -j DNAT --to ${DOMU_IP}:${DOMU_PORT} 2>'/dev/null' \\
  || command iptables -A PREROUTING -t nat -p ${DOMU_PROTO} \\
-d ${DOM0_IP} --dport ${CLEAN_DOMU_PORT} \\
-j DNAT --to ${DOMU_IP}:${DOMU_PORT}
" \ >> '/etc/network/if-up.d/iptables'