Back to blogSecurity & Privacy

How to Create and Host Your Own Free OpenVPN Server

8 min read
How to Create and Host Your Own Free OpenVPN Server
Publicidade

Creating your own VPN server using OpenVPN provides enhanced privacy, security, and control over your internet connection.

Publicidade
Wi-Fi router transmitting stable and fast internet signal.

Why Hosting Your Own Private VPN Server is the Ultimate Privacy Solution

DomineTec Tip: Running your own VPN secures your connection but uses your own server IP. If you want rotating anonymous IPs, read our guide on best verified no-logs VPNs.

With the increasing concerns about online surveillance and data privacy, hosting your own VPN server has become a reliable solution for users seeking to secure their internet traffic. A Virtual Private Network (VPN) encrypts your internet connection, making it difficult for third parties to monitor your online activities. By creating your own OpenVPN server, you gain complete control over your data, avoiding reliance on third-party VPN services that may log your activity or sell your information. This guide provides a comprehensive overview of how to set up and host your own OpenVPN server on a Linux VPS, specifically using Ubuntu or Debian.

Digital padlock representing internet network security and privacy.

Step 1: Setting Up Your Hosting Environment (Free-Tier VPS or Local Linux PC)

Server Deployment Step Linux Shell Command Resulting Action
Install Packages sudo apt install openvpn easy-rsa -y Downloads the VPN server binaries
Enable Routing sysctl -w net.ipv4.ip_forward=1 Allows Linux OS to forward packets

The first step in creating your own OpenVPN server is selecting the right hosting environment. You can either use a free-tier Virtual Private Server (VPS) or a local Linux PC. Here, we will discuss both options:

Option A: Free-Tier VPS

Many cloud service providers offer free-tier VPS options that are suitable for hosting your OpenVPN server. Popular choices include:

  • Amazon Web Services (AWS): Offers a free tier for the first 12 months with limited resources.
  • Google Cloud Platform (GCP): Provides a free tier with an always-free f1-micro instance.
  • Oracle Cloud: Offers a free tier with two compute instances.
  • Vultr: Provides a free trial credit that can be used to create a VPS.
Publicidade

Choose a provider based on your preference, and create a new instance. Ensure that the server is running Ubuntu 20.04 or Debian 10/11, as these are the most common distributions for OpenVPN installations.

Option B: Local Linux PC

If you prefer to host the OpenVPN server on your own hardware, you can use a local Linux PC. Ensure your system meets the following requirements:

  • Linux distribution (Ubuntu or Debian recommended)
  • Static IP address (recommended)
  • Firewall configured to allow VPN traffic

This option provides more control and can be cost-effective, but it requires a stable internet connection and sufficient bandwidth for multiple users.

Network and streaming settings menu on Smart TV.

Step 2: Installing OpenVPN Binaries and Configuring CA Directory with Easy-RSA

Once your hosting environment is set up, the next step involves installing OpenVPN and configuring the Certificate Authority (CA) using Easy-RSA.

Installing OpenVPN

To install OpenVPN on your Ubuntu/Debian server, follow these steps:

  1. Connect to your server via SSH. Use the following command, replacing user and server_ip with your actual username and server IP address:
  2. ssh user@server_ip
  3. Update your package lists:
  4. sudo apt update && sudo apt upgrade -y
  5. Install OpenVPN and Easy-RSA:
  6. sudo apt install openvpn easy-rsa -y

Configuring the CA Directory with Easy-RSA

Easy-RSA is a CLI utility to manage the Public Key Infrastructure (PKI) for OpenVPN. To configure Easy-RSA, follow these steps:

  1. Create a directory for Easy-RSA:
  2. make-cadir ~/openvpn-ca
  3. Navigate to the new directory:
  4. cd ~/openvpn-ca
  5. Initialize the PKI environment:
  6. ./easyrsa init-pki
Publicidade

