OpenVPN en OpenBSD

Enlaces de interés

Instalación

Despues de configurar perfil en nuestro OpenBSD, lanzamos la instalación:

# groupadd -g 500 _openvpn
# useradd -u 500 -g 500 -c 'OpenVPN Server' -s /sbin/nologin -d /var/openvpn -m _openvpn

# more pkglist.txt | grep openvpn
openvpn-2.0.2.tgz
openvpn-2.0.4.tgz

# pkg_add -v openvpn-2.0.4.tgz

# cp -R /usr/local/share/examples/openvpn/ /etc

Openvpn con clave estática (Pre-Shared Key)

La configuración de OpenVPN con clave estática es la más simple de instalar, e ideal para VPNs punto a punto.

VENTAJAS:

  • Fácil instalación.
  • SIN X509 PKI (Public Key Infrastructure) que mantener

INCONVENIENTES:

  • Escalabilidad limitada – un cliente, un servidor
  • La clave secreta tiene que existir en texto plano en cada uno de los pares VPN
  • La clave secreta tiene que intercambiarse previamente usando un canal seguro

Ejemplo sencillo

Se creará un tunel VPN con un terminador de tunel servidor con IP 192.168.8.1 y un terminador de tunel cliente con IP 192.168.8.2 Encriptando la comunicación entre cliente y servidor a traves del puerto UDP 1194, el puerto por defecto de OpenVPN.

Generando una clave estática:

# openvpn --genkey --secret static.key

Copia la clave estática tanto en cliente como servidor, utilizado un canal seguro existente (SFTP).

Ejemplo de fichero de configuración para Servidor

dev tun0
ifconfig 192.168.8.1 192.168.8.2
secret /etc/openvpn/static.key

Ejemplo de fichero de configuración para cliente

remote myremote.mydomain
dev tun0
ifconfig 192.168.8.2 192.168.8.1
secret /etc/openvpn/static.key

Configuración del Firewall

Asegurate que:

  • El puerto UDP 1194 está abierto en el Servidor
  • La interfaz virtual TUN usada por OpenVPN no está bloqueada en el cliente o en el servidor

La mayoria de los problemas de conexión encontrados en OpenVPN están relacionados con una mala configuración del firewall.

Probando la VPN

Ejecuta OpenVPN usando los respectivos archivos de configuración tanto en servidor como en cliente, cambiando ‘myremote.mydomain’ en el archivo de configuración de cliente apuntando al nombre de dominio o IP pública del servidor.

# openvpn --config /etc/openvpn/openvpn.conf

Para verificar que la VPN está ejecutandose, deberias poder hacer ping hacia 192.168.8.2 desde el servidor y hacia 192.168.8.1 desde el cliente.

Completando el Ejemplo

Añade las siguientes líneas a los ficheros de configuración de servidor y cliente, para que openVPN corra como daemon, se use compresión en el enlace, y se mantenga viva la conexión a través de NAT router/firewall

# ejecuta OpenVPN como servicio
user nobody
group nobody
daemon
# Usa compresion en el enlace VPN
comp-lzo
# Enlace mas resistente a fallos en la conexion
keepalive 10 60
ping-timer-rem
persist-tun
persist-key

Permitir al cliente llegar a la red completa del servidor

Supongamos que la red de servidor OpenVPN es 192.168.1.0/24. tendriamos que añadir la siguiente ruta en el cliente:

en Linux:

# route add -net 192.168.1.0 netmask 255.255.255.0 dev tun0

En OpenBSD:

# route add -net 192.168.1 tun0 192.168.8.2

Then on the server side, add a route to the server’s LAN gateway that routes 10.8.0.2 to the OpenVPN server machine (only necessary if the OpenVPN server machine is not also the gateway for the server-side LAN). Also, don’t forget to enable IP Forwarding on the OpenVPN server machine.

Configurando PKI (Infrestuctura de Clave Pública)

Vamos a configurar nuestro propio Certificate Authority (CA) y generar certificados y claves para un servidor OpenVPN y múltiples clientes

El primer paso configurando OpenVPN 2.0 es establecer una PKI (public key infrastructure). PKI consta de:

  • Un certificado por separado (también conocida como clave pública) y una clave privada para cada servidor y cada cliente
  • Un master Certificate Authority (CA) certificado y clave que es usado para firmar cada certificado de servidor y cliente.

OpenVPN soporta validación bidireccional basada en certificados, lo que significa que cada cliente debe validar el certificado de servidor y el servidor debe validar el certificado de cliente antes de se establezca una confianza mutua.

Servidor y cliente validarán al otro comprobando que el certificado presente fue firmado por el master certificate authority (CA), para despúes comprobar la información de la cabecera del certificado ya validado, como el certificate common name o el tipo de certificado (cliente or servidor).

Este modelo de seguridad tiene los siguientes elementos interesantes desde la perspectiva de una VPN:

  • El Servidor solo necesita su propio certificado/clave – No necesita conocer los certificados individuales de cada uno de los clientes con posibilidad de conectarse a él.
  • El Servidor solo acepta clientes suyos certificados fueron firmados por el master CA certificate (El cual generaremos más adelante). Y como el servidor es capaz de realizar la verificación de la firma sin acceder a la clave privada CA , es posible que esta clave CA (la clave más sensible en toda la estructura PKI) resida en una máquina completamente diferente, incluso una que no tenga conexión a la red.
  • Si una clave privada se ve comprometida, puede ser deshabilitada añadiendo su certificado a una CRL (certificate revocation list). La CRL permite que los certificados comprometidos sean selectivamente rechazados sin requerir una reconstrucción completa de la PKI.
  • El Servidor puede forzar derechos de acceso para clientes especificos basados en campos del certificado, tales como el Common Name.

Creando Certificados & Claves de la Autoridad Certificadora Primaria (CA)

En esta sección generaremos un certificado/clave master CA , un certificado/clave de servidor , y certificados/claves para tres clientes por separado.

Para la gestión de PKI, usaremos un conjunto de Scripts incluidos con OpenVPN.

Luego, Iniciaremos la infraestructura PKI:

# cd /etc/openvpn/easy-rsa/
# ./vars
NOTE: when you run ./clean-all, I will be doing a rm -rf on /etc/openvpn/easy-rsa/keys
# ./clean-all
you must define KEY_DIR
# export KEY_DIR="/etc/openvpn/easy-rsa/keys"

El último comando (build-ca) Contruirá eol certificado y clave Autoridad Certificadora (CA) con el comando OpenSSL interactivo:

# ./build-ca
Generating a 1024 bit RSA private key
............++++++
...........++++++
writing new private key to 'ca.key'
-----
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.
-----
Country Name (2 letter code) [KG]:
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:OpenVPN-CA
Email Address [me@myhost.mydomain]:

Observa que en la secuencia de arriba, la mayoria de los parametros preguntados tienen un valor por defecto establecido en el script ‘vars’. El único parametro que debe explicitamente introducirse es el ‘Common Name’. En el ejemplo de arriba, “OpenVPN-CA”.

Generando certificados & claves para servidor

Generaremos un certificado y clave privada para el servidor:

# cd /etc/openvpn/easy-rsa/
# ./build-key-server server

Como en el paso anterior, la mayoria de los parametros viene por defecto. Cuando se pregunta por el ‘Common Name’, introduce “server”. Las dos siguiente preguntas serán contestadas afirmativamente, “Sign the certificate? [y/n]” y “1 out of 1 certificate requests certified, commit? [y/n]”.

Generando certificados & claves para 3 clientes

Generamos los certificados de cliente

# cd /etc/openvpn/easy-rsa/
# ./build-key client1
# ./build-key client2
# ./build-key client3

Si prefieres que las claves de cliente tengan contraseña, ejecuta el script ‘build-key-pass’ en su lugar.

Recuerda que para cada cliente, debes asegurarte de escribir el apropiado ‘Common Name’ cuando se te pregunte, ej: “client1”, “client2”, o “client3”. Siempre usa un ‘common name’ único para cada cliente.

Genererar parametros de Diffie Hellman

los Parametros de Diffie Hellman deberán ser generados por el servidor de OpenVPN. En OpenBSD:

# cd /etc/openvpn/easy-rsa/
# ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
.................+...........................................
...................+.............+.................+.........
......................................

Ficheros de claves

Nuestras claves recien generadas y certificados se encuentran ahora en el subdirectorio ‘keys’. La siguiente tabla explica los ficheros más relevantes:

Archivo Necesario para Propósito Confidencial
ca.crt servidor + clientes Root CA certificate NO
ca.key key signing machine only Root CA key SI
dh{n}.pem solo servidor Parametros Diffie Hellman NO
server.crt solo servidor Certificado Servidor NO
server.key solo servidor Clave Servidor SI
client1.crt solo cliente1 Certificado Cliente1 NO
client1.key solo cliente1 Clave Cliente1 SI
client2.crt solo cliente2 Certificado Cliente2 NO
client2.key solo cliente2 Clave Cliente2 SI
client3.crt solo cliente3 Certificado Cliente3 NO
client3.key solo cliente3 Clave Cliente3 SI

El último paso del proceso de generación de claves es copiar todos los ficheros en las máquinas que lo necesiten, tratando de copiar los ficheros confidenciales a través de un canal seguro.

¿Sería posible configurar PKI sin un canal seguro preexistente?

La respuesta es sí. En el ejemplo de arriba, hemos generado todas las claves privadas en el mismo lugar. Esforzandonos un poco más, podriamos haber hecho esto de otra manera. por ejemplo, en lugar de generar el certificado y claves de cliente en el servidor, podriamos haber hecho que el cliente generara su propia clave privada localmente, y después enviar un ‘Certificate Signing Request’ (CSR) a la ‘key-signing machine’. A su vez, la ‘key-signing machine’ podrá procesar el CSR y devolver un certificado firmado al cliente. Esto se hará sin necesitar que el fichero confidencial ‘.key’ salga del máquina en la que ha sido generado.

Usando la Interfaz de Gestión

La Interfaz de Gestión de OpenVPN permite un gran control sobre los procesos de OpenVPN. La Interfaz de Gestión se usa directamente con un Telnet a un puerto determinado, o indirectamente usando un GUI de OpenVPN que a su vez se conecta a la Interfaz de Gestión.

Para habilitar la Interfaz de Gestión en un servidor o cliente OpenVPN, añade la siguiente linea al fichero de configuración:

  management localhost 7505

Esta línea le dice a OpenVPN que escuche en el puerto TCP 7505 conexiones cliente para la Interfaz de Gestión (el puerto 7505 es una elección arbitraria – puedes usar cualquier puerto libre).

Una vez que se está ejecutando OpenVPN , podrás conectar a la Interfaz de Gestión usando un cliente telnet. Por ejemplo:

  # telnet localhost 7505
  Trying 127.0.0.1...
  Connected to localhost.
  Escape character is '^]'.
  >INFO:OpenVPN Management Interface Version 1 -- type 'help' for more info
  help
  Management Interface for OpenVPN 2.0_rc14 i686-suse-linux [SSL] [LZO] [EPOLL] built on Feb 15 2005
  Commands:
  echo [on|off] [N|all]  : Like log, but only show messages in echo buffer.
  exit|quit              : Close management session.
  help                   : Print this message.
  hold [on|off|release]  : Set/show hold flag to on/off state, or
                           release current hold and start tunnel.
  kill cn                : Kill the client instance(s) having common name cn.
  kill IP:port           : Kill the client instance connecting from IP:port.
  log [on|off] [N|all]   : Turn on/off realtime log display
                           + show last N lines or 'all' for entire history.
  mute [n]               : Set log mute level to n, or show level if n is absent.
  net                    : (Windows only) Show network info and routing table.
  password type p        : Enter password p for a queried OpenVPN password.
  signal s               : Send signal s to daemon,
                           s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.
  state [on|off] [N|all] : Like log, but show state history.
  status [n]             : Show current daemon status info using format #n.
  test n                 : Produce n lines of output for testing/debugging.
  username type u        : Enter username u for a queried OpenVPN username.
  verb [n]               : Set log verbosity level to n, or show if n is absent.
  version                : Show current version number.
  END
  

Expandiento el ambito de la VPN para incluir máquinas adicionales tanto en la subred de cliente o servidor

Incluyendo múltiples maquinas en la parte del servidor usando una VPN enrutada (dev tun)

una vez que la VPN está funcionando entre cliente y servidor, puede ser deseable expandir el ambito de la VPN para que los clientes alcancen múltiples máquinas en la red del servidor, en lugar unicamente del servidor porpiamente dicho.

para este ejemplo, asumiremos que la parte LAN del servidor LAN usa una subred 192.168.0.0/24 y el rango de direcciones IP que usa la VPN es 172.16.0.0/24 as cited in the server directive in the OpenVPN server configuration file.

First, you must advertise the 10.66.0.0/24 subnet to VPN clients as being accessible through the VPN. This can easily be done with the following server-side config file directive:

  push "route 10.66.0.0 255.255.255.0"

Next, you must set up a route on the server-side LAN gateway to route the VPN client subnet (10.8.0.0/24) to the OpenVPN server (this is only necessary if the OpenVPN server and the LAN gateway are different machines).

Make sure that you’ve enabled IP and TUN/TAP forwarding on the OpenVPN server machine.

Including multiple machines on the client side when using a routed VPN (dev tun)

In a typical road-warrior or remote access scenario, the client machine connects to the VPN as a single machine. But suppose the client machine is a gateway for a local LAN (such as a home office), and you would like each machine on the client LAN to be able to route through the VPN.

For this example, we will assume that the client LAN is using the 192.168.4.0/24 subnet, and that the VPN client is using a certificate with a common name of client2. Our goal is to set up the VPN so that any machine on the client LAN can communicate with any machine on the server LAN through the VPN.

Before setup, there are some basic prerequisites which must be followed:

  • The client LAN subnet (192.168.4.0/24 in our example) must not be exported to the VPN by the server or any other client sites which are using the same subnet. Every subnet which is joined to the VPN via routing must be unique.
  • The client must have a unique Common Name in its certificate (”client2” in our example), and the duplicate-cn flag must not be used in the OpenVPN server configuration file.

First, make sure that IP and TUN/TAP forwarding is enabled on the client machine.

Next, we will deal with the necessary configuration changes on the server side. If the server configuration file does not currently reference a client configuration directory, add one now:

  client-config-dir ccd

In the above directive, ccd should be the name of a directory which has been pre-created in the default directory where the OpenVPN server daemon runs. On Linux this tends to be /etc/openvpn and on Windows it is usually \Program Files\OpenVPN\config. When a new client connects to the OpenVPN server, the daemon will check this directory for a file which matches the common name of the connecting client. If a matching file is found, it will be read and processed for additional configuration file directives to be applied to the named client.

The next step is to create a file called client2 in the ccd directory. This file should contain the line:

  iroute 192.168.4.0 255.255.255.0

This will tell the OpenVPN server that the 192.168.4.0/24 subnet should be routed to client2.

Next, add the following line to the main server config file (not the ccd/client2 file):

  route 192.168.4.0 255.255.255.0

Why the redundant route and iroute statements, you might ask? The reason is that route controls the routing from the kernel to the OpenVPN server (via the TUN interface) while iroute controls the routing from the OpenVPN server to the remote clients. Both are necessary.

Next, ask yourself if you would like to allow network traffic between client2’s subnet (192.168.4.0/24) and other clients of the OpenVPN server. If so, add the following to the server config file.

  client-to-client
  push "route 192.168.4.0 255.255.255.0"

This will cause the OpenVPN server to advertise client2’s subnet to other connecting clients.

The last step, and one that is often forgotten, is to add a route to the server’s LAN gateway which directs 192.168.4.0/24 to the OpenVPN server box (you won’t need this if the OpenVPN server box is the gateway for the server LAN). Suppose you were missing this step and you tried to ping a machine (not the OpenVPN server itself) on the server LAN from 192.168.4.8? The outgoing ping would probably reach the machine, but then it wouldn’t know how to route the ping reply, because it would have no idea how to reach 192.168.4.0/24. The rule of thumb to use is that when routing entire LANs through the VPN (when the VPN server is not the same machine as the LAN gateway), make sure that the gateway for the LAN routes all VPN subnets to the VPN server machine.

Similarly, if the client machine running OpenVPN is not also the gateway for the client LAN, then the gateway for the client LAN must have a route which directs all subnets which should be reachable through the VPN to the OpenVPN client machine.


Navigation


FOTOGRAFIAS

www.flickr.com
Esta ventana muestra fotos de joakinen. Hazte una igual aquí.


VIAJES
http://itineraria.org

CURSOS
http://ctx.es

BLOG http://creativecodeworks.com/blog

Personal Tools