Skip to content

Instantly share code, notes, and snippets.

@namazso
Last active December 24, 2023 17:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namazso/f08ce21897022f97c206c996656b5d80 to your computer and use it in GitHub Desktop.
Save namazso/f08ce21897022f97c206c996656b5d80 to your computer and use it in GitHub Desktop.
Wireguard VPN with NetworkManager and firewalld

WireGuard VPN setup with NetworkManager and firewalld

Prerequisites

This guide uses NetworkManager and firewalld. Both of these are installed and used by default on current versions of Red Hat Enterprise Linux and Fedora.

First, test that NetworkManager is in use:

# nmcli
eth0: connected to eth0
        "The Linux Foundation Microsoft Hyper-V"
        ethernet (hv_netvsc), 00:15:5D:01:03:0C, hw, mtu 1500
        ip4 default, ip6 default
        inet4 192.168.1.134/24
        route4 192.168.1.0/24 metric 100
        route4 default via 192.168.1.1 metric 100
        inet6 2001:4c4e:24cd:d400:215:5dff:fe01:30c/64
        inet6 fe80::215:5dff:fe01:30c/64
        route6 fe80::/64 metric 1024
        route6 2001:4c4e:24cd:d400::/64 metric 100
        route6 2001:4c4e:24cd:d400::/64 via fe80::8efd:deff:fe33:fb18 metric 105
        route6 default via fe80::8efd:deff:fe33:fb18 metric 100

lo: connected (externally) to lo
        "lo"
        loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536
        inet4 127.0.0.1/8
        inet6 ::1/128

DNS configuration:
        servers: 192.168.1.1
        domains: home
        interface: eth0

        servers: 2001:4c48:1::1
        domains: home
        interface: eth0

Then test that firewalld is active:

# firewall-cmd --state
running

Generating a WireGuard configuration file

VPN services that support WireGuard will usually have a configuration generator site or guide. My chosen service, AirVPN, generated the following file when selecting a Czeh server:

[Interface]
Address = 10.184.152.149/32, fd7d:76ee:e68f:a993:d172:bc31:cc8:3a7f/128
PrivateKey = 6K+Ij5DThhAdbW2YL7gyjvhKOTV37qmZZQ6p8oSjH0U=
MTU = 1320
DNS = 10.128.0.1, fd7d:76ee:e68f:a993::1

[Peer]
PublicKey = PyLCXAQT8KkM4T+dUsOQfn+Ub3pGxfGlxkIApuig+hk=
PresharedKey = bXLsMq+/4koXwJ8UFcqZCoGLJOzokeKiZd6M9VP0CDM=
Endpoint = 185.156.174.117:1637
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 15

These are usually fairly similar across services, so just substitute your own one in place.

Importing into NetworkManager

Rename your configuration to the name you'd like the profile and interface to be named. I chose wg-centaurus.conf as that's what AirVPN calls this specific server. Then, import the file:

# nmcli connection import type wireguard file wg-centaurus.conf
Connection 'wg-centaurus' (4e1b0fd1-6fd1-46a1-9358-03b6f238d58f) successfully added.

It should automatically connect, and you should now have the masked IP address! We should test it:

# curl ipinfo.io
{
  "ip": "185.156.174.115",
  "hostname": "115.174.156.185.in-addr.arpa",
  "city": "Prague",
  "region": "Prague",
  "country": "CZ",
  "loc": "50.0880,14.4208",
  "org": "AS9009 M247 Europe SRL",
  "postal": "110 00",
  "timezone": "Europe/Prague",
  "readme": "https://ipinfo.io/missingauth"
}
# curl v6.ipinfo.io
{
  "ip": "2001:ac8:33:8:f7e9:fa3:a40c:ab11",
  "city": "Prague",
  "region": "Prague",
  "country": "CZ",
  "loc": "50.0880,14.4208",
  "org": "AS9009 M247 Europe SRL",
  "postal": "110 00",
  "timezone": "Europe/Prague",
  "readme": "https://ipinfo.io/missingauth"
}

Killswitch with firewalld

Now, see what happens if we disable the VPN profile:

# nmcli connection down wg-centaurus
Connection 'wg-centaurus' successfully deactivated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)
# curl ipinfo.io
{
  ...
  "country": "HU",
  ...
}
#curl v6.ipinfo.io
{
  ...
  "country": "HU",
  ...
}

As expected, the internet is still accessible, however the original IP is displayed.

To prevent this from happening, we'll be following meow646's blogpost on setting up a VPN Killswitch. Please visit their site for full details.

We first create the policy:

# firewall-cmd --permanent --new-zone VPN-Only
success
# firewall-cmd --permanent --zone VPN-Only --set-target DROP
success
# firewall-cmd --permanent --new-policy VPN-Killswitch
success
# firewall-cmd --permanent --policy VPN-Killswitch --set-target DROP
success
# firewall-cmd --reload
success

Then we exclude the VPN server from the policy. Since AirVPN is using a non-standard WireGuard port, we modify the command to allow a specific port instead of the predefined wireguard service:

# firewall-cmd --policy VPN-Killswitch --add-rich-rule='rule family="ipv4" destination address="185.156.174.117" port port="1637" protocol="udp" accept'
success

If you want to allow access to your LAN, you'll need to add a rule for that too. My network uses the 192.168.1.0/24 range, therefore I'm running the command unmodified:

# firewall-cmd --policy VPN-Killswitch --add-rich-rule='rule family="ipv4" destination address="192.168.1.0/24" accept'
success

Then we set ingress and egress zones:

# firewall-cmd --policy VPN-Killswitch --add-ingress-zone HOST
success
# firewall-cmd --policy VPN-Killswitch --add-egress-zone VPN-Only
success

Next we add the network interfaces. As seen in the initial nmcli, I only have one named eth0:

# firewall-cmd --permanent --zone VPN-Only --add-interface=eth0
The interface is under control of NetworkManager, setting zone to 'VPN-Only'.
success

And we should be done. Time to test it again:

# curl --connect-timeout 1 ipinfo.io
curl: (28) Failed to connect to ipinfo.io port 80 after 1001 ms: Timeout was reached
# curl --connect-timeout 1 v6.ipinfo.io
curl: (28) Failed to connect to v6.ipinfo.io port 80 after 1000 ms: Timeout was reached

Great, seems like there's no connection made. Let's enable VPN and try again:

# nmcli connection up wg-centaurus
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/5)
# curl --connect-timeout 1 ipinfo.io
{
  "ip": "185.156.174.115",
  "hostname": "115.174.156.185.in-addr.arpa",
  "city": "Prague",
  "region": "Prague",
  "country": "CZ",
  "loc": "50.0880,14.4208",
  "org": "AS9009 M247 Europe SRL",
  "postal": "110 00",
  "timezone": "Europe/Prague",
  "readme": "https://ipinfo.io/missingauth"
}
# curl --connect-timeout 1 v6.ipinfo.io
{
  "ip": "2001:ac8:33:8:f7e9:fa3:a40c:ab11",
  "city": "Prague",
  "region": "Prague",
  "country": "CZ",
  "loc": "50.0880,14.4208",
  "org": "AS9009 M247 Europe SRL",
  "postal": "110 00",
  "timezone": "Europe/Prague",
  "readme": "https://ipinfo.io/missingauth"
}

And it seems like the VPN connection still works as intended. Now, we should write the running configuration to file so it doesn't go away on a reboot:

# firewall-cmd --runtime-to-permanent
success

Port forwarding

This is the exact same as without a VPN when using firewalld, however for the sake of completeness is included here. I prefer creating a "service" to group the VPN forwarded ports under:

# firewall-cmd --permanent --new-service=vpn-ports
success
# firewall-cmd --permanent --service=vpn-ports "--set-description=VPN Ports"
success
# firewall-cmd --permanent --service=vpn-ports "--set-short=VPN Ports"
success
# firewall-cmd --permanent --service=vpn-ports --add-port=3333/tcp
success

Now we just want to allow this service on the VPN connection's zone. Let's find out the zone:

# firewall-cmd --get-active-zones
FedoraServer
  interfaces: wg-centaurus
VPN-Only
  interfaces: eth0

And add the service:

# firewall-cmd --permanent --zone=FedoraServer --add-service=vpn-ports
success

Then reload, as --permanent does not apply to the current running configuration:

# firewall-cmd --reload
success

Let's test if it worked by listening on the port with netcat:

# nc -v -l 3333
Ncat: Version 7.93 ( https://nmap.org/ncat )
Ncat: Listening on :::3333
Ncat: Listening on 0.0.0.0:3333

And on another device, let's visit the expected URL:

# curl http://185.156.174.115:3333/

This should result in netcat printing the request:

Ncat: Connection from 185.9.19.107.
Ncat: Connection from 185.9.19.107:40518.
GET / HTTP/1.1
Host: 185.156.174.115:3333
User-Agent: curl/8.0.1
Accept: */*

Congratulations, your port forward is working!


"WireGuard" is a registered trademark of Jason A. Donenfeld.


LICENSE OF THIS GUIDE:

Creative Commons Legal Code

CC0 1.0 Universal

    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
    HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

  i. the right to reproduce, adapt, distribute, perform, display,
     communicate, and translate a Work;
 ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
     likeness depicted in a Work;
 iv. rights protecting against unfair competition in regards to a Work,
     subject to the limitations in paragraph 4(a), below;
  v. rights protecting the extraction, dissemination, use and reuse of data
     in a Work;
 vi. database rights (such as those arising under Directive 96/9/EC of the
     European Parliament and of the Council of 11 March 1996 on the legal
     protection of databases, and under any national implementation
     thereof, including any amended or successor version of such
     directive); and
vii. other similar, equivalent or corresponding rights throughout the
     world based on applicable law or treaty, and any national
     implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

 a. No trademark or patent rights held by Affirmer are waived, abandoned,
    surrendered, licensed or otherwise affected by this document.
 b. Affirmer offers the Work as-is and makes no representations or
    warranties of any kind concerning the Work, express, implied,
    statutory or otherwise, including without limitation warranties of
    title, merchantability, fitness for a particular purpose, non
    infringement, or the absence of latent or other defects, accuracy, or
    the present or absence of errors, whether or not discoverable, all to
    the greatest extent permissible under applicable law.
 c. Affirmer disclaims responsibility for clearing rights of other persons
    that may apply to the Work or any use thereof, including without
    limitation any person's Copyright and Related Rights in the Work.
    Further, Affirmer disclaims responsibility for obtaining any necessary
    consents, permissions or other rights required for any use of the
    Work.
 d. Affirmer understands and acknowledges that Creative Commons is not a
    party to this document and has no duty or obligation with respect to
    this CC0 or use of the Work.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment