Back to blogSecurity & Privacy

How to Install and Connect a VPN on Linux Ubuntu via Terminal

8 min read
How to Install and Connect a VPN on Linux Ubuntu via Terminal
Publicidade

To install and connect a VPN on Linux Ubuntu via terminal, use APT for OpenVPN or WireGuard, and configure with command utilities.

Publicidade

In the realm of networking, Virtual Private Networks (VPNs) offer a robust solution for maintaining online privacy and bypassing geo-restrictions. Linux Ubuntu, with its powerful command line interface, allows users to manage VPN connections effectively through terminal commands. Utilizing terminal interfaces to manage VPN connection tunnels presents several advantages, such as greater control over configurations, the ability to automate tasks, and easier integration with scripts. This guide will walk you through the processes of installing and configuring both OpenVPN and WireGuard on Ubuntu via the terminal.

Wi-Fi router transmitting stable and fast internet signal.

Advantages of Managing VPN Connection Tunnels via Terminal Interfaces in Linux

DomineTec Tip: Command-line interfaces in Linux allow powerful routing automation rules. If you need to manage Smart DNS, check out how to configure smart DNS on router.

Using the terminal to manage VPN connections on Ubuntu comes with numerous advantages:

  • Precision and Control: Command line interfaces allow for fine-tuned configurations that may not be available through graphical user interfaces.
  • Automation: Scripts can be created to automate the connection process, making it easier to manage multiple VPN profiles.
  • Resource Efficiency: Terminal-based applications consume fewer resources compared to GUI applications, making them ideal for servers or older hardware.
  • Remote Management: Connecting to headless servers and managing VPN connections remotely is seamless via SSH.
  • Comprehensive Troubleshooting: Command line tools offer detailed logging and diagnostic capabilities for troubleshooting connection issues.
Publicidade
Digital padlock representing internet network security and privacy.

Method 1: Installing and Running OpenVPN Clients on Ubuntu Command Lines (APT)

Terminal Action Ubuntu Shell Command (OpenVPN/WireGuard) Execution Effect
Install OpenVPN sudo apt update && sudo apt install openvpn -y Downloads the OpenVPN dependencies
Start WireGuard Tunnel sudo wg-quick up wg0 Brings up the virtual interface secure connection

OpenVPN is one of the most widely used VPN protocols and comes with a robust set of features. Below are the steps to install and configure OpenVPN on Ubuntu using terminal commands.

Step 1: Update Package List

Before installing any software, it is essential to update the package list to ensure you have the latest version available. Open your terminal and execute the following command:

sudo apt update

Step 2: Install OpenVPN

To install OpenVPN, run the following command:

sudo apt install openvpn

This command fetches OpenVPN from the Ubuntu repositories and installs it on your system. During installation, you might be prompted to confirm the installation; type 'Y' and hit Enter to proceed.

Step 3: Obtain OpenVPN Configuration Files

Next, you need the configuration files provided by your VPN service provider. These files typically end with a .ovpn extension and contain the necessary settings to connect to the VPN server. Download these configuration files to a directory of your choice, for example:

~/vpn-configs

Step 4: Connect to the VPN

To connect to the VPN, navigate to the directory containing your .ovpn files:

cd ~/vpn-configs

Then, use the following command to initiate the connection:

sudo openvpn --config your-config-file.ovpn

Replace your-config-file.ovpn with the actual name of your configuration file. You may be prompted to enter your VPN username and password if required by your provider.

Publicidade

Step 5: Verify the VPN Connection

To verify that your VPN connection is active, you can use the following command to check your IP address:

curl ifconfig.me

Your IP address should now reflect the VPN server's location instead of your physical location.

Network and streaming settings menu on Smart TV.

Method 2: Configuring and Enabling WireGuard Interfaces via wg-quick Utilities

WireGuard is a modern, high-performance VPN protocol that is considered simpler and faster than OpenVPN. Below are the steps to install and configure WireGuard on Ubuntu through the terminal.

Step 1: Install WireGuard

First, ensure your package list is up to date, as mentioned previously. Then, install WireGuard with the following command:

sudo apt install wireguard

Step 2: Generate WireGuard Keys

WireGuard utilizes public and private key pairs for authentication. To generate these keys, run:

wg genkey | tee privatekey | wg pubkey > publickey

This command creates two files: privatekey and publickey. Store these keys securely, as they are essential for the configuration.

Step 3: Configure WireGuard

Create a configuration file, typically located in the /etc/wireguard/ directory, using a text editor of your choice:

sudo nano /etc/wireguard/wg0.conf

In this file, you need to add the following configuration:

[Interface]
PrivateKey = your_private_key
Address = 10.0.0.2/24
ListenPort = 51820

[Peer]
PublicKey = peer_public_key
Endpoint = 192.168.1.100:51820
AllowedIPs = 0.0.0.0/0

Replace your_private_key with the contents of your privatekey file, peer_public_key with the public key of the VPN server, and the endpoint IP with the server's IP address.

Publicidade

Step 4: Bring Up the WireGuard Interface

To activate the WireGuard interface, use the wg-quick utility:

sudo wg-quick up wg0

After running this command, your VPN should be connected. You can check the status of the WireGuard interface by executing:

sudo wg

Step 5: Verify the VPN Connection

As with OpenVPN, you can verify your connection by checking your public IP address:

curl ifconfig.me

The output should show your IP as the VPN's location.

Network connection and structured cabling for high-performance streaming.

To automate the VPN connection on system startup, you can create a systemd service for both OpenVPN and WireGuard.

For OpenVPN

1. Create a service file for OpenVPN:

sudo nano /etc/systemd/system/openvpn@.service

2. Add the following content:

UnitSection
Description=OpenVPN connection to %i
After=network.target

ServiceSection
Type=simple
ExecStart=/usr/sbin/openvpn --config /etc/openvpn/%i.conf
Restart=on-failure

InstallSection
WantedBy=multi-user.target

3. Enable the OpenVPN service to start on boot:

sudo systemctl enable openvpn@your-config-file

For WireGuard

1. Create a service file for WireGuard:

sudo nano /etc/systemd/system/wg-quick@wg0.service

2. Add the following content:

UnitSection
Description=WireGuard via wg-quick(8) for %i
After=network-online.target
Wants=network-online.target

ServiceSection
Type=simple
ExecStart=/usr/bin/wg-quick up %i
ExecStop=/usr/bin/wg-quick down %i
Restart=on-failure

InstallSection
WantedBy=multi-user.target

3. Enable the WireGuard service to start on boot:

sudo systemctl enable wg-quick@wg0
Streaming applications installed and organized on TV screen.

Essential Diagnostic Tools for Resolving Connection Issues and Routing Checks

When managing VPN connections, it is crucial to have diagnostic tools at your disposal to troubleshoot any issues. Below are some essential commands and techniques:

Publicidade

Check Network Interface Status

Use the following command to view the status of all network interfaces:

ip a

This will show you if your VPN interface (tun0 for OpenVPN or wg0 for WireGuard) is up and running.

View Logs for OpenVPN

To check OpenVPN logs for connection issues, use:

journalctl -u openvpn@your-config-file

View Logs for WireGuard

For WireGuard, you can check the logs using:

sudo journalctl -u wg-quick@wg0

Test Connectivity

To test connectivity through your VPN, use the following command:

ping 8.8.8.8

This command tests connectivity to an external IP address. If the VPN is working correctly, the ping should return responses.

Check Routing Table

To view your current routing table, run:

route -n

This command will show you the routes available on your system. Ensure that your default route points through the VPN interface when connected.

Conclusion

Managing VPN connections on Linux Ubuntu via the terminal provides a level of control and automation that is invaluable for users seeking both privacy and accessibility. By following the steps outlined for installing OpenVPN and WireGuard, configuring automatic startup, and utilizing diagnostic tools, you can ensure a seamless and secure VPN experience. Whether you are a casual user or a systems administrator, mastering these command line utilities will enhance your networking capabilities and safeguard your online activities.

Configuring OpenVPN on Ubuntu: Advanced Settings

Publicidade

Once you have installed OpenVPN on your Ubuntu system, the next step involves configuring the OpenVPN client to connect to a VPN server. This configuration is crucial for ensuring secure and efficient VPN connectivity. The configuration file, typically named client.ovpn, serves as the cornerstone of this setup. It contains essential parameters that dictate how your system interacts with the VPN server.

To begin, you will need to locate or create your client.ovpn file, which usually resides in the /etc/openvpn/ directory. It is advisable to create a backup of the original file before making any modifications. The following key parameters should be included in your OpenVPN configuration:

  • client - This directive indicates that the configuration is for a client.
  • dev tun - This specifies the use of a TUN (layer 3) device, which is suitable for routing IP packets.
  • proto udp - The protocol used for communication; UDP is generally faster and more efficient than TCP for VPN applications.
  • remote vpn.dominetec.com 1194 - Replace this with your actual VPN server's domain or IP address and the port number on which the server is listening (generally 1194 for UDP).
  • resolv-retry infinite - This setting directs the client to keep trying to resolve the server name indefinitely in case of DNS issues.
  • nobind - Prevents the client from binding to a specific local port, allowing it to select one dynamically.
  • persist-key and persist-tun - These options help maintain the tunnel and key during network disruptions.
  • remote-cert-tls server - This directive ensures that the server certificate is verified to protect against man-in-the-middle attacks.
  • cipher AES-256-CBC - Specifies the encryption cipher used for securing the connection; AES-256 is widely regarded for its security and performance.
  • auth SHA256 - This setting defines the hash function used for authenticating packets.
  • key-direction 1 - This is necessary if you are using a shared key for both client and server.
  • cert /etc/openvpn/client.crt and key /etc/openvpn/client.key - The paths to the client’s certificate and private key files, respectively.
  • ca /etc/openvpn/ca.crt - Path to the Certificate Authority certificate that signed the server's certificate.
Publicidade

In addition to the basic settings, you may want to implement specific routing policies. By default, OpenVPN will route all traffic through the VPN, effectively creating a 'full tunnel.' However, in some cases, you may want to configure a 'split tunnel' where only specific traffic routes through the VPN. This can be accomplished by adding appropriate route directives in your configuration file.

For example, to route only traffic destined for the 192.168.1.0/24 network through the VPN, you would add:

route 192.168.1.0 255.255.255.0

Finally, once you have completed your configuration, start the OpenVPN service using the following command:

sudo systemctl start openvpn@client

Ensure the service is enabled to start on boot with:

sudo systemctl enable openvpn@client

By carefully configuring these parameters, you can ensure a secure and optimized VPN connection tailored to your specific networking needs.

Understanding VPN Security Concepts and Best Practices

When implementing a VPN on an Ubuntu system, understanding the underlying security concepts is critical for maintaining the integrity and confidentiality of your data. A VPN secures your internet connection by encrypting your data traffic, shielding it from unauthorized access and eavesdropping. However, the effectiveness of a VPN is contingent upon several key security practices and considerations.

Firstly, the choice of encryption protocol plays a pivotal role in the security of your VPN. The most commonly used protocols include:

Publicidade
  • OpenVPN - Open-source and highly configurable, it supports various encryption methods and is considered very secure when properly configured.
  • IPsec - Often used in conjunction with L2TP, IPsec provides strong encryption and authentication but can be complex to set up.
  • WireGuard - A newer protocol that offers simplicity and high performance, along with state-of-the-art cryptographic principles.

Regardless of the protocol selected, it is imperative to use strong encryption standards. AES-256-GCM is recommended as it provides both confidentiality and integrity checks, making it less susceptible to attacks.

Another critical aspect of VPN security is the management of authentication credentials. Using two-factor authentication (2FA) significantly enhances security by requiring a second form of verification beyond just a password. This could be a time-based one-time password (TOTP) or a hardware token. Additionally, regularly rotating and updating your passwords and keys can mitigate the risk of unauthorized access.

Monitoring and logging are also vital components of VPN security. While many VPN providers keep logs for operational purposes, it is crucial to understand their logging policies. A no-logs policy means that the VPN provider does not store any connection or usage data, which is a significant advantage for user privacy. If you manage your own VPN, ensure that logging is minimized and that logs do not contain identifiable information.

Network ports and firewall settings also require careful management. By default, OpenVPN uses UDP port 1194, but it can be configured to use TCP on port 443, which is advantageous for traversing restrictive firewalls. Ensure that the necessary ports are open on both the client and server side, and consider implementing firewall rules to block all non-VPN traffic when the VPN is connected, often referred to as a kill switch.

Publicidade

Finally, be aware of potential vulnerabilities inherent in VPN use. For instance, DNS leaks can expose your browsing activity. To prevent this, configure your VPN settings to use secure DNS servers, such as Cloudflare (1.1.1.1) or Google DNS (8.8.8.8). You can also implement DNS leak protection features available in many VPN clients.

In conclusion, while a VPN provides a robust layer of security, its effectiveness is heavily reliant on the correct configuration and adherence to best practices. By paying close attention to encryption protocols, authentication methods, logging policies, and network configurations, you can significantly enhance your VPN's security posture, ensuring that your data remains private and secure while traversing the internet.

For more networking and security guides, check out our step-by-step tutorials on configure smart DNS on router and best verified no-logs VPNs. For official hardware troubleshooting, visit the Official Ubuntu Portal.

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