[systemd-devel] nspawn: how to allow containers to connect to a specific host's port and prevent all the rest ?

Lennart Poettering lennart at poettering.net
Fri Mar 31 06:09:03 UTC 2017


On Tue, 07.03.17 10:02, Fabien Meghazi (fme at odoo.com) wrote:

> Hello everyone,
> 
> I would like to constraint the network in the containers I spawn using
> nspawn.
> What I'd like to achieve is the following:
> 
> - prevent the containers to use the network interfaces of the host
> - make one exception and allow the containers to connect (tcp) to a
> specific port bound on the host's loopback device
> 
> The option --private-network allows me to achieve the first goal, once I
> use this option the container is "network isolated".
> 
> Then, reading the man page, I though that using --port would allow the
> container to connect to a host specific port so here's what I've been
> trying so far:
> 
> On the host I run netcat so I can check connections on the guest:
> 
>     root at host # netcat -l -p 1234
> 
> >From the host, I can telnet to localhost 1234 without problem.
> Then I run the container like this:
> 
>     root at host #  systemd-nspawn -M test --private-network --port 1234
> 
> But from the container I can't connect back to the host
> 
>     root at test # telnet localhost 1234
>     Trying ::1...
>     Trying 127.0.0.1...
>     telnet: Unable to connect to remote host: Connection refused
> 
> 
> So I guess I've been using the --port option in an inappropriate way
> thinking it would map a host port to the container loopback
> interface.

The --port option works the other way round: it permits connecting to
a host port which then ends up on the container's virtual network
interface.

> I checked the other networking options but I could not find something
> suitable for my use case.
> Any idea about how I could allow the container to connect to a specific
> port on the host but forbid all the rest ?

--private-network will create a virtual network between host and the
container, and it will assign IP addresses automatically to it. You
can use normal firewalling (i.e iptables) to restrict what may be sent
in and out of the container.

for example, on the host you could add a DROP rule that prohibits all
incoming traffic from the network interface pointing to the container
(that name of that is stable and generated from the container name,
"machinectl status <foobar>" will show you what it is), except for
that on the specific port.

If your container is set up properly, and has nss-myhostname enabled
you can reach the host's address always under the name "gateway" if
you want to connect to it.

Long story short: it's like in normal IP networking, nspawn will
provide you a virtual network and you can use the same tools as you
would with physical devices.

Lennart

-- 
Lennart Poettering, Red Hat


More information about the systemd-devel mailing list