GNU/Linux >> Tutoriales Linux >  >> Linux

Cómo instalar y configurar el servidor OpenVPN en Ubuntu 20.04

OpenVPN es una solución VPN de código abierto para empresas que utilizan técnicas de redes privadas virtuales para crear conexiones seguras punto a punto con instalaciones de acceso remoto. OpenVPN es una tecnología confiable utilizada por muchas VPN para garantizar que todos los datos enviados a través de Internet estén encriptados y sean privados.

En términos simples, OpenVPN le permite conectarse a otros dispositivos dentro de una red segura. Es multiplataforma y puede ser Windows, Mac, Android, iOS y Linux. OpenVPN ofrece un amplio conjunto de características que incluyen:

  • Ancho de banda ilimitado
  • Cambios de servidor ilimitados
  • Uso de varios dispositivos
  • Sin almacenamiento de registros
  • Opciones de protocolo
  • Múltiples conexiones simultáneas

En este tutorial, aprenderemos cómo instalar y configurar el servidor y el cliente OpenVPN en un VPS Ubuntu 20.04.

Requisitos

  • Un nuevo Ubuntu 20.04 VPS en Atlantic.net Cloud Platform.
  • Se ha configurado una contraseña raíz en su servidor.

Paso 1:Crear el servidor en la nube de Atlantic.Net

Primero, inicie sesión en su servidor en la nube de Atlantic.Net. Cree un nuevo servidor, eligiendo Ubuntu 20.04 como sistema operativo, con al menos 1 GB de RAM. Conéctese a su servidor en la nube a través de SSH e inicie sesión con las credenciales resaltadas en la parte superior de la página.

Una vez que haya iniciado sesión en su servidor Ubuntu 20.04, ejecute el siguiente comando para actualizar su sistema base con los últimos paquetes disponibles.

apt-get update -y

Paso 2:habilite el reenvío de IP

A continuación, deberá habilitar el reenvío de IP en su sistema para que OpenVPN pueda enrutar correctamente el tráfico a través de la VPN.

Puede habilitar el reenvío de IP editando el archivo /etc/sysctl.conf:

nano /etc/sysctl.conf

Descomente la siguiente línea:

net.ipv4.ip_forward = 1

Guarde el archivo cuando haya terminado, luego ejecute el siguiente comando para aplicar los cambios:

sysctl -p

Paso 3:Instale el servidor OpenVPN

apt-get install openvpn -y

Una vez que se haya completado la instalación, puede continuar con el siguiente paso.

Paso 4:crear la autoridad de certificación

Para configurar la autoridad de certificación y la infraestructura PKI, deberá descargar EasyRSA en su sistema. Puedes descargarlo con el siguiente comando:

wget https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.6/EasyRSA-unix-v3.0.6.tgz

Una vez descargado, extraiga el archivo descargado con el siguiente comando:

tar -xvzf EasyRSA-unix-v3.0.6.tgz

A continuación, mueva el directorio extraído a /etc/openvpn/ con el siguiente comando:

mv EasyRSA-v3.0.6 /etc/openvpn/easy-rsa

A continuación, cambie el directorio a /etc/openvpn/easy-rsa y cree un archivo de configuración de EasyRSA:

cd /etc/openvpn/easy-rsa
nano vars

Agregue las siguientes líneas, incluidos su país, ciudad y dirección de correo electrónico preferida:

set_var EASYRSA                 "$PWD"
set_var EASYRSA_PKI             "$EASYRSA/pki"
set_var EASYRSA_DN              "cn_only"
set_var EASYRSA_REQ_COUNTRY     "INDIA"
set_var EASYRSA_REQ_PROVINCE    "Gujarat"
set_var EASYRSA_REQ_CITY        "Junagadh"
set_var EASYRSA_REQ_ORG         "Atlantic CERTIFICATE AUTHORITY"
set_var EASYRSA_REQ_EMAIL     "[email protected]"
set_var EASYRSA_REQ_OU          "Atlantic EASY CA"
set_var EASYRSA_KEY_SIZE        2048
set_var EASYRSA_ALGO            rsa
set_var EASYRSA_CA_EXPIRE      7500
set_var EASYRSA_CERT_EXPIRE     365
set_var EASYRSA_NS_SUPPORT  "no"
set_var EASYRSA_NS_COMMENT            "Atlantic CERTIFICATE AUTHORITY"
set_var EASYRSA_EXT_DIR         "$EASYRSA/x509-types"
set_var EASYRSA_SSL_CONF        "$EASYRSA/openssl-easyrsa.cnf"
set_var EASYRSA_DIGEST          "sha256"

Guarde el archivo cuando haya terminado.

Luego, inicie el directorio PKI usando el siguiente comando:

./easyrsa init-pki

Deberías obtener el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki

A continuación, cree los certificados de CA con el siguiente comando:

./easyrsa build-ca

Deberías obtener el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020

Enter New CA Key Passphrase:
Re-Enter New CA Key Passphrase:
Generating RSA private key, 2048 bit long modulus (2 primes)
.....................................................................................................+++++
..................................................+++++
e is 65537 (0x010001)
Can't load /etc/openvpn/easy-rsa/pki/.rnd into RNG
139636302492992:error:2406F079:random number generator:RAND_load_file:Cannot open file:../crypto/rand/randfile.c:98:Filename=/etc/openvpn/easy-rsa/pki/.rnd
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields, there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:
CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/etc/openvpn/easy-rsa/pki/ca.crt

El comando anterior generará dos archivos llamados ca.key y ca.crt. Estos certificados se utilizarán para firmar su servidor y los certificados de sus clientes.

Paso 5:Crear archivos de certificados de servidor

A continuación, deberá generar un par de claves y una solicitud de certificado para su servidor.

Ejecute el siguiente comando para generar la clave del servidor denominada atlantic-server:

./easyrsa gen-req atlantic-server nopass

Debería ver el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020
Generating a RSA private key
.............................+++++
...+++++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/atlantic-server.key.IMonKybM0y'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [atlantic-server]:

Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa/pki/reqs/atlantic-server.req
key: /etc/openvpn/easy-rsa/pki/private/atlantic-server.key

Esto generará una clave privada y un archivo de solicitud de certificado para el servidor.

Paso 6:Firme la clave del servidor mediante CA

A continuación, deberá firmar la clave del servidor atlántico con su certificado de CA:

Puede firmar la clave del servidor usando el siguiente comando:

./easyrsa sign-req server atlantic-server

Debería ver el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020

You are about to sign the following certi
ficate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 365 days:

subject=
commonName                = atlantic-server

Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes
Using configuration from /etc/openvpn/easy-rsa/pki/safessl-easyrsa.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'atlantic-server'
Certificate is to be certified until Jun 29 11:43:05 2021 GMT (365 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/atlantic-server.crt

A continuación, verifique el archivo de certificado generado con el siguiente comando:

openssl verify -CAfile pki/ca.crt pki/issued/atlantic-server.crt

Deberías obtener el siguiente resultado:

pki/issued/atlantic-server.crt: OK

A continuación, ejecute el siguiente comando para generar una clave Diffie-Hellman segura para usar en el intercambio de claves:

./easyrsa gen-dh

Deberías obtener el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
......................+...........................+............................................

DH parameters of size 2048 created at /etc/openvpn/easy-rsa/pki/dh.pem

Después de crear todos los archivos de certificado, cópielos en el directorio /etc/openvpn/server/:

cp pki/ca.crt /etc/openvpn/server/
cp pki/dh.pem /etc/openvpn/server/
cp pki/private/atlantic-server.key /etc/openvpn/server/
cp pki/issued/atlantic-server.crt /etc/openvpn/server/

Paso 7:Generar certificado de cliente y archivo de clave

A continuación, deberá crear la clave y el archivo de certificado para el cliente.

Primero, ejecute el siguiente comando para crear el archivo de claves del cliente:

./easyrsa gen-req client nopass

Deberías obtener el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020
Generating a RSA private key
...+++++
........+++++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/client.key.JmBal6cmr8'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [client]:

Keypair and certificate request completed. Your files are:
req: /etc/openvpn/easy-rsa/pki/reqs/client.req
key: /etc/openvpn/easy-rsa/pki/private/client.key

A continuación, firme la clave de cliente con su certificado de CA:

./easyrsa sign-req client client

Deberías obtener el siguiente resultado:

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.1.1f  31 Mar 2020

You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a client certificate for 365 days:

subject=
commonName                = client

Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes
Using configuration from /etc/openvpn/easy-rsa/pki/safessl-easyrsa.cnf
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'client'
Certificate is to be certified until Jun 29 11:46:58 2021 GMT (365 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /etc/openvpn/easy-rsa/pki/issued/client.crt

A continuación, copie todos los certificados de clientes y archivos clave en el directorio /etc/openvpn/client/:

cp pki/ca.crt /etc/openvpn/client/
cp pki/issued/client.crt /etc/openvpn/client/
cp pki/private/client.key /etc/openvpn/client/

Paso 8:configurar el servidor OpenVPN

En este punto, todos los certificados y archivos clave están listos. A continuación, cree un nuevo archivo de configuración de OpenVPN dentro del directorio /etc/openvpn/:

nano /etc/openvpn/server.conf

Agregue las siguientes líneas según su certificado y ruta de clave:

port 1194
proto udp
dev tun
ca /etc/openvpn/server/ca.crt
cert /etc/openvpn/server/atlantic-server.crt
key /etc/openvpn/server/atlantic-server.key
dh /etc/openvpn/server/dh.pem
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1"

push "dhcp-option DNS 208.67.222.222"
push "dhcp-option DNS 208.67.220.220"
duplicate-cn
cipher AES-256-CBC
tls-version-min 1.2
tls-cipher TLS-DHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-RSA-WITH-AES-256-
CBC-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-
CBC-SHA256
auth SHA512
auth-nocache
keepalive 20 60
persist-key
persist-tun
compress lz4
daemon
user nobody
group nogroup
log-append /var/log/openvpn.log
verb 3

Guarde el archivo cuando haya terminado, luego inicie el servicio OpenVPN y habilítelo para que se inicie después de que el sistema se reinicie usando el siguiente comando:

systemctl start [email protected]
systemctl enable [email protected]

Ejecute el siguiente comando para verificar el estado del servicio OpenVPN:

systemctl status [email protected]

Deberías obtener el siguiente resultado:

Loaded: loaded (/lib/systemd/system/[email protected]; disabled; vendor preset: enabled)
Active: active (running) since Mon 2020-06-29 11:48:25 UTC; 7s ago
Docs: man:openvpn(8)
https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
https://community.openvpn.net/openvpn/wiki/HOWTO
Main PID: 2868 (openvpn)
Status: "Initialization Sequence Completed"
Tasks: 1 (limit: 2353)
Memory: 2.0M
CGroup: /system.slice/system-openvpn.slice/[email protected]
└─2868 /usr/sbin/openvpn --daemon ovpn-server --status /run/openvpn/server.status 10 --cd /etc/openvpn --script-security 2 --conf>

Jun 29 11:48:25 vpnserver systemd[1]: Starting OpenVPN connection to server...
Jun 29 11:48:25 vpnserver systemd[1]: Started OpenVPN connection to server.

Una vez que el servicio OpenVPN se haya iniciado correctamente, creará una nueva interfaz de red llamada tun0. Puedes verificarlo con el siguiente comando:

ip a show tun0

Debería obtener la nueva interfaz tun0 en el siguiente resultado:

4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state 
UNKNOWN group default qlen 100
link/none
inet 10.8.0.1 peer 10.8.0.2/32 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::5f83:99a:30d:eb0/64 scope link stable-privacy
valid_lft forever preferred_lft forever

Paso 9:Crear archivo de configuración del cliente

A continuación, deberá crear un archivo de configuración de cliente de OpenVPN denominado client.ovpn. Necesitará este archivo para conectar su servidor OpenVPN desde el sistema cliente.

nano /etc/openvpn/client/client.ovpn

Agregue las siguientes líneas:

client
dev tun
proto udp
remote your-vpn-server-ip 1194
ca ca.crt
cert client.crt
key client.key
cipher AES-256-CBC
auth SHA512
auth-nocache
tls-version-min 1.2
tls-cipher TLS-DHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-RSA-WITH-AES-256-
CBC-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-
CBC-SHA256
resolv-retry infinite
compress lz4
nobind
persist-key
persist-tun
mute-replay-warnings
verb 3

Guarde el archivo cuando haya terminado.

Paso 10:Instalar y configurar el cliente OpenVPN

A continuación, deberá instalar OpenVPN en el sistema cliente y conectarse al servidor OpenVPN.

Primero, inicie sesión en la máquina cliente e instale el paquete OpenVPN con el siguiente comando:

apt-get install openvpn -y

A continuación, deberá copiar los archivos de configuración del cliente OpenVPN desde el servidor OpenVPN a la máquina cliente.

En la máquina cliente, ejecute el siguiente comando para descargar todos los archivos de configuración del cliente:

scp -r [email protected]:/etc/openvpn/client .

Una vez que se hayan copiado todos los archivos, cambie el directorio al cliente y ejecute el siguiente comando para conectarse al servidor OpenVPN:

cd client
openvpn --config client.ovpn

Una vez que esté conectado al servidor OpenVPN, debería ver el siguiente resultado:

Jun 29 11:48:27 2020 TCP/UDP: Preserving recently used remote address: 
[AF_INET]69.87.218.145:1194
Jun 29 11:48:27 2020 Socket Buffers: R=[212992->212992] S=[212992->212992]
Jun 29 11:48:27 2020 UDP link local: (not bound)
Jun 29 11:48:27 2020 UDP link remote: [AF_INET]69.87.218.145:1194
Jun 29 11:48:27 2020 TLS: Initial packet from [AF_INET]69.87.218.145:1194, sid=6d27e1cb 
524bd8cd
Jun 29 11:48:27 2020 VERIFY OK: depth=1, CN=Easy-RSA CA
Jun 29 11:48:27 2020 VERIFY OK: depth=0, CN=atlantic-server
Jun 29 11:48:27 2020 Control Channel: TLSv1.3, cipher TLSv1.3 TLS_AES_256_GCM_SHA384, 
2048 bit RSA
Jun 29 11:48:27 2020 [atlantic-server] Peer Connection Initiated with 
[AF_INET]69.87.218.145:1194
Jun 29 11:48:27 2020 SENT CONTROL [atlantic-server]: 'PUSH_REQUEST' (status=1)
Jun 29 11:48:27 2020 PUSH: Received control message: 'PUSH_REPLY,redirect-gateway 
def1,dhcp-option DNS 208.67.222.222,dhcp-option DNS 208.67.220.220,route 10.8.0.1,topology 
net30,ping 20,ping-restart 60,ifconfig 10.8.0.6 10.8.0.5,peer-id 0,cipher AES-256-GCM'
Jun 29 11:48:27 2020 OPTIONS IMPORT: timers and/or timeouts modified
Jun 29 11:48:27 2020 OPTIONS IMPORT: --ifconfig/up options modified
Jun 29 11:48:27 2020 OPTIONS IMPORT: route options modified

Después de una conexión exitosa, OpenVPN asignará una dirección IP a su sistema. Puedes comprobarlo con el siguiente comando:

ip a show tun0

Salida:

4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state 
UNKNOWN group default qlen 100
link/none
inet 10.8.0.6 peer 10.8.0.5/32 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::7226:57b1:f101:313b/64 scope link stable-privacy
valid_lft forever preferred_lft forever

También puede verificar el registro del servidor OpenVPN para verificar el estado de la conexión usando el siguiente comando:

tail -f /var/log/openvpn.log

Conclusión

¡Felicidades! Ha configurado con éxito un servidor VPN con OpenVPN en un Ubuntu 20.04 VPS. Ahora puede acceder a Internet de forma segura y proteger su identidad, ubicación y tráfico. Visite la documentación oficial de OpenVPN para obtener más información.


Linux
  1. Cómo instalar y configurar el servidor de acceso OpenVPN

  2. Cómo instalar y configurar un servidor NFS en Ubuntu 20.04

  3. Cómo instalar y configurar OpenVPN Server en Debian 10

  4. Cómo instalar y configurar el servidor DHCP en Ubuntu 20.04

  5. Cómo instalar y configurar el servidor Redis en Ubuntu

Cómo instalar y usar pgAdmin en Ubuntu 18.04

Cómo instalar y configurar Parse Server en Ubuntu 20.04

Cómo instalar y configurar Elasticsearch en Ubuntu 20.04

Cómo instalar y configurar Nextcloud en Ubuntu 20.04

Cómo instalar y configurar un servidor TeamSpeak en Ubuntu 18.04

Cómo instalar y configurar un servidor de Minecraft en Ubuntu 18.04