Next, you need to build the CA certificate and key:

  1. Build the CA:
  2. ./easyrsa build-ca

    Follow the prompts to set your passphrase and provide the necessary details. You can use default values by pressing Enter.

Now that you have configured the CA, you can move on to generating the server certificates and keys.

Network connection and structured cabling for high-performance streaming.

Step 3: Generating Cryptographic Keys and Exporting Client .ovpn Profiles

In this step, we will generate the server's cryptographic keys and setup client profiles. This process involves creating secure certificates for both the server and the client.

Generating Server Certificate and Key

  1. Generate the server certificate and key:
  2. ./easyrsa gen-req server nopass
  3. Sign the server certificate with the CA:
  4. ./easyrsa sign-req server server
  5. Generate Diffie-Hellman parameters:
  6. ./easyrsa gen-dh
  7. Generate an HMAC signature to strengthen the server's TLS integrity:
  8. openvpn --genkey --secret ta.key
  9. Move the generated files to the OpenVPN directory:
  10. sudo cp pki/ca.crt pki/issued/server.crt pki/private/server.key pki/dh.pem ta.key /etc/openvpn

Generating Client Certificates and Exporting .ovpn Profiles

To allow clients to connect to your VPN, you must create client certificates and export them as .ovpn files:

  1. Generate a client certificate and key:
  2. ./easyrsa gen-req client1 nopass
  3. Sign the client certificate with the CA:
  4. ./easyrsa sign-req client client1
  5. Export the client configuration file. Create a new directory for the client configuration:
  6. mkdir -p ~/client-configs/keys
  7. Copy the client certificates to the appropriate directory:
  8. cp pki/ca.crt pki/issued/client1.crt pki/private/client1.key ~/client-configs/keys
  9. Create a client configuration file:
  10. nano ~/client-configs/client1.ovpn

    Insert the following configuration, adjusting the server's IP address as necessary:

    client
    dev tun
    proto udp
    remote YOURSERVERIP 1194
    resolv-retry infinite
    nobind
    persist-key
    persist-tun
    remote-cert-tls server
    cipher AES-256-CBC
    auth SHA256
    key-direction 1
    
    

    Then, include the contents of the ca.crt, client1.crt, and client1.key files in the following format:

    
    
    Streaming applications installed and organized on TV screen.

    Insert ca.crt content here

    Insert client1.crt content here

    Insert client1.key content here

  11. Save the file and exit the text editor.
Publicidade

Step 4: Setting Up NAT Network Routes (sysctl) and Opening Router Firewalls

To ensure that your OpenVPN server can route traffic properly, you need to configure network address translation (NAT) and adjust firewall settings.

Configuring NAT with sysctl

OpenVPN requires that IP forwarding is enabled on your server. To enable IP forwarding, follow these steps:

  1. Edit the sysctl configuration file:
  2. sudo nano /etc/sysctl.conf
  3. Uncomment the following line:
  4. #net.ipv4.ip_forward=1

    Change it to:

    net.ipv4.ip_forward=1
  5. Apply the changes:
  6. sudo sysctl -p

Setting Up Firewall Rules

Next, you will need to set up firewall rules to allow VPN traffic. If you are using UFW (Uncomplicated Firewall), execute the following commands:

  1. Allow OpenVPN traffic:
  2. sudo ufw allow 1194/udp
  3. Allow SSH access (if needed):
  4. sudo ufw allow OpenSSH
  5. Enable the firewall:
  6. sudo ufw enable

If you are using iptables instead of UFW, you can set the following rules:

sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -s 10.8.0.0/24 -j ACCEPT

These commands allow traffic from the VPN subnet (10.8.0.0/24) to be masqueraded and forwarded to the internet interface (eth0).

Starting the OpenVPN Server

With everything configured, you can now start the OpenVPN service:

sudo systemctl start openvpn@server

To ensure the service starts automatically on boot, use the following command:

Publicidade
sudo systemctl enable openvpn@server

Testing the VPN Connection

To connect to the OpenVPN server, transfer the client1.ovpn file to your client device (Windows, macOS, Linux, or Android). Use an OpenVPN client application to import the configuration file and connect to your VPN server.

Conclusion

Hosting your own OpenVPN server allows you to maintain privacy and control over your internet connection. By following this detailed guide, you have successfully set up a secure, reliable VPN server on your Linux VPS or local PC. Regularly update your server and OpenVPN installation for optimal security, and consider creating additional client profiles as needed for family or friends. With the knowledge gained here, you can confidently navigate the world of online privacy.

Understanding OpenVPN Configuration Files

OpenVPN relies heavily on configuration files to establish VPN connections. These files, typically denoted by the .conf or .ovpn extensions, contain all necessary parameters for the VPN server and client to communicate effectively. Understanding the structure and options available within these files is crucial for tailoring your VPN server to your specific needs.

At a minimum, your server configuration file should include the following essential directives:

  • port: This directive specifies the port on which the OpenVPN server will listen for incoming connections. The default is 1194, but you can specify any unused port.
  • proto: This parameter allows you to choose between UDP or TCP protocols. UDP is generally preferred for its speed and lower latency, but TCP can be used for more reliable connections.
  • dev: This directive sets the type of virtual network interface. Common options are 'tun' for routed IP tunnels or 'tap' for Ethernet bridging.
  • ca, cert, key, and dh: These parameters define the paths to the Certificate Authority file, server certificate, private key, and Diffie-Hellman parameters, respectively. They are crucial for establishing a secure connection.
  • server: This line specifies the IP address range for the VPN clients. For example, server 10.8.0.0 255.255.255.0 provides clients with IP addresses in the 10.8.0.0/24 subnet.
  • push: Use this directive to push specific routes or DNS settings to clients. For example, push "redirect-gateway def1" routes all traffic through the VPN.
Publicidade

Beyond these basic parameters, you can incorporate advanced configurations to enhance functionality. For example, utilizing the client-config-dir directive allows you to specify a directory containing unique configurations for specific clients. This feature can be beneficial for applying custom routing rules or settings based on user requirements.

Security is another critical aspect of OpenVPN configuration. Implementing the tls-auth directive adds an additional layer of HMAC authentication, which helps mitigate certain types of attacks, such as packet injection. Additionally, you can specify protocols to enforce cipher strength using cipher and auth directives, ensuring that your data is encrypted and authenticated effectively.

Finally, understanding client configuration files is equally important. A standard .ovpn file for a client might include the following directives:

  • remote: This specifies the server address and port to connect to, e.g., remote yourvpnserver.com 1194.
  • client: This tells the OpenVPN client that it is connecting to a server.
  • resolv-retry infinite: This setting ensures that the client continually attempts to resolve the server's address until successful.

By mastering the OpenVPN configuration files, you can create a robust and tailored VPN solution that meets your security and usability requirements.

Routing Policies and Network Ports in OpenVPN

Routing policies and the management of network ports are essential components of a well-functioning OpenVPN server. Understanding how to configure these elements can significantly impact the performance, security, and overall usability of your VPN setup.

Publicidade

When setting up routing in OpenVPN, you will often encounter two primary types of routing: client-to-client and server-to-client. The client-to-client directive, when enabled by adding client-to-client in your server configuration, allows connected clients to communicate directly with each other. This can be beneficial for applications that require peer-to-peer connectivity but introduces potential security concerns. Be cautious when enabling this feature, ensuring that proper firewall rules are in place to protect sensitive data.

On the other hand, server-to-client routing allows the server to manage all traffic flow. By default, this is the mode OpenVPN uses, providing a more controlled environment where the server can enforce security policies and monitor traffic effectively.

To facilitate proper routing, it’s important to manage the IP address assignment correctly. You can utilize the server directive to define a subnet that clients will use. For instance, server 10.8.0.0 255.255.255.0 not only sets the subnet range but also enables OpenVPN to handle the necessary routing tables automatically.

In addition to internal routing, OpenVPN can also manage how client traffic exits the VPN. The push "redirect-gateway def1" command allows you to route all client traffic through the VPN, which can be useful for privacy purposes. However, if you want to enable Internet browsing while maintaining local network access, you can selectively push specific routes using the push "route" directive.

Publicidade

Network ports are another critical aspect of OpenVPN configuration. By default, OpenVPN communicates over UDP on port 1194. However, you may need to change this port for various reasons, such as ISP restrictions or conflicts with other services. To change the listening port, modify the port directive in your server configuration file, and ensure that the corresponding port is open in your firewall settings. If you opt for TCP, remember to adjust your client configuration accordingly.

Firewall management is paramount when configuring OpenVPN. Ensure that your firewall allows traffic on the specified ports. If you're using iptables on a Linux server, you might include rules such as:

  • iptables -A INPUT -p udp --dport 1194 -j ACCEPT
  • iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
  • iptables -A FORWARD -i tun0 -j ACCEPT
  • iptables -A FORWARD -o tun0 -j ACCEPT

In summary, effective routing policies and network port management are vital in establishing a secure and efficient OpenVPN server. By understanding and correctly implementing these configurations, you can optimize your VPN setup for performance and security.

For more networking and security guides, check out our step-by-step tutorials on best verified no-logs VPNs and install VPN on Linux terminal. For official hardware troubleshooting, visit the Official OpenVPN Project Website.

Publicidade

Written by

DomineTec

DomineTec Team — bringing you the best tips on technology, digital security, jobs and finance.

Receba as melhores dicas no seu e-mail

Tecnologia, segurança digital, finanças e empregos — tudo que importa, direto na sua caixa de entrada. 100% gratuito, sem spam.

Respeitamos sua privacidade. Cancele a qualquer momento.

Related Posts

More in Security & Privacy

View all
SoluçÔes de Segurança Zero Trust: Por Que Empresas Ainda Sofrem InvasÔes Após Investir MilhÔes
Security & Privacy

SoluçÔes de Segurança Zero Trust: Por Que Empresas Ainda Sofrem InvasÔes Após Investir MilhÔes

A maioria das implementaçÔes Zero Trust são apenas "band-aids" caros. Aprenda como construir uma arquitetura defensiva real que impede invasÔes e protege a receita.

DomineTec
5 min
Serviços de Teste de Penetração (Pentest): A Diferença Crítica Entre um Scan e uma Auditoria Real
Security & Privacy

Serviços de Teste de Penetração (Pentest): A Diferença Crítica Entre um Scan e uma Auditoria Real

Pare de confiar apenas em scanners automatizados. Entenda por que serviços profissionais de Pentest sĂŁo a Ășnica forma de descobrir falhas lĂłgicas profundas.

Equipe DomineTec
5 min
SOC 2 Compliance Companies: The Ultimate Guide to Security Audits
Security & Privacy

SOC 2 Compliance Companies: The Ultimate Guide to Security Audits

Discover the essential aspects of SOC 2 compliance and security audits in our comprehensive guide for companies seeking certification.

DomineTec
5 min
Serviços de SEO Enterprise: Como Escolher a AgĂȘncia Certa Antes de Investir Mais de R$ 500 Mil
Security & Privacy

Serviços de SEO Enterprise: Como Escolher a AgĂȘncia Certa Antes de Investir Mais de R$ 500 Mil

Este guia completo sobre serviços de SEO enterprise mostra como empresas SaaS, fintechs, plataformas de saĂșde, vendors de cybersecurity e marcas B2B globais podem reduzir CAC, melhorar pipeline qualificado, fortalecer SEO tĂ©cnico, escalar crescimento internacional e criar receita orgĂąnica previsĂ­vel. Entenda modelos de precificação, custos ocultos, comparação de fornecedores, confiança em procurement, ROI, renovação e como escolher a agĂȘncia certa antes de contratar.

DomineTec
5 min
Publicidade