Making a service only accessible when connected to vpn via wg-easy

Alright, I'm very happy that after years, I figured it out and I'd like to share it.

The first clue was: connecting and disconnecting from the vpn showed no change when going to whoami.mydomain.com. So the key here is to get that to change.

Turns out when you're using docker swarm, and traefik is in it, and you're just normally exposing ports 80 and 443, the "real IP" doesn't get forwarded through. So, you need to update your docker-compose file stack to use "host" mode:

ports:
      - target: 80
        published: 80
        protocol: tcp
        mode: host
      - target: 443
        published: 443
        protocol: tcp
        mode: host

Once that's done and you redeploy, you'll see that connecting and disconnecting from the VPN does indeed change the IP address in the X-Forwarded-For header.

X-Forwarded-For: 172.18.0.1

Next, now that you see a different IP when you connect / disconnect from the VPN, the CIDR for that is used in the whitelist middleware.

I didn't know too much about middleware CIDRs so I did a bit of research. I originally thought putting /32 of an IP meant that it would cater to all 172.x.x.x IPs but no.. actually /32 is MORE specific and would require that EXACT IP to be used.

So, you put /8 on the end to allow all IPs from 172.x.x.x.

The middleware whitelist now looks like this:

  middlewares:
    ipwhitelist-vpn:
      ipAllowList:
        sourceRange:
          - "172.0.0.0/8"

Stick that in your dynamic config and make your whoami router use it and there you go! FINALLY.

--

The caveat here is that it's less secure than using overlay networking modes, because it gives containers direct asccess to the host network stack. This means they bypass Docker's virtual network isolation, so containers can interact with the host network resources directly. But I trust traefik, so hopefully no issue.

But if anyone figures out how to do this without using host network mode, I'd love to hear. Maybe this is a starting point?

1 Like