Set Up OpenConnect VPN Server (ocserv) on Ubuntu 20.04 with Letās Encrypt
This tutorial is going to show you how to run your own VPN server by installing OpenConnect VPN server on Ubuntu 20.04. OpenConnect VPN server, aka ocserv, is an open-source implementation of Cisco AnyConnnect VPN protocol, which is widely used in businesses and universities. AnyConnect is an SSL-based VPN protocol that allows individual users to connect to a remote network.
Note: This tutorial also works on Ubuntu 20.10 and Ubuntu 21.04.
Why Set Up Your Own VPN Server?
- Maybe you are a VPN service provider or a system administrator, which behooves you to set up our own VPN server.
- You donāt trust the no-logging policy of VPN service providers, so you go the self-host route.
- You can use VPN to implement network security policy. For example, if you run your own email server, you can require users to log in only from the IP address of the VPN server by creating an IP address whitelist in the firewall. Thus, your email server is hardened to prevent hacking activities.
- Perhaps you are just curious to know how VPN server works.
Features of OpenConnect VPN Server
- Lightweight and fast. In my test, I can watch YouTube 4K videos with OpenConnect VPN. YouTube is blocked in my country (China).
- Runs on Linux and most BSD servers.
- Compatible with Cisco AnyConnect client
- There are OpenConnect client software for Linux, MacOS, Windows and OpenWRT. For Android and iOS, you can use the Cisco AnyConnect Client.
- Supports password authentication and certificate authentication
- Supports RADIUS accounting.
- Supports virtual hosting (multiple domains).
- Easy to set up
- Resistant to deep packet inspection (DPI)
I particularly like the fact that compared to other VPN technologies, it is very easy and convenient for the end-user to use OpenConnect VPN. Whenever I install a Linux distro on my computer and want to quickly unblock websites or hide my IP address, I install OpenConnect client and connect to the server with just two lines of commands:
sudo apt install openconnect
sudo openconnect -b vpn.mydomain.com
There is also OpenConnect VPN client for Fedora, RHEL, CentOS, Arch Linux and OpenSUSE. You can easily install it with your package manager.
sudo dnf install openconnect sudo yum install openconnect sudo pacman -S openconnect
Requirements
To follow this tutorial, you will need a VPS (Virtual Private Server) that can access blocked websites freely (Outside of your country or Internet filtering system). I recommend Kamatera VPS, which features:
- 30 days free trial.
- Starts at $4/month (1GB RAM)
- High-performance KVM-based VPS
- 9 data centers around the world, including United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.
Follow the tutorial linked below to create your Linux VPS server at Kamatera.
Once you have a VPS running Ubuntu 20.04, follow the instructions below.
You also need a domain name to enable HTTPS for OpenConnect VPN. I registered my domain name from NameCheap because the price is low and they give whois privacy protection free for life.
Step 1: Install OpenConnect VPN Server on Ubuntu 20.04
Log into your Ubuntu 20.04 server. Then use apt
to install the ocserv
package from the default Ubuntu repository.
sudo apt update sudo apt install ocserv
Once installed, the OpenConnect VPN server is automatically started. You can check its status with:
systemctl status ocserv
Sample output:
ā ocserv.service - OpenConnect SSL VPN server Loaded: loaded (/lib/systemd/system/ocserv.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-04-12 19:57:08 HKT; 12s ago Docs: man:ocserv(8) Main PID: 216409 (ocserv-main) Tasks: 2 (limit: 9451) Memory: 1.6M CGroup: /system.slice/ocserv.service āā216409 ocserv-main āā216429 ocserv-sm
Hint: If the above command doesnāt quit immediately, you can press the Q key to gain back control of the terminal.
If itās not running, then you can start it with:
sudo systemctl start ocserv
By default OpenConnect VPN server listens on TCP and UDP port 443. If itās being used by web server, then the VPN server would probably fail to start. We will see how to change the port in OpenConnect VPN configuration file later.
If thereās a firewall running on your server, then you will need to open port 80 and 443. For example, if you use UFW, then run the following command.
sudo ufw allow 80,443/tcp
Step 2: Install Letās Encrypt Client (Certbot) on Ubuntu 20.04 Server
The gnutls-bin
package installed along with ocserv
provides tools to create your own CA and server certificate, but we will obtain and install Letās Encrypt certificate. The advantage of using Letās Encrypt certificate is that itās free, easier to set up and trusted by VPN client software.
Run the following commands to install Letās Encrypt client (certbot) from the default Ubuntu repository.
sudo apt install certbot
To check the version number, run
certbot --version
Sample output:
certbot 0.40.0
Step 3: Obtain a Trusted TLS Certificate from Letās Encrypt
I recommend using the standalone
or webroot
plugin to obtain TLS certificate for ocserv.
Standalone Plugin
If thereās no web server running on your Ubuntu 20.04 server and you want OpenConnect VPN server to use port 443, then you can use the standalone plugin to obtain TLS certificate from Letās Encrypt. Run the following command. Donāt forget to set A record for your domain name.
sudo certbot certonly --standalone --preferred-challenges http --agree-tos --email [emailĀ protected] -d vpn.example.com
Where:
certonly
: Obtain a certificate but donāt install it.--standalone
: Use the standalone plugin to obtain a certificate--preferred-challenges http
: Perform http-01 challenge to validate our domain, which will use port 80.--agree-tos
: Agree to Letās Encrypt terms of service.--email
: Email address is used for account registration and recovery.-d
: Specify your domain name.
As you can see the from the following screenshot, I successfully obtained the certificate.
Using webroot Plugin
If your Ubuntu 20.04 server has a web server listening on port 80 and 443, then itās a good idea to use the webroot plugin to obtain a certificate because the webroot plugin works with pretty much every web server and we donāt need to install the certificate in the web server.
First, you need to create a virtual host for vpn.example.com.
Apache
If you are using Apache, then
sudo nano /etc/apache2/sites-available/vpn.example.com.conf
And paste the following lines into the file.
<VirtualHost *:80>
ServerName vpn.example.com
DocumentRoot /var/www/ocserv
</VirtualHost>
Save and close the file. Then create the web root directory.
sudo mkdir /var/www/ocserv
Set www-data (Apache user) as the owner of the web root.
sudo chown www-data:www-data /var/www/ocserv -R
Enable this virtual host.
sudo a2ensite vpn.example.com
Reload Apache for the changes to take effect.
sudo systemctl reload apache2
Once virtual host is created and enabled, run the following command to obtain Letās Encrypt certificate using webroot plugin.
sudo certbot certonly --webroot --agree-tos --email [emailĀ protected] -d vpn.example.com -w /var/www/ocserv
Nginx
If you are using Nginx, then
sudo nano /etc/nginx/conf.d/vpn.example.com.conf
Paste the following lines into the file.
server {
listen 80;
server_name vpn.example.com;
root /var/www/ocserv/;
location ~ /.well-known/acme-challenge {
allow all;
}
}
Save and close the file.Ā Then create the web root directory.
sudo mkdir -p /var/www/ocserv
Set www-data (Nginx user) as the owner of the web root.
sudo chown www-data:www-data /var/www/ocserv -R
Reload Nginx for the changes to take effect.
sudo systemctl reload nginx
Once virtual host is created and enabled, run the following command to obtain Letās Encrypt certificate using webroot plugin.
sudo certbot certonly --webroot --agree-tos --email [emailĀ protected] -d vpn.example.com -w /var/www/ocserv
Step 4: Edit OpenConnect VPN Server Configuration File
Edit ocserv main configuration file.
sudo nano /etc/ocserv/ocserv.conf
First, we need to configure password authentication. By default, password authentication through PAM (Pluggable Authentication Modules) is enabled, which allows you to use Ubuntu system accounts to login from VPN clients. This behavior can be disabled by commenting out the following line.
auth ="pam[gid-min=1000]"
If we want users to use separate VPN accounts instead of system accounts to login, we need to add the following line to enable password authentication with a password file.
auth ="plain[passwd=/etc/ocserv/ocpasswd]"
After finishing editing this config file, we will see how to use ocpasswd
tool to generate the /etc/ocserv/ocpasswd
file, which contains a list of usernames and encoded passwords.
Note: Ocserv supports client certificate authentication, but Letās Encrypt does not issue client certificate. You need to set up your own CA to issue client certificate.
Next, if you donāt want ocserv to use TCP and UDP port 443, then find the following two lines and change the port number. Otherwise leave them alone.
tcp-port = 443 udp-port = 443
Then find the following two lines. We need to change them.
server-cert = /etc/ssl/certs/ssl-cert-snakeoil.pem server-key = /etc/ssl/private/ssl-cert-snakeoil.key
Replace the default setting with the path of Letās Encrypt server certificate and server key file.
server-cert = /etc/letsencrypt/live/vpn.example.com/fullchain.pem server-key = /etc/letsencrypt/live/vpn.example.com/privkey.pem
Then, set the maximal number of clients. Default is 128. Set to zero for unlimited.
max-clients = 128
Set the number of devices a user is able to log in from at the same time. Default is 2. Set to zero for unlimited.
max-same-clients = 2
By default, keepalive packets are sent every 300 seconds (5 minutes). I prefer to use a short time (30 seconds) to reduce the chance of VPN connection dropout.
keepalive = 30
Next, find the following line. Change false
to true
to enable MTU discovery, which can optimize VPN performance.
try-mtu-discovery = false
You can set the time that a client is allowed to stay idle before being disconnected via the following two parameters. If you prefer the client to stay connected indefinitely, then comment out these two parameters.
idle-timeout=1200 mobile-idle-timeout=1800
After that, set the default domain to vpn.example.com.
default-domain = vpn.example.com
The IPv4 network configuration is as follows by default. This will cause problems because many home routers also set the IPv4 network range to 192.168.1.0/24
.
ipv4-network = 192.168.1.0 ipv4-netmask = 255.255.255.0
We can use another private IP address range (10.10.10.0/24) to avoid IP address collision, so change the value of ipv4-network
to
ipv4-network = 10.10.10.0
Now uncomment the following line to tunnel all DNS queries via the VPN.
tunnel-all-dns = true
The default DNS resolver addresses are as follows, which is fine.
dns = 8.8.8.8 dns = 1.1.1.1
Note: If you are a VPN service provider, then itās a good practice to run your own DNS resolver on the same server. If thereās a DNS resolver running on the same server, then specify the DNS as
dns = 10.10.10.1
10.10.10.1 is the IP address of OpenConnect VPN server in the VPN LAN. This will speed up DNS lookups a little bit for clients because the network latency between the VPN server and the DNS resolver is eliminated.
Then comment out all the route parameters (add # symbol at the beginning of the following lines), which will set the server as the default gateway for the clients.
#route = 10.0.0.0/8 #route = 172.16.0.0/12 #route = 192.168.0.0/16 #route = fd00::/8 #route = default #no-route = 192.168.5.0/255.255.255.0
Save and close the fileĀ Then restart the VPN server for the changes to take effect.
sudo systemctl restart ocserv
Step 5: Create VPN Accounts
Now use the ocpasswd tool to generate VPN accounts.
sudo ocpasswd -c /etc/ocserv/ocpasswd username
You will be asked to set a password for the user and the information will be saved to /etc/ocserv/ocpasswd
file. To reset password, simply run the above command again.
Step 6: Enable IP Forwarding
In order for the VPN server to route packets between VPN clients and the Internet, we need to enable IP forwarding by running the following command.
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/60-custom.conf
Then apply the changes with the below command. The -p option will load sysctl settings from /etc/sysctl.d/60-custom.conf file. This command will preserve our changes across system reboots.
sudo sysctl -p /etc/sysctl.d/60-custom.conf
Step 7: Configure IP Masquerading in Firewall
We need to set up IP masquerading in the server firewall, so that the server becomes a virtual router for VPN clients. I will use UFW, which is a front end to the iptables firewall. Install UFW on Ubuntu with:
sudo apt install ufw
First, you need to allow SSH traffic.
sudo ufw allow 22/tcp
Then find the name of your serverās main network interface.
ip addr
As you can see, itās namedĀ ens3
on my Ubuntu server.
To configure IP masquerading, we have to add iptables command in a UFW configuration file.
sudo nano /etc/ufw/before.rules
By default, there are some rules for the filter
table. Add the following lines at the end of this file. Replace ens3
with your own network interface name.
# NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.10.10.0/24 -o ens3 -j MASQUERADE
# End each table with the 'COMMIT' line or these rules won't be processed
COMMIT
In Nano text editor, you can go to the end of the file by pressing Ctrl+W
, then pressing Ctrl+V
.
The above lines will append (-A) a rule to the end of of POSTROUTING chain of nat table. It will link your virtual private network with the Internet. And also hide your network from the outside world. So the Internet can only see your VPN serverās IP, but canāt see your VPN clientās IP, just like your home router hides your private home network.
By default, UFW forbids packet forwarding. We can allow forwarding for our private network. Find the ufw-before-forward
chain in this file and add the following 3 lines, which will accept packet forwarding if the source IP or destination IP is in the 10.10.10.0/24
range.
# allow forwarding for trusted network -A ufw-before-forward -s 10.10.10.0/24 -j ACCEPT -A ufw-before-forward -d 10.10.10.0/24 -j ACCEPT
Save and close the file. Then enable UFW.
sudo ufw enable
If you have enabled UFW before, then you can use systemctl to restart UFW.
sudo systemctl restart ufw
Now if you list the rules in the POSTROUTING chain of the NAT table by using the following command:
sudo iptables -t nat -L POSTROUTING
You can see the Masquerade rule.
It can take some time for UFW to process the firewall rules. If the masquerade rule doesnāt show up, then restart UFW again (sudo systemctl restart ufw
).
Step 8: Open Port 443 in Firewall
Run the following command to open TCP and UDP port 443. If you configured a different port for ocserv, then change 443 to your configured port.
sudo ufw allow 443/tcp sudo ufw allow 443/udp
Now OpenConnect VPN server is ready to accept client connections.
If you run a local DNS Resolver
For those of you who run a local DNS resolver, if you specified 10.10.10.1 as the DNS server for VPN clients, then you must allow VPN clients to connect to port 53 with the following UFW rule.
sudo ufw insert 1 allow in from 10.10.10.0/24
You also need to edit the BIND DNS serverās configuration file (/etc/bind/named.conf.options
) to allow VPN clients to send recursive DNS queries like below.
allow-recursion { 127.0.0.1; 10.10.10.0/24; };
Then restart BIND.
sudo systemctl restart named
How to Install and Use OpenConnect VPN client on Ubuntu 20.04 Desktop
Run the following command to install OpenConnect VPN command line client on Ubuntu desktop.
sudo apt install openconnect
You can Connect to VPN from the command line like below. -b
flag will make it run in the background after connection is established.
sudo openconnect -b vpn.example.com:port-number
You will be asked to enter VPN username and password. If the connection is successfully established, you will see the following message.
Got CONNECT response: HTTP/1.1 200 CONNECTED CSTP connected. DPD 90, Keepalive 32400 Connected tun0 as 192.168.1.139, using SSL Established DTLS connection (using GnuTLS). Ciphersuite (DTLS1.2)-(RSA)-(AES-256-GCM).
To stop the connection, run:
sudo pkill openconnect
To run the client non-interactively, use the following syntax.
echo -n password | sudo openconnect -b vpn.example.com -u username --passwd-on-stdin
If you want to use Network Manager to manage VPN connection, then you also need to install these packages.
sudo apt install network-manager-openconnect network-manager-openconnect-gnome
If you are successfully connected to the VPN server, but your public IP address doesnāt change, thatās because IP forwarding or IP masquerading is not working. I once had a typo in my iptables command (using a wrong IP address range), which caused my computer not being able to browse the Internet.
If you encounter the following error, then you should disable the UDP port in ocserv, which is explained later in the speed optimization section.
DTLS handshake failed: Resource temporarily unavailable, try again
If you have the following error, itās likely that your VPN username or password is wrong.
fgets (stdin): Inappropriate ioctl for device
Auto-Connect on System Startup
To let OpenConnect VPN client automatically connect to the server at boot time, we can create a systemd service unit.
sudo nano /etc/systemd/system/openconnect.service
Put the following lines to the file. Replace the red text.
[Unit] Description=OpenConnect VPN Client After=network-online.target systemd-resolved.service Wants=network-online.target [Service] Type=simple ExecStart=/bin/bash -c '/bin/echo -n password | /usr/sbin/openconnect vpn.example.com -u username --passwd-on-stdin' KillSignal=SIGINT Restart=always RestartSec=2 [Install] WantedBy=multi-user.target
Save and close the file. Then enable this service so that it will start at boot time.
sudo systemctl enable openconnect.service
Explanation of the file content:
After=network-online.target systemd-resolved.service
andWants=network-online.target
make this service run after network is up. We want theopenconnect.service
start after thesystemd-resolved.service
because that will ensure the DNS server address set by OpenConnect wonāt be overridden bysystemd-resolved.service
.- In reality, this service can still run before network is up. We add
Restart=always
andRestartSec=2
to restart this service after 2 seconds if this service fails. - Systemd doesnāt recognise pipe redirection, so in the
ExecStart
directive, we wrap the comand in single quotes and run it with the Bash shell. - Since OpenConnect VPN client will run as a systemd service, which runs in the background, thereās no need to add
-b
flag to theopenconnect
command. - The
KillSignal
directive tells Systemd to send theSIGINT
signal when thesystemctl stop openconnect
command is issued. This will performs a clean shutdown by logging the session off, and restoring DNS server settings and the Linux kernel routing table.
To start this Systemd service immediately, run
sudo systemctl start openconnect
To stop this Systemd service, run
sudo systemctl stop openconnect
How to Automatically Restart OpenConnect Client When Resuming from Suspend
If your Ubuntu desktop goes into suspend state, the OpenConnect client would lose connection to the VPN server. To make it automatically restart when resuming from suspend, we need to create another systemd service unit.
sudo nano /etc/systemd/system/openconnect-restart.service
Add the following lines in the file.
[Unit] Description=Restart OpenConnect client when resuming from suspend After=suspend.target [Service] Type=simple ExecStart=/bin/systemctl --no-block restart openconnect.service [Install] WantedBy=suspend.target
Save and close the file. Then enable this service.
sudo systemctl enable openconnect-restart.service
Automatic-Restart When VPN Connection Drops
Sometimes the VPN connection would drop due to other reasons. You can run the following command to check if the VPN client can ping the VPN serverās private IP address (10.10.10.1). If the ping is unsuccessful, then the command on the right will be executed to restart the VPN client. ||
is the OR operator in Bash. It executes the command on the right only if the command on the left returned an error.
ping -c9 10.10.10.1 || systemctl restart openconnect
The ping will be done 9 times, i.e 9 seconds. You can use an infinite loop in the Bash shell to make the whole command run forever. Press Ctrl+C
to stop it.
for ((; ; )) do (ping -c9 10.10.10.1 || systemctl restart openconnect) done
Now we can create a systemd service for this task.
sudo nano /etc/systemd/system/openconnect-check.service
Add the following lines to this file. We specify that this service should run after the openconnect.service
.
[Unit] Description=OpenConnect VPN Connectivity Checker After=openconnect.service [Service] Type=simple ExecStart=/bin/bash -c 'for ((; ; )) do (ping -c9 10.10.10.1 || systemctl restart openconnect) done' [Install] WantedBy=multi-user.target
Save and close the file. Then start this service.
sudo systemctl start openconnect-check
Enable auto-start at boot time.
sudo systemctl enable openconnect-check
Once this service is started, the ping command will run forever. If the VPN connection drops, it will automatically restart openconnect.service
.
OpenConnect GUI Client for Windows and macOS
They can be downloaded from OpenConnect GUI Github Page.
Speed
OpenConnect VPN is pretty fast. I can use it to watch 4k videos on YouTube. As you can see, my connection speed is 63356 Kbps, which translates to 61 Mbit/s.
And hereās the test results on speedtest.net.
Speed Optimization
OpenConnect by default uses TLS over UDP protocol (DTLS) to achieve faster speed, but UDP canāt provide reliable transmission. TCP is slower than UDP but can provide reliable transmission. One optimization tip I can give you is to disable DTLS, use standard TLS (over TCP), then enable TCP BBR to boost TCP speed.
To disable DTLS, comment out (add #
symbol at the beginning) the following line in ocserv configuration file.
udp-port = 443
Save and close the file. Then restart ocserv service.
sudo systemctl restart ocserv.service
To enable TCP BBR, please check out the following tutorial. Note that you need to disable DTLS in ocserv, or TCP BBR wonāt work.
In my test, standard TLS with TCP BBR enabled is two times faster than DTLS.
Another very important factor affecting speed is how good the connection between your local computer and the VPN server is. If you live in the middle east and the VPN server is located in the U.S, the speed would be slow. Choose a data center thatās close to where you live.
Also, check your CPU load average. (htop
can be installed by sudo apt install htop
).
htop
Make sure the CPU load average is under 1
. I once had a CPU load average of 3
, which caused a high latency between the VPN client and VPN server.
Auto-Renew Letās Encrypt Certificate
Edit root userās crontab file.
sudo crontab -e
Add the following line at the end of the file. Itās necessary to reload ocserv service for the VPN server to pick up new certificate and key file.
@daily certbot renew --quiet && systemctl reload ocserv
Troubleshooting Tips
OpenVZ
Note that if you are using OpenVZ VPS, make sure you enable the TUN virtual networking device in VPS control panel. (If you use Vultr VPS, then you have KVM-based VPS, so you donāt have to worry about this.)
Log File
If you encounter any problem, then check OpenConnect VPN server log.
sudo journalctl -eu ocserv.service
I found that if I change port 443 to a different port, the great firewall of China will block this VPN connection.
Debugging Mode
If ocserv tells you that it canāt load the /etc/ocserv/ocserv.conf
file, you can stop ocserv.
sudo systemctl stop ocserv
Then run it in the foreground with debugging enabled.
sudo /usr/sbin/ocserv --foreground --pid-file /run/ocserv.pid --config /etc/ocserv/ocserv.conf --debug=10
Then output might give you some clues why ocserv isnāt working.
Canāt browse the Internet
If you are successfully connected to the VPN server, but you canāt browse the Internet, thatās because IP forwarding or IP masquerading is not working. I remember my VPS provider once did a platform upgrade, which changed the name of the main network interface from ens3
to enp3s0
, so I had to update the name in the UFW file (/etc/ufw/before.rules
).
Syntax Error
If you see the following error when trying to establish VPN connection, itās probably because thereās a syntax error in your ocserv config file. Check the journal (sudo journalctl -eu ocserv
) to find out.
Got inappropriate HTTP CONNECT response: HTTP/1.1 401 Cookie is not acceptable
Restart Your Computer
If you see the following error when trying to establish VPN connection, itās likely a local computer problem. Try restarting your computer.
Server 'vpn.your-domain.com' requested Basic authentication which is disabled by default
TLS connection was non-properly terminated
If you see the following error on the client when trying to establish a VPN connection,
SSL connection failure: The TLS connection was non-properly terminated.
you probably should restart the ocserv
service on the VPN server.
sudo systemctl restart ocserv
You can create a cron job to automatically restart ocserv
once per day at 4 AM.
sudo crontab -e
Add the following line.
0 4 * * * systemctl restart ocserv
Save and close the file.
How to Install the Latest Version of ocserv
Check your current ocserv
version.
ocserv -v
Sometimes, the latest version of ocserv
will fix an issue. You may also want to use a new feature thatās only available in the latest release. Follow the instructions below to install the latest ocserv
version.
Install build dependency packages.
sudo apt install -y git ruby-ronn libbsd-dev libsystemd-dev libpcl-dev libwrap0-dev libgnutls28-dev libev-dev libpam0g-dev liblz4-dev libseccomp-dev libreadline-dev libnl-route-3-dev libkrb5-dev libradcli-dev libcurl4-gnutls-dev libcjose-dev libjansson-dev libprotobuf-c-dev libtalloc-dev libhttp-parser-dev protobuf-c-compiler gperf nuttcp lcov libuid-wrapper libpam-wrapper libnss-wrapper libsocket-wrapper gss-ntlmssp haproxy iputils-ping freeradius gawk gnutls-bin iproute2 yajl-tools tcpdump
Clone the ocserv Git repository.
git clone https://gitlab.com/openconnect/ocserv.git
Generate configuration scripts.
cd ocserv autoreconf -fvi
Compile the source code. If you see deprecated warnings, you can ignore them.
./configure && make
Install the binaries.
sudo make install
The files will be install to /usr/loca/bin/
and /usr/local/sbin/
. Next, we need to copy the systemd service file.
sudo cp /lib/systemd/system/ocserv.service /etc/systemd/system/ocserv.service
Edit this file.
sudo nano /etc/systemd/system/ocserv.service
Because the compiled version of ocserv binary is located at /usr/local/sbin/ocserv
, we need to change
ExecStart=/usr/sbin/ocserv --foreground --pid-file /run/ocserv.pid --config /etc/ocserv/ocserv.conf
to
ExecStart=/usr/local/sbin/ocserv --foreground --pid-file /run/ocserv.pid --config /etc/ocserv/ocserv.conf
Save and close the file. Then reload systemd.
sudo systemctl daemon-reload
Restart ocserv service.
sudo systemctl restart ocserv
Make OpenConnect VPN server and web server use port 443 at the same time
Please read the following article:
More Useful Tips
Wrapping Up
Thatās it! I hope this tutorial helped you install and configure OpenConnect VPN on Ubuntu 20.04. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks š
Everyone, Pls use English instead of Chinese to avoid this site to be blocked by GFW~!!!!!!
Hi, I have successfully connected but got the error message as below:
How to fix this problem? please help!!
Try disabling UDP/DTLS in ocserv. To disable DTLS, comment out (add # symbol at the beginning) the following line in ocserv configuration file.
Save and close the file. Then restart ocserv service.
To enable TCP BBR, please check out the following tutorial. Note that you need to disable DTLS in ocserv, or TCP BBR wonāt work.
How to Easily boost Ubuntu Network Performance by enabling TCP BBR
In my test, standard TLS with TCP BBR enabled is faster than DTLS.
Xiao Guoan
Hello
My problem is that after connecting to OpenConnect the speed is lost or does not exceed 0.78mb. How to fix the problem
OpenConnect VPN protocol itself is very fast. However, there are other factors that can impact speed, such as the network condition between the VPN client and the VPN server. Always choose a server close to the client as the VPN server.
You can enable the TCP BBR algorithm to speed up TCP connection speed.
The user is constantly banned, for example, between the transition from 3g to a wi fi network.
Can you help me find a solution?
I have never been banned. Maybe
sudo journalctl -eu ocserv
will give you some clues.hello,
did you faced an error like:
main.c:868: bind UDP to [::]:443: Invalid argument
⦠Network is unreachable
client works fine and can access internet but still see this errors in my logs š
it seems issue was with udp-port, tried to comment it in config file.
Hi Marat,
Would you please give more information of how your issue was resolved?
I have the same issue but I donāt know how to fix it?
https://askubuntu.com/questions/1325690/ufw-block-error-seen-in-journalctl-xe-command
Thanks
Hi Mostafa,
To be honest, I donāt remember, try to comment related line in config file š
Hello Xiao!
Great tutorial!
I have a question. If I have the nginx running in parallel with the vpn and use the haproxy as you explained in the linked tutorial is there a way to make a site from nginx available only to the vpn? What would be needed in the haproxy, nginx and vpn configuration?
From a newbie perspective I expect something like an client IP forward through haproxy to nginx where nginx decides to deny/accept the connection. And the vpn needs to do something like a split tunnel. But I need to search some more documentation for all of these.
Any terms that would be helpful in this when I look into the manuals?
Many thanks!
Ok, after working some days on this issue this is what I did. Let me know if there are other things that need to be taken care of besides what I did here.
I first did the in the /etc/sysctl.conf file
In /etc/haproxy/haproxy.cfg
I added the
to bind the vpn internal ip to the frontend
In the nginx backaned I added server
I created the rpz dns resolver and added in it all the dns entries from the sites that I wanted to be in the āintranetā as stated in this tutorial (/etc/bind/db.rpz.local):
https://corejumping.com/muzehiki/ubuntu/set-up-response-policy-zone-rpz-in-bind-resolver-on-debian-ubuntu
In nginx I added the proxy_protocol directive to the listen ssl directive, this is required to get the real ip from haproxy (that is why I modified that configuration file as well):
And to allow and deny ip connections the known lines:
If you allow access to all your Nginx virtual hosts to VPN clients only, you can simply make Nginx listen on the VPN interface,
Check the
/etc/nginx/nginx.conf
file and the default Nginx virtual host to see the there arelisten 443 ssl
directives, change them tolisten 10.10.10.1:443 ssl
. So your Nginx virtual host wonāt accept connections from the public Internet. Then use RPZ to make an āintranetā DNS record for the domain.You donāt need to change the HAProxy configurations or add
allow
,deny
directives in Nginx.Yeah!
Youāre right. That is simpler than the way I did it. š
Hello, how can I know exactly if my client is connected to my ocserv?
And see it online.
Tell me the commands
sudo occtl show users
Help please view the client connection history in ocserv through specific commands
Run
occtl help
to see how to use it.Thank you so much.
Please tell me how you can make sure AnyConnect does not turn off on mobile.
Thereās no way to make sure a VPN connection or any TCP connection doesnāt drop.
Great tutorial. Thanks!
Ubuntu 20.10 gives below error , When i checked the file is present there.
error connecting to sec-mod socket ā/run/ocserv.socket.83a664e5ā: No such file or directory
If you look carefully at the log, it said it canāt find the socket, and next, it initialized this socket. So problem solved, right? š
how to fix the: transmitted packet is too large (emsgsize) ?
Hi,
You said to edit /etc/bind/named.conf.options to allow VPN clients to send recursive DNS queries
I didnāt find this file on my server, what should I do exactly?
thanks for your article
If you donāt run a local DNS resolver on the VPN server, then you donāt have this file and you donāt need to edit it.
So everything is running fine with IPv4. When enabling ipv6 on the dns. After I add
allow-recursion { 127.0.0.1; 10.10.10.0/24; fda9:4efe:7e3b:03ea::/48; };
The DNS for the IPv6 and the IPv4 stop working.
If I remove fda9:4efe:7e3b:03ea::/48; from the bind9 config the ipv4 dns will start working again. any ideas?
Hi, Iāve used this guide a few times for ipv4 successfully, but just now found that the ipv6 section seems to be incomplete. In the āSet Up IPv6 in Firewall (Debian, Ubuntu)ā section of your other guide here https://corejumping.com/muzehiki/linux-server/ocserv-vpn-server-apache-nginx-haproxy and there is the additional step of adding the two
, which is missing from this guide. Once I added those lines, ipv6 forwarding works properly.
Thanks for pointing it out. I just added the missing step to this article.
First of all, thank you very much for this valuable article and your beautiful expression. I did everything successfully. However, there is one point that I do not understand or cannot do. Cisco AnyConnect uses TLS 1.2 for some reason. Canāt we force this to use TLS 1.3? All packages on my system have the latest version. Looking forward to your valuable feedback. Good work.
Cisco Annyconnect client has some problems when using TLS 1.3. You can force the server to use TLS 1.3, but if the client has a compatibility problem, the VPN would stop working.
Thank you for your valuable reply. Thank you for your valuable reply. OpenConnectās own client also uses the TLS 1.2 protocol. Either there is a different situation in these applications or I am doing something wrong. I want to understand the issue better. How can I force the system to use TLS 1.3? Even though I edit this on Apache, it doesnāt work. It persistently uses TLS 1.2. By the way, Iām running with TCP only, DTLS is turned off. I wonder if TLS over TCP currently only supports TLS 1.2? What is your opinion on this? Iām curious about your comments.
TLS1.3 will be disabled when cisco client compatibility is enabled. See here: ocserv changelog
I do exactly as told.
when I ran iptables -t nat -L POSTROUTING
The response is :
Why did this happen?
Does this matter?
Itās correct. I forgot to update the screenshot
Another Question.
I deployed Open Connect on Ubuntu 20.04 VPS step by step as you showed in this article.
I can use it on iOS devices smoothly.
But It is very slow on Windows 10.
I tried Cisco Anyconnect and OpenConnect-GUI, It is to slow to use. I can connect to the server, everything seems ok. No error happens. But It just toooooooooo slow.
The most important factor affecting speed is how good is the connection between your local computer and the VPN server. If you live in the middle east and the VPN server is located in the U.S, the speed would be slow. Choose a data center thatās close to where you live.
One great way to improve the speed of OpenConnect VPN is disabling UDP port 443 in ocserv and enabling TCP BBR algorithm in the Linux kernel, as I have already said in the āspeed optimizationā section in this article.
The OpenConnect VPN protocol is not slow in its own right. If you really think itās slow, you might want to try the WireGuard VPN protocol, which is the fastest VPN protocol.
If your speed is still slow when using WireGuard VPN, you should change data center location. Some VPS hosting providers allow you to easily migrate from one data center to another.
The advantage of OpenConnect VPN is that itās a HTTPS-based VPN and operates on TCP port 443, so its super hard to block it by a national firewall. WireGuard VPN can be easily identified and blocked. You can see the OpenConnect VPN speed tested on my Windows computer.
My Windows 10 PC and iOS devices use the same Wi-Fi. Also, Latest Cisco official Anyconnect client app installed on Windows 10 PC and iOS devices.
Connection speed on iOS devices is much much much much much faster than Windowsā.
I do not know why and how to fix.
Thank U.
I enabled BBR on my VPS.
Itās much faster now.
čæč”systemctl status ocservēę¶åļ¼ę示俔ęÆäøęēŗ¢č²ēäøč”
Jul 04 01:17:40 vultr.guest ocserv[11868]: error connecting to sec-mod socket ā/run/ocserv.socket.efb2f1d4ā: No such file or directory
čæäøŖę示ļ¼ä½č²ä¼¼äøå½±å使ēØć
ä½OpenConnectäøē“äøč¬ äøē„éęÆäøęÆåčæäøŖēå½±å
åé¢čæęäøč”.
čæäøŖč”Øē¤ŗ ocserv å¼å§ę¾äøå°čæäøŖ socket ęä»¶ļ¼ ę仄å®å°±č¦åå§åčæäøŖ socket ęä»¶.
čæęÆę£åøøē. č¦å½±åēčÆ, ęę客ę·ē«Æé½ä¼åå°å½±å.
č²ä¼¼äøå½±å使ēØļ¼ä½ęÆOpenConnectēéåŗ¦äøē“äøč¬ļ¼äøē„éęÆäøęÆåčæäøŖå½±å
å ¶å®é对äŗę°ę®äøåæļ¼ä»„åå å°ē宽带čæč„åļ¼éåŗ¦äøä¼å¾ę ¢ć
ęēØäøå½ē§»åØē100M宽带čæę°å å”ēVPNļ¼äøč½½éåŗ¦åÆä»„č¾¾å° 72Mbit/s, äøä¼ éåŗ¦åÆč¾¾ 69 Mbit/sć
å¦å¤ęåē°ļ¼1å·č³6å·ē½å¤©ļ¼ę°ę建ēOpenConnectęå”åØļ¼ęå¼éčæå ꬔåļ¼å°±åä¹čæäøäøäŗć
ä»ä»å¤©å¼å§ļ¼å°±äøä¼ęčæē§ē°č±”ćäøē„éęÆäøęÆå äøŗē¹å¾å¤Ŗęę¾č¢«å¼ŗäŗć
ęå ä¹ęęę¶é“é½ęÆēØOpenConnectļ¼ å¹¶ę²”ęčæē§ę åµćę认为ęÆę°ę®äøåæēé®é¢ć ęäŗę°ę®äøåæä¼åå°éē¹å ³ę³Øć
ęēØ nDPI 深度ę£ęµå å·„å ·ęµčÆčæļ¼OpenConnect åŖä¼č¢«ę£ęµäøŗ TLS čæę„ļ¼å¹¶äøč½ę£ęµå° VPN åč®®ć
仄åēØčæikev2ē梯åļ¼éåŗ¦ć客ę·ē«ÆęÆęé½é常儽ļ¼åÆ¹ē§»åØč®¾å¤ä¹ę ¼å¤å儽ļ¼čŖåØä¼ē ćęå¼éčæä¹å„½ļ¼čēµä¹éåøøå°ćęå”端儽å使ēØstrongswanę建ēć
äøē„éęØåƹčæäøŖęÆå¦ē ē©¶ļ¼åÆå¦åäøēÆęēØļ¼é ē¦å¢å ēęå们ć
äøę³č¢«åč¶ć
Hello and thank you for the amazing tutorials. Iām having an issue with the IP masquerading. I can connect to my VPN, no problem. Everything checks out āokā as far as I can tell. My IP does not become the IP of the VPN server. It stays the same.
When I run sudo iptables -t nat -L POSTROUTING, I get the same results as written in the tutorial. Any way you can help me figure this out? Thank you!
Hello again, I figured it out. I had some errors in the config files. I missed the commenting out of the routing parameters.
You are so thorough and clear with your directions. I think we all love you LinuxBabe. You rock. Thank you again =)
Hay Xiao
Thank you for this awesome and detailed tutorial
I build an OpenConnect server using your instruction. It works well except for a site that I have on the very same VPS.
I can access my site only through VPN in my country, but it seems that when OpenConnect VPN and site are on the same server, VPN neglects the site.
Could you please help me with this?
You can create a special DNS record for your VPN users with Response Policy Zone, pointing the site domain to the 10.10.10.1 IP address, so when VPN users visit your site, their traffic will be tunnelled through the VPN. You also need to make the site listen on the 10.10.10.1 interface for both port 80 and 443.
ęØēęēØļ¼é常详尽ļ¼éåøøęč°¢ćęē §ęØēęēØļ¼éØē½²äŗęå”åØļ¼ēØčµ·ę„äøåę£åøøļ¼éåŗ¦ä¹å¾åæ«ć
ä½ęäøäøŖē°č±”ļ¼ęÆę¬”ęäøåØiOS设å¤äøčæēVPNå „ē”ļ¼å±å¹åøøéļ¼č½Æä»¶åå°čæč”ļ¼ä½éę„ę¶Anyconnectäøå®ä¼ęå¼ļ¼éčæä¹č½čæäøćę 论使ēØWiFičæęÆ5Gļ¼é½ä¼ęå¼ć
Windows10äøä½æēØOpenConnectļ¼å“č½å¤éæę¶é“äæęčæę„ļ¼ę„ēę„åæļ¼ä¹ęŖę„å°ęēŗæčŖåØéčæēēčæ¹ćę仄似ä¹äøęÆå äøŗGFWēå¹²ę°ļ¼
é£ä¹ļ¼ęęØęä»ä¹ę¹ę³ļ¼č®©ęęŗäøęēŗæēęŗēåå°äøē¹å¢
ęØęē« éęå°äŗäøäøŖåę°ļ¼ä½ä¼¼ä¹ęęå¹¶äøå„½ć
Amazing article, thank you!
Error found: openconnect-restart script
Line āExecStart=/bin/systemctl āno-block restart ocnyc.serviceā should be āExecStart=/bin/systemctl āno-block restart openconnect.serviceā
And it is better to add ādeploy-hook = systemctl restart ocservā into /etc/letsencrypt/cli.ini to reload ocserv after certbot certificate renewal for Ubuntu >= 18.04
Is it really necessary to have a VPS? Canāt I use my home server for this?
I checked on VPS Vultr and the cheapest is $6/month =$72 per yearā¦.
NordVPN is $50/year for meā¦.which nullifies the purpose of wanting to reduce costs
If you want to use VPN for privacy, you canāt use your home server, because when you are at your home, thereās no point in connecting to a VPN server hosted at home. Your IP address wonāt change. And when you are not at your home, connecting to a VPN server hosted at home will always let the websites know your home IP address, which can be easily used to track you personally.
Yes, the starting price at Vultr has increased. You can use Kamatera VPS, which starts at $4/month ($48/year)
It says $5 is the lowest for Kamatera. What about https://www.hostinger.com/vps-hosting ?
I donāt know where you find the $5/month pricing. On my computer, the Kamatera web page says $4/month and I have a VPS at Kamatera that costs $4 per month.
Hostinger starts at $3.95 per month, but it uses OVZ (OpenVZ) for the virtualization of VPS, which is much slower in performance and you canāt install your own Linux kernel. I would never use OpenVZ-based VPS. Always choose KVM or Xen-based VPS.
éåøøęč°¢ä½ čÆ¦ē»ēęēØćęč·éęēØé 置儽åļ¼č½čæäøVPNļ¼ ä½ä»ē¶ę¾ē¤ŗēęÆęčŖå·±ēIPćęč§å¾é®é¢ä¼¼ä¹åØIP-forwarding äøćsystemctl restart ufw åŗē°äøé¢ēé误ć
sudo iptables -t nat -L POSTROUTING ä¹ę²”ęč§ååŗē°ćéäøufw č§åęä»¶ćč½éŗ»ē¦ä½ åø®ęēäøäøåļ¼åäøę¬”éåøøęč°¢ļ¼
ęå»ęäŗåé¢äøäøŖCOMMITļ¼ååŗē°čæäøŖé误ć
äøå„½ęęļ¼ufw ē°åØčµ·ę„äŗļ¼iptablesč§åä¹åŗē°äŗļ¼ä½čæęÆę¾ē¤ŗčŖå·±ēIPć
sysctl -p ä¹ę§č”äŗ
ēę³äøåŗčæåŗčÆ„ēåŖåæäŗļ¼
ęä½ ē
/etc/ufw/before.rules
仄å/etc/ocserv/ocserv.conf
ęä»¶åē»ęēäøäøćHi,
Is there any option so that we can have a web panel for this open connect server? I mean, we can add/delete/edit/manipulate the users via this web panel.
Hi Xiao Guoan, Iām very sorry about missing your prompt reply. Iāve managed to make ocserv work for me, though Iām still not sure where went wrong, and how exactly I got it to work.
If you donāt mind, I have another question. Is it possible to use haproxy on 443 to route ssh request to the service which listens to port 222? I used to have a working setup but now I forgot how to do itā¦
Thanks again for your time!
You are using the 192.168.86.0/24 network in
/etc/ocserv/ocserv.conf
file, but you use 10.10.10.0/24 network in/etc/ufw/before.rules
file?Hi Xiao Guoan, yes I think that might be the very reason it didnāt work at first. The network in
before.rules
is correctly configured now, so itās working!Just wondering if you had a chance to look into my additional question about routing ssh requests through haproxy on 443 port?
Again this blog is awesome, your efforts put into it are very much appreciated!
If you donāt want your SSH traffic to be monitored, use the following command for SSH.
or
Your SSH traffic will be encrypted by the VPN tunnel and it looks like HTTPS traffic to others.
I donāt think you can proxy SSH traffic with HAProxy and even if you can, it will be detected as SSH traffic.
Hi Xiao Guoan, thanks again:)
Hello. Thank you for such a good and useful article! What a great job has been done. Excellent. But I still had difficulties. I did everything according to the instructions. But the devices do not connect to the vpn server. Errors are displayed in the log, but I donāt understand what they say at all. Help please. Thanks!
大佬,
I just get through all the procedures on local server as a test . seems OK. thanks a lot for the detailed informative sharing. learned a lot.
Just tried Kamatera , but seems cannot receive the phone verification code from the website to äøå½čé . Donāt know if you encounter the same problem before.
In China , I just got a domain name. but seems only after å¤ę”, can be fully functioning. even though in domestic it is DNSed already . but when I tried to get the CA from Letās certificate , failed for reasons of firewall ( I guess the domain name already occupied by Ali, but still not yet propagate the my IP to the outside china DNS servers) . How do you think the reason?
thanks again for this tutorial and others
I have a China Mobile (äøå½ē§»åØ) phone number, and I can receive the verification code from Kamatera.
Go to https://dnsmap.io to check your DNS record propagation status.
Never used Aliyun before.
Thank you for your reply
I tried the dnsmap.io . also ipdonation.net all can get the correct IP of my new domain.
I just tried to get the CA . but still failed on the stage āhttp-01 challengeā , like below:
++++++++
Performing the following challenges:
http-01 challenge for my.domain.xyz
Waiting for verificationā¦
Challenge failed for domain my.domain.xyz
+++++++
When free, pls give some hint . thanks a lot
I sort of figured out the source of problem ā¦
seems the firewall configuration imposed by the Ali cloud on the workstation.
Let me try to find a way out ā¦
thanks again
大佬
this is the message from my PC , VPNed through Ali , mentored by you.
thank you for this tutorial .
learned a lot
My mentioned problems originate from ignorance of network and typo .
your guide is superb!
now connected with the ocserv server . cheers and thanks
but still two problems:
1. the default gateway for the client end is set to itself , so, there would be no internet for client.
2. when I ctrl+c , stop the openconnenct client, the client PCās route table is not recovered to the original. actually the route table is empty.
========= here below is my part in the configuration file.
ā-below is the message from ocserv to the client terminal:
When you are free , PLS help give some hint š
Correct config should be
Hi Admin,
Your tutorial is great.
I did everything and now both from Ubuntu Laptop and Android mobile I can connect to the VPN network without showing any error.
But the problem is, when check *What is my IP* in the browser, it is showing the old ISP IP itself instead of the ocserv server IP.
Any idea how to solve this?
Myself found the solution. It was actually due to my misunderstanding.
I thought the commenting of route is a part of the DNS resolver running on the same server which I donāt had.
Issue solved after commenting all routes..
Hello, is it possible for oscerv to connect to one domain with TLS Certificate from Letās Encrypt two (2) or (3) vps/vds servers and use eitherā¦
Yes, simply create multiple DNS A records for the same hostname.
When a hostname has multiple A records, the VPN client will choose one of the A records randomly.
You need to make sure all VPN servers has the same TLS certificate.
hello tutorial is very good. i have two issues here:
1: when i connect with any connect i can not stablish ssh connection to the server it self ?
2: i want to use split-tunneling here and i add no-route lines(1580 lines) to .conf file but in client side it is not effecting and my whole traffic is tunneling. in status i have got messages for excluding routes but in client side its not working.. so what can i do ?
1. VPN connection doesnāt affect SSH connection. You can SSH using the public IP address or the private VPN address.
2. Split tunneling in ocserv accepts at most 200 no-route/route lines.
I appreciate the quick response & ssh worked on private ip address.
hello. i installed service thats awesome , so i want to ask username & password in one page , how should we do it ? can you help me ? thanks
use the ocpasswd tool to generate VPN accounts.
What do you mean by āusername & password in one pageā?
when client is going to connect first prompt for entering username and then prompt for password and its two times prompt. but i see any connect vpn that asks for username and password same time in just one prompt. like picture that i attached
Thatās done in the client software. If you use the OpenConnect GUI client, you can ask the software author to change this, but I really think itās not an issue for most people.
no thats totally server side configuration but i cant find right one. so no that is not issue. thanks
Hello, can I control the system ocserv on ubuntu, specifically I need to account for user traffic, I would like to know how much was downloaded by specific users, what exactly, and visit https.
Thanks in advance
Hello, can I control the system ocserv on ubuntu, specifically I need to account for user traffic, I would like to know how much was downloaded by specific users, what exactly, and visit https.
Thanks in advance
I was also getting the error Server āvpn.your-domain.comā requested Basic authentication which is disabled by default and it took me a while to figure out that āocpasswd -c /etc/ocserv/ocpasswd usernameā has been changed to āocpasswd -c /etc/ocserv/passwd usernameā on the default installation.