VPN tunnel for outgoing connections but still allowing incoming bidirectional connections, using Wireguard or OpenVPN on Linux
For a particular use case, I need to be able to set up a Linux host (specifically Debian) to use a VPN tunnel for routing outgoing connections, but still allow incoming connections outside of that VPN tunnel and for the traffic relating to those to be routed outside of the VPN.
More concretely, it's a remote, headless host that:
- I have root access on
- I want to be able to connect to with for example (not only) SSH (thus requiring bidirectional IP traffic flow for incoming connections)
- I want for its outgoing connections to be routed through a VPN
- where the VPN in question has no provisions for incoming connections
I have tried a few times, and got as far as to being able to bring up the VPN tunnel, and immediately when I do that the SSH session dies; most likely because the routing table is updated to route traffic through the VPN. When I bring the VPN tunnel back down through a remote console, SSH starts to work again.
The VPN in question supports OpenVPN and Wireguard; for this particular situation, I'd prefer Wireguard, but if OpenVPN is easier to set up for this, that's fine. Answers relating to either are equally valid as far as this question is concerned, but please do not suggest alternative VPN technologies or switching VPN providers.
I can segregate the applications that I am most interested in being routed through the tunnel to special-purpose user accounts, and in a real pinch I could deal with something like only traffic to 80/tcp and 443/tcp being routed through the VPN tunnel, but the best would be if all outgoing connections from that host are routed through the tunnel. The killer for me seems to be allowing bidirectional data flow for connections that are initiated by other hosts toward this host; if it wasn't for that, this would be a straightforward "client" VPN setup.
Nothing in the OpenVPN or Wireguard man pages stands out to me as relevant for solving this, at least directly, but maybe I'm missing something obvious.
Web searches bring up plenty of guides on how to set up a VPN server (concentrator), but that's not relevant here.
What are my options, and what settings do I need to change for this to work? One possibility seems to me to be some kind of policy-based routing, but how can I implement that? Network namespaces, nftables
skuid matching, some kind of routing table trickery, some kind of interface affinity past routing table changes, ...? The host in question already uses nftables for firewalling purposes.