334.4 Virtual Private Networks
Weight: 4
Description: Candidates should be familiar with the use of OpenVPN, IPsec and WireGuard to set up remote access and site to site VPNs.
Key Knowledge Areas:
Understand the principles of bridged and routed VPNs
Understand the principles and major differences of the OpenVPN, IPsec, IKEv2 and WireGuard protocols
Configure and operate OpenVPN servers and clients
Configure and operate IPsec servers and clients using strongSwan
Configure and operate WireGuard servers and clients
Awareness of L2TP
Partial list of the used files, terms and utilities:
/etc/openvpn/
openvpn
/etc/strongswan.conf
/etc/strongswan.d/
/etc/swanctl/swanctl.conf
/etc/swanctl/
swanctl
/etc/wireguard/
wg
wg-quick
ip
Open VPN
What is OpenVPN?
OpenVPN is Company that created the OpenVPN Community Edition VPN server which is open-source and free to use. They also developed the OpenVPN tunneling protocol which is a tunneling protocol based on SSL encryption protocol. Many VPN services use this protocol. There is something else which is called OpenVPN Access server which is an enterprise product that has a web Interface and only offers 2 simultaneous connections on the free version.
OpenVPN Community Edition (Open Source)
OpenVPN is an open-source software application that implements virtual private network (VPN) techniques to create secure point-to-point or site-to-site connections.
OpenVPN can use a variety of methods such as pre-shared secret keys, certificates, or usernames/passwords, to let clients authenticate to the server. OpenVPN uses the OpenSSL protocol and implements many security and control features such as challenge response authentication, single sign-on capability, load balancing and failover features and multi daemon support.
By default OpenVPN works on port 1194 UDP but Open VPN is highly capable of transparently traversing through firewalls especially when the default port is chanaged to 443.
Installing OpenVPN
For demonstration we install OpenVPN on rocky linux. First Enable IP Forwarding
install openvpn (Make sure to install the epel-release package) :
Now that OpenVPN is installed. Navigate to its installation folder and download easy-rsa. Easy-RSA builds and manages certificate authorities (CAs).
Configure Easy-RSA
Next, we need to add and build an SSL certificate. To do that, first, navigate to the easy-rsa directory
for ease of use, lets create a var file, with bellow contents:
You can change the value of country, city, province, and email according to your requirements.
Now, initiate the PKI directory with the following command.
Finally, You can build your CA certificate.
Generate Server Certificate Files
Use the following command to get your key-pair and certificate request.
Sign the Server Key With CA
To sign your server key with the CA, run the following command.
We need the Diffie-Hellman key for key exchanging purposes. Generate the key by running the following command.
Next, copy all these files to the /etc/openvpn/server/ directory.
Generate Client Key and Certificate
You can get the client key by running the following command.
Next sign your client key with the generated CA certificate.
Copy these files to the /etc/openvpn/client/ directory
Configure OpenVPN Server
Make and open a new config file in the server directory with the following command.
Then add the following code lines in the file.
All OpenVPN configuration files should be configured under /etc/openvpn directory but by default no configuration files are found here. So we should either create new ones (which seems complicated) or we can easily copy sample configuration files from /usr/share/doc/openvpn-/sample/sample-config-files/server.conf to /etc/openvpn directory and modify them
Start and Enable OpenVPN Service
Your OpenVPN is ready to launch. Start and enable the server using the following commands.
A new network interface tun0 will be created on the successful start of the OpenVPN server. Run ifconfig
command to see the details.
Generate the Client Configuration File
The next step is to connect the client to the OpenVPN server. We need the client configuration file for that. To generate the client configuration file, run the following command.
Now, copy and paste the following code into the file.
You can either create client configuration file like what we have done here or copy sample client configuration file from /usr/share/doc/openvpn-/sample/sample-config-files/client.conf to /etc/openvpn/client/ and modify that.
Configure Routing
Set OpenVPN service settings with the following commands to allow it through the firewall.
Set the routing to forward the incoming traffic from the VPN to the local network.
Reload to make the changes effective.
Install and Use OpenVPN in Client Machine
You have to install epel-release and OpenVPN as you did on the server-side.
Now copy the client config files from the server using the command given below.
Go to the client directory and connect to the OpenVPN server using the following commands.
Run the ifconfig tun0
to see the assigned IP address.
openvpn command
Lets take a look at two important openvpn command options:
--mlok
Using this option ensures that key material and tunnel data are never written to disk due to virtual memory paging operations which occur under most modern operating systems. It ensures that even if an attacker was able to crack the box running OpenVPN, he would not be able to scan the system swap file to recover previously used ephemeral keys
The downside of using --mlock is that it will reduce the amount of physical memory available to other applications.
--push
Push a config file option back to the client for remote execution. Note that option must be enclosed in double quotes (""). The client must specify --pull in its config file. The set of options which can be pushed is limited by both feasibility and security. Some options such as those which would execute scripts are banned, since they would effectively allow a compromised server to execute arbitrary code on the client. Other options such as TLS or MTU parameters cannot be pushed because the client needs to know them before the connection to the server can be initiated.This is a partial list of options which can currently be pushed: --route, --route-gateway, --route-delay, --redirect-gateway, --ip-win32, --dhcp-option, --inactive, --ping, --ping-exit, --ping-restart, --setenv, --auth-token, --persist-key, --persist-tun, --echo, --comp-lzo, --socket-flags, --sndbuf, --rcvbuf
for more info review my LPIC-2 book: https://borosan.gitbook.io/lpic2-exam-guide/2125-openvpn#openvpn
Working with IPSec Server and Clients
ipsec concpet
IPSec create boundary between protected and unprotected network. Traffic traversing the boundary is a subject to access controls that specified by user or administrator responsible for IPSec configuration. From the control, the traffic maybe cross the boundary with afforded security services via AH or ESP, or are discarded.
What is IKE?
IKE. Defined in RFC 7296, IKE is a protocol that enables two systems or devices to establish a secure communication channel over an untrusted network. The protocol uses a series of key exchanges to create a secure tunnel between a client and a server through which they can send encrypted traffic. The security of the tunnel is based on the Diffie-Hellman key exchange
IPSec Policy
Fundamental of IPSec service is the concept of security policy that determined by two database. Those are, Security Policy Database (SPD), and Security Association Database (SAD). This policy applied to each IP packet that transit from a source to a destination.
Security Association
Security Association is a key concept to both node exchange information about authentication and encryption mechanism. An association is a one-way logical connection between a sender and a receiver that affords security services to the traffic carried on it
There are three parameter that identify the security association: 1. Security Parameters Index (SPI), bit string carry IPSec protocol header information to enable receiving system to select packet that will be received 2. IP Destination Address, the endpoint address of IPSec 3. Security Protocol Identifier, this field from the outer IP header indicates whether the association is an AH or ESP security association
Security Association Database (SAD)
In each IPsec implementation, there is a nominal Security Association Database that defines the parameters associated with each SA. This database stored a parameter to build IKE SA and IPSec SA. Below the parameter in an SAD entry:
1. Security Parameter Index: A 32-bit value selected by the receiving end of an SA to uniquely identify the SA 2. Sequence Number Counter: A 32-bit value used to generate the Sequence Number field in IPSec Protocol headers. 3. Sequence Counter Overflow: A flag indicating whether overflow of the Sequence Number Counter should generate an auditable event and prevent further transmission of packets on this SA 4. Anti-Replay Window: Used to determine whether an inbound AH or ESP packet is a replay 5. AH Information: Authentication algorithm, keys, key lifetimes, and related parameters being used with AH 6. ESP Information: Encryption and authentication algorithm, keys, initialization values, key lifetimes, and related parameters being used with ESP (required for ESP implementations). 7. Lifetime of this Security Association: A time interval or byte count after which an SA must be replaced with a new SA (and new SPI) or terminated, plus an indication of which of these actions should occur 8. IPsec Protocol Mode: Tunnel, transport, or wildcard 9. Path MTU: Any observed path maximum transmission unit (maximum size of a packet that can be transmitted without fragmentation) and aging variables
Security Policy Database (SPD)
Security policy stores the IP traffic that related to specific SA, it means SPD contains the entries, each entry defines a subset of IP traffic and points to an SA for that traffic. Each SPD entry is defined by IP and upper-layer protocol field values, called selector. These selector is used to filter outgoing traffic in order to map it in to a particular SA. The following selectors determine an SPD entry:
1. Remote IP Address: This may be a single IP address, an enumerated list or range of addresses, or a wildcard (mask) address for remote private network 2. Local IP Address: This may be a single IP address, an enumerated list or range of addresses, or a wildcard (mask) address for local private network 3. Next Layer Protocol: The IP protocol header (IPv4, IPv6, or IPv6 Extension) includes a field (Protocol for IPv4, Next Header for IPv6 or IPv6 Extension) that designates the protocol operating over IP 4. Name: A user identifier from the operating system. This is not a field in the IP or upper-layer headers but is available if IPsec is running on the same operating system as the user. 5. Local and Remote Ports: These may be individual TCP or UDP port values, an enumerated list of ports, or a wildcard port.
setkey
setkey adds, updates, dumps, or flushes Security Association Database (SAD) entries as well as Security Policy Database (SPD) entries in the kernel.
Notable setkey syntax:
Use -f to supply a file containing database entries.
Use -c to supply database entries via stdin.
and
• add
• get
• delete
• flush
• Dump
all manipulate the SAD database entries
spdadd, spdupdate, spddelete, spdflush, spddump all manipulate the SPD database entries
IPSec Protocol
IPSec using protocol Authentication Header (AH), and Encapsulation Security Payload (ESP), to provide traffic security services.
Authentication Header (AH)
In this protocol, IP header and data payload is hashed. From this hash, a new AH header is build which is appended to the packet. This new packet is transmitted via router where the router hashes the header and the payload. Both the hashes need to be exactly matched. Even a single bit is changed, the AH header will not match.
Encapsulating Security Payload (ESP)
This is a security protocol to provide encryption and integrity to the data packets. The ESP is added after the standard IP header. As it contains standard IP header, it can be routed easily with standard IP devices. This makes it backwards-compatible with IP routers and even those devices that were not designed to operate with IPsec. ESP is performed at the IP packet layer. It contains six parts of which two parts are only authenticated (Security Parameter Index, Sequence Number) whereas the rest of the four parts are encrypted during transmission (Payload Data, Padding, Pad Length and Next Header). It supports multiple encryption protocols and is up to the user to decide which one to opt.
Commonly, ESP using in Virtual Private Network or underlay network context, and we will focus with this protocol than Authentication Header. Because in service provider network, we often meet this kind of protocol
IPSec Encryption Technologies
Security Association (SA) can be configured two mode IPSec operation, they are Tunnel mode or Transport mode. Both modes have their own uses and should be used with caution depending upon the solution.
Tunnel Mode
This encrypts both the payload and the header. IPsec in tunnel mode is used when the destination of the packet is different than the security termination point. The most common use of this mode is between gateways or from end station to gateway. The gateway serves as a proxy for the hosts. So when the origin of the packets differs from the device that is providing security, tunnel mode is used.
Transport Mode
In this encryption mode, only the data portion of each packet is encrypted. This mode is applicable between end stations or between end station and gateway.
IP Traffic Processing
IPSec is executed on a packet on packet-by-packet basis. When IPSec implemented, each outbound packet is processed by IPSec logic before transmission. The Packet that sent must be consulted with the Security Policy Database (SPD) (or associated caches). If no policy is found in the SPD that matches a packet (for either inbound or outbound traffic), the packet MUST be discarded, vice versa.
How does it work
IPsec makes use of tunneling. The data packets that we define sensitive or interesting are sent through the tunnel securely. By defining the characteristics of the tunnel, the security protection measures of sensitive packets are defined. IPsec offers numerous technologies and encryption modes. But its working can be broken into five major steps. A brief overview is given below:
1. Interesting Traffic Initiation
The sensitive traffic that needs to be monitored is deemed interesting. After deciding about the traffic, the security policy is implemented on the configuration interface for the peers. When this traffic transits the IPsec client, the IKE phase one is triggered.
2. IKE Phase One
In this step, first the IPsec peers are authenticated thus protecting the identities of the peers. Then the Internet Key Exchange (IKE) Security Associations (SA) policy is negotiated among the peers. This results in both the parties to have a shared secret matching key that helps in the IKE phase two. Also, in this phase, there is setting up of a secure tunnel through which the exchange of information for phase two will occur. This phase has two operating modes
Main Mode: There are three exchanges among the initiator and the receiver. In first exchange, algorithms and hashes are exchanged. The second exchange is responsible for generations of shared secret keying using Diffie-Hellman exchange. The last exchange is for the verification of the other side’s identity. All three of these exchanges are bi-directional.
Aggressive Mode: There are fewer exchanges in this mode. All the required information is squeezed making it faster to use. The only trouble is that information is shared before there is a secure channel making this mode vulnerable.
3. IKE Phase Two
This phase negotiates information for IPsec SA parameters through the IKE SA. Here as well IPsec policies are shared and then establish IPsec SAs. There is only a single mode (quick mode) in this phase. It exchanges nonce providing replay protection. These nonces generate new shared secret key material. If the lifetime for IPsec expires, it can renegotiate a new SA.
4. Data Transfer
Here the data is safely and securely transmitted through the IPsec tunnel. The sent packets are encrypted and decrypted using the specified encryption in the IPsec SAs.
5. Tunnel Termination
The tunnel may terminate by either deletion or by time out. Time out occurs when the specified time (sec) has passed or when specified number of bytes will have passed through the tunnel.
What is racoon?
The racoon tool is the key exchange daemon for the IPsec IKE protocol. In the case of shared keys, hosts are authenticated dynamically by racoon using preshared secret keys. With the certificate method, hosts are authenticated using certificate files.
(1)The administrator sets a policy to SPD by using setkey. (2)Kernel refers to SPD in order to make a decision of applying IPsec to a packet. (3)If IPsec is required, then kernel get the Key for IPsec-SA from SAD. (4)If it is failed, then kernel send a request to get the Key to racoon. (5)racoon exchange the Key by using IKE with the other to be established IPsec-SA. (6)racoon put the Key into SAD. (7)Kernel can send a packet applied IPsec.
/etc/racoon/racoon.conf
The racoon configuration file is located at /etc/racoon/racoon.conf. A very simple configuration is shown in the following example:
/etc/ipsec-tools.conf
The ipsec-tools
package includes utilities needed for establishing connection. the configuration file is /etc/ipsec-tools.conf
.
L2TP
L2TP is a VPN technology. It is insecure by itself. It must be used over an IPSec link due to this.
Strongswan
Strongswan Overview
strongSwan is an OpenSource IPsec-based VPN solution. It was originally based on the discontinued FreeS/WAN project . StrongSwan originally was designed for Linux, but has since been ported to Android, FreeBSD, Mac OS X, Windows and other platforms. The focus of strongSwan is on:
Simplicity of configuration
Strong encryption and authentication methods
Powerful IPsec policies supporting large and complex VPN networks
Modular design with great expandability
The maintainer of the strongSwan project is Andreas Steffen, who is a professor for security in communications and head of the Institute for Internet Technologies and Applications at the University of Applied Sciences Rapperswil in Switzerland and president of the consulting firm strongSec GmbH.
installing strongswan
for installing strongswan on RedHat distributions first you need to enable epel-repo and then install it:
check the strongswan configuration directory:
strongswan.conf
Check the configuration file, strongswan.conf, you free to modify this file depend on your own and concern:
swanctl
swanctl is a cross-platform command line utility to configure, control and monitor the strongSwan IKE daemon (charon) via the vici
interface plugin. It is a replacement for the aging starter, ipsec and stroke tools.
The charon
daemon was built from scratch to implement the IKEv2 protocol for the strongSwan project. Most of its code is located in the libcharon
library making the IKE daemon core available to other programs such as charon-systemd
, charon-svc
, charon-cmd
or the Android app.
The vici
[ˈvitʃi] plugin for libcharon
provides the Versatile IKE Control Interface (VICI). As its name indicates, it provides an interface for external applications to not only configure, but also to control and monitor the IKE daemon charon
.
Subcommands:
Each subcommand has additional options. Pass --help
to a subcommand to get additional information.
swanctl uses a configuration file called swanctl. conf(5) to parse configurations and credentials.
swanctl.conf
The swanctl --load-…
commands read connections, secrets and IP address pools from swanctl.conf
located in the swanctl configuration directory, usually /etc/swanctl
.
The configuration file to be loaded may be specified for each command explicitly via the --file
argument, e.g. to use separate files for the connections
and secrets
sections.
time formats
For all options that define a time, the time is specified in seconds. The s, m, h and d suffixes explicitly define the units for seconds, minutes, hours and days, respectively.
The path to the
swanctl
directory can also be set with theSWANCTL_DIR
environment variable.
example:
Certificates for users, hosts and gateways are issued by a fictitious strongSwan CA. In our example scenarios the CA certificate strongswanCert.pem
must be present on all VPN endpoints in order to be able to authenticate the peers. For your particular VPN application you can either use certificates from any third-party CA or generate the needed private keys and certificates yourself with the strongSwan pki tool, the use of which will be explained in one of the sections following below.
Site-to-Site Case
In this scenario two security gateways moon and sun will connect the two subnets moon-net and sun-net with each other through a VPN tunnel set up between the two gateways:
Configuration on gateway moon:
Configuration on gateway sun:
The local and remote identities used in this scenario are the subjectDistinguishedNames contained in the end entity certificates. The certificates and private keys are loaded into the charon daemon with the command
whereas
loads the connections defined in swanctl.conf
. With start_action = trap
the IPsec connection is automatically set up with the first plaintext payload IP packet wanting to go through the tunnel.
to see more examples, visit the strongswan official github page: https://github.com/strongswan/strongswan
Wiregaurd
WireGuard® is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims to be faster, simpler, leaner, and more useful than IPsec, while avoiding the massive headache. It intends to be considerably more performant than OpenVPN.
WireGuard is designed as a general purpose VPN for running on embedded interfaces and super computers alike, fit for many different circumstances. Initially released for the Linux kernel, it is now cross-platform (Windows, macOS, BSD, iOS, Android) and widely deployable. It is currently under heavy development, but already it might be regarded as the most secure, easiest to use, and simplest VPN solution in the industry.
Install Wireguard
Here we use rocky8:
This step also installs GNU GCC compiler needed to build the Linux Kernel modules.
Wiregaurd Configuration
WireGuard aims to be as easy to configure and deploy as SSH. A VPN connection is made simply by exchanging very simple public keys – exactly like exchanging SSH keys – and all the rest is transparently handled by WireGuard.
Configure Wireguard Server
Create an empty configuration file on the server for Wireguard settings with proper permissions.
After creating the directory, create the public and private keys using the “wg” and “tee” command-line tools.
wg
wg is the configuration utility for getting and setting the configuration of WireGuard tunnel interfaces. The interfaces themselves can be added and removed using ip-link(8)
and their IP addresses and routing tables can be set using ip-address(8)
and ip-route(8)
. The wg utility provides a series of sub-commands for changing WireGuard-specific aspects of WireGuard interfaces.Available subcommands:
show
: Shows the current configuration and device informationshowconf
: Shows the current configuration of a given WireGuard interface, for use withsetconf'
set:
Change the current configuration, add peers, remove peers, or change peerssetconf:
Applies a configuration file to a WireGuard interfaceaddconf:
Appends a configuration file to a WireGuard interfacesyncconf:
Synchronizes a configuration file to a WireGuard interfacegenkey:
Generates a new private key and writes it to stdoutgenpsk:
Generates a new preshared key and writes it to stdoutpubkey:
Reads a private key from stdin and writes a public key to stdout
You may pass
--help
to any of these subcommands to view usage.
okey, lets create a private/public key pair for the Wireguard server using wg command:
The generated key will be printed upon execution of the above command.
Next we need to Configure a Tunnel Device for Routing VPN Traffic.To set up a device, create a configuration file in the ‘/etc/wireguard’ directory
Before creating the configuration file, obtain the Private Key:
Save the private key somewhere; you will need this key later in the configuration file.
Now, create the “wg0.conf” file.
This configuration file contains the following key terms:
Address – the private IP address for the Interface (wg0).
SaveConfig = true – saves the state of the interface on restart or shutdown of the server.
ListenPort – the port where the WireGuard daemon listens.
PrivateKey – the key that we have just generated.
PostUp – this command will be executed before firing up the interface
PostDown – this command will be executed before turning off the interface.
Do not forget to Set Privileges of Configuration and “privatekey” File:
Start the Interface
To fire up the interface, issue the command given below:
If you have obtained the output shown in the section above, you have successfully started the interface. You check the status of the interface with wg
command:
obviously you can bring down the interface via sudo wg-quick up wg0
command.
You can also enable the interface to auto-start the interface on boot of the OS via
sudo systemctl enable wg-quick@wg0
At this stage, the server setup has been completed. Now, if you want to set up this VPN server for NAT, you will need to enable IPv4 forwarding.
Enable IPv4 Forwarding
To enable IPv4 forwarding for the NAT, create a “99-custom.conf” file in the “/etc/sysctl.d” directory
Configure Wireguard Client
First install wiregaurd by repeating same steps we have mentioned above.
Create Public and Private Keys
In this step, we will create a new ‘/etc/wireguard’ directory in the Client machine.
After creating the directory, create the public and private keys using the “wg” and “tee” command-line tools.
Next, Configuration for Routing VPN Traffic. Before creating the configuration file, get the Private key using the following command:
Now, create the “wg0.conf” file:
The configuration file contains the following key terms:
PrivateKey – the key generated on the client machine.
Address – the IP address for the Interface (wg0).
PublicKey – the public key of the VPN server machine to which we want to connect.
AllowedIPs – all allowed IP addresses for traffic flow using the VPN.
Endpoint – we will provide the IP address and port number of the CentOS 8 server machine to which we want to connect.
Set Privileges of Configuration and “privatekey” File:
wg-quick
Now that we have finalized the permissions, we can fire up the interface (wg0) using the wg-quick
command-line tool.
and finnaly you can get the status of the link on client with simple wg command:
Enable the interface to auto-start the interface on boot via
systemctl enable wg-quick@wg0
command.
Add IP Address and Public Key of Client to Rocky 8 Server
The final step is to add the IP address and public key of the VPN client machine to the configuration file of the Rocky 8 WireGuard VPN server machine.
Return to the server machine and add the following content to the “/etc/wireguard/wg0.conf” file:
so it would be like this at the end:
use wg
command to Verify Tunnel Connection.
that's all!
.
.
.
resources:
https://en.wikipedia.org/wiki/OpenVPN
https://www.geeksforgeeks.org/how-to-install-and-setup-the-openvpn-server-on-ubuntu-debian/
https://vitux.com/how-to-install-openvpn-on-almalinux-8-centos-8-or-rocky-linux-8/
https://openvpn.net/community-resources/reference-manual-for-openvpn-2-4/
https://ngoprek.achyarnurandi.id/2016/07/learning-how-build-ipsec-site-to-site.html
https://www.kame.net/newsletter/20001119/
https://github.com/strongswan/strongswan
https://docs.strongswan.org/docs/5.9/swanctl/swanctl.html
https://docs.strongswan.org/docs/5.9/daemons/charon.html
https://docs.strongswan.org/docs/5.9/plugins/vici.html
https://docs.strongswan.org/docs/5.9/index.html
https://www.howtoforge.com/how-to-set-up-wireguard-vpn-on-centos-8/
https://manpages.debian.org/unstable/wireguard-tools/wg.8.en.html
https://linuxhint.com/install-wireguard-vpn-centos/
https://gist.github.com/dockerlead/e9f025264b1b2caeba34f5d85fe1e866
.
Last updated