Currently showing posts tagged: iptables

port redirection from kvm host to guest

By , January 23, 2012 2:58 am

I’ve just started using kvm in earnest, and immediately ran into the challenge of how to access my guest via ssh. My first instinct was to configure the guest in bridged mode, but this doesn’t work well (or at all) with wireless interfaces.

So plan B was to set up port redirection from the host to the guest, e.g. so that ssh’ing to localhost port 2222 would redirect to the guest’s port 22.

After a quick google, some fiddling with iptables, and a glance at the libvirt Networking wiki page, I was still having no luck. Then it hit me – my guest was using user-mode networking, and rather than getting its DHCP-allocated IP from the libvirtd-launched dnsmasq instance on the host, was receiving a hardcoded allocation of 10.0.2.15 from the host which is on 10.0.2.2. This can be extremely puzzling at first, because no network commands run on the host (such as ifconfig, iptables, brctl, route) will reveal this magic address, yet the host is still accessible from the guest via it.

After a lot more googling, I stumbled across a technique for configuring host to guest port redirection on a running VM. This sounded very promising, but virt-manager refused to accept the magic Control-Alt-2 key combination to switch to QEMU monitor mode. It turns out that this is no accident. However, since libvirt 0.8.8, the QEMU monitor can be accessed via virsh.
Note that the --hmp option is required, otherwise the monitor expects the command in JSON format, so omitting it leads to errors like error: internal error cannot parse json ... lexical error: invalid char in json text.

The final hurdle was figuring out the correct monitor command. The host_net_redir command as mentioned in the above article is no longer recognized. Luckily the QEMU monitor interface helped me out here – I spotted an encouraging sounding command hostfwd_add:

# virsh qemu-monitor-command --hmp sles11 'help hostfwd_add'
hostfwd_add [vlan_id name] [tcp|udp]:[hostaddr]:hostport-[guestaddr]:guestport -- redirect TCP or UDP connections from host to guest (requires -net user)

and google confirmed that the latter had superceded the former.

So finally we have the complete solution:

# virsh qemu-monitor-command --hmp sles11 'hostfwd_add ::2222-:22'
# ssh -p 2222 localhost
Password:
Last login: Mon Jan 23 00:37:44 2012
linux-mnsh:~ #

Hooray!

UPDATE: just found another very simple solution – add a new NIC to the VM which doesn’t use user-mode networking. Then it will get a IP (on 192.168.100.0/24 by default) which is still NAT’d but also routable via virbr0 on the host, meaning no redirection is necessary; just ssh directly to the guest’s IP from the host. A minor disadvantage of this is that the guest won’t be directly reachable from outside the host, but that’s unlikely to be an issue in most scenarios.

Share

Panorama Theme by Themocracy