This is an old revision of the document!
Table of Contents
OpenVPN
Routed VPN
Esta configuración nos permite conectividad punto a punto entre los distintos clientes y el servidor VPN
http://openvpn.net/index.php/open-source/documentation/howto.html#quick
1. Instalar el paquete, tanto en el servidor como en todos los clientes.
sudo aptitude install openvpn openssl
2. Generate the master Certificate Authority (CA) certificate & key
cd /usr/share/doc/openvpn/examples/easy-rsa/2.0 sudo su vim vars
... export KEY_COUNTRY="ES" export KEY_PROVINCE="BC" export KEY_CITY="Barcelona" export KEY_ORG="Jamgo" export KEY_EMAIL="info@jamgo.es" export KEY_EMAIL=info@jamgo.es export KEY_CN=cn export KEY_NAME=name export KEY_OU=IT ...
source ./vars ./clean-all ./build-ca
3. Generate certificate & key for server
./build-key-server server
4. Generate certificates & keys for a client
./build-key client1
5. Generate Diffie Hellman parameters
./build-dh
6. Mover llaves
6.1 Servidor (todavia como root)
mkdir -p /etc/openvpn/keys/server cd /usr/share/doc/openvpn/examples/easy-rsa/2.0 cp keys/ca.crt /etc/openvpn/keys/server; mv keys/server.* /etc/openvpn/keys/server; mv keys/client1.* /etc/openvpn/keys/ ; mv keys/dh1024.pem /etc/openvpn/keys/server
6.2 Cliente
cd /etc/openvpn/keys tar cvfj client1.tar.bz2 client1.key client1.crt ca.crt scp client1.tar.bz2 user@client.machine.com:/tmp/ rm -fr client1.tar.bz2
On the client machine:
sudo su mkdir /etc/openvpn/company1 mv /tmp/client1.tar.bz2 /etc/openvpn/company1 cd /etc/openvpn/company1 tar xvfj client1.tar.bz2
7. Creating configuration files for server and clients
7.1 Server
cd /usr/share/doc/openvpn/examples/sample-config-files cp server.conf.gz /etc/openvpn/ cd /etc/openvpn/; gzip -d server.conf.gz vim server.conf
... ca /etc/openvpn/keys/ca.crt cert /etc/openvpn/keys/server.crt key /etc/openvpn/keys/server.key dh /etc/openvpn/keys/dh1024.pem client-to-client user nobody group nogroup crl-verify /etc/openvpn/crl.pem ...
Creamos el archivo vacío donde se almacenarán los certificados revocados:
sudo touch /etc/openvpn/crl.pem
7.2 Client
On the client machine:
cd /usr/share/doc/openvpn/examples/sample-config-files cp client.conf /etc/openvpn/company1.conf vim /etc/openvpn/company1.conf
... ca /etc/openvpn/company1/ca.crt cert /etc/openvpn/company1/client1.crt key /etc/openvpn/company1/client1.key remote vpn.server.com 1194 ...
IMPORTANTE: hay variables que tienen que ser idénticas en el archivo de configuración del servidor y de todos los clientes, como “port”, “proto”, etc…
8. Starting up the VPN and testing for initial connectivity
8.1 (Opcional) Abrir el puerto y protocolo definido en el archivo de configuración en el firewall (UDP 1194 por defecto)
8.2 (Opcional) Si se quiere que los clientes puedan acceder además de al servidor VPN a otras máquinas que estén en la red privada (LAN) de éste, y si el gateway de esa LAN NO es el servidor VPN, en el servidor VPN hay que activar masquerade.
8.3 Arrancar:
sudo /etc/init.d/openvpn start
Acceso desde el cliente a la LAN del servidor VPN (gateway de la LAN y servidor VPN son distintos)
Queremos que desde el cliente se llegue no solo al servidor VPN, sino también a la LAN de ese servidor. La particularidad es que el servidor VPN es una máquina virtual detrás de un Hipervisor KVM. Además el Hipervisor KVM está detrás de un router ADSL casero en modo DMZ, de forma que TODO el tráfico lo redirige hacia el Hipervisor.
Resumen:
Máquina | Interfaz | IP | Comentario |
---|---|---|---|
Cliente | wlan0 | 192.168.1.100 | LAN doméstica. Se conecta al router que le da salida a internet |
Cliente | tun0 | 172.16.0.6 | Red VPN |
Servidor VPN | eth0 | 10.0.0.11 | LAN corporativa (VM de KVM) |
Servidor VPN | tun0 | 172.16.0.1 | Red VPN |
Hipervisor KVM | p5p1 | 192.168.1.4 | LAN que se conecta al router que le da salida a internet |
Hipervisor KVM | virbr0 | 10.0.0.1 | LAN corporativa (Hipervisor de KVM) |
Servidor destino | eth0 | 10.0.0.12 | LAN corporativa (VM de KVM) |
El objetivo es conectarse de la siguiente manera:
[Cliente] → [Hipervisor KVM] → [Servidor VPN] → [Servidor destino]
1. (Servidor VPN) Anunciar a los clientes la ruta a la que se pueden conectar, y si es menester, reiniciar el servicio VPN:
sudo vim /etc/openvpn/server.conf
... push "route 10.0.0.0 255.255.255.0" ...
sudo /etc/init.d/openvpn restart
2. (Servidor VPN) Crear el guión para el enrutado de tráfico y hacer que se ejecute al arrancar el servidor:
vim /home/ubuntu/firewall_on.sh
#!/bin/bash IPTABLES=/sbin/iptables # Borrado de reglas de iptables $IPTABLES -P INPUT ACCEPT $IPTABLES -F INPUT $IPTABLES -P OUTPUT ACCEPT $IPTABLES -F OUTPUT $IPTABLES -P FORWARD ACCEPT $IPTABLES -F FORWARD $IPTABLES -t nat -F $IPTABLES -t filter -F $IPTABLES -t mangle -F # Interfaces LAN_IF="eth0" VPN_IF="tun0" LO_IF="lo" #CRÍTICO: habilitar redirección IPv4, deshabilitado por defecto echo "1" > /proc/sys/net/ipv4/ip_forward $IPTABLES -t nat -A POSTROUTING -o $LAN_IF -j MASQUERADE
chmod +x /home/ubuntu/firewall_on.sh cd /etc/init.d sudo ln -s /home/ubuntu/firewall_on.sh sudo update-rc.d firewall_on.sh defaults
3. (Hipervisor KVM) Crear el guión para el enrutado de tráfico y hacer que se ejecute al arrancar el servidor:
vim /home/ubuntu/firewall_on.sh
#!/bin/bash IPTABLES=/sbin/iptables # Borrado de reglas de iptables $IPTABLES -P INPUT ACCEPT $IPTABLES -F INPUT $IPTABLES -P OUTPUT ACCEPT $IPTABLES -F OUTPUT $IPTABLES -P FORWARD ACCEPT $IPTABLES -F FORWARD $IPTABLES -t nat -F $IPTABLES -t filter -F $IPTABLES -t mangle -F # Interfaces VIRT_IF="virbr0" EXT_IF="p5p1" LO_IF="lo" KVM_LAN_IP="192.168.1.4" VM="10.0.0.0/24" KVM_VM_IP="10.0.0.1" # VPN VPN_VM="10.0.0.11" VPN_NET="172.16.0.0/24" VPN_PROTOCOL="udp" VPN_PORT="1193" # KVM $IPTABLES -A INPUT -i $VIRT_IF -p udp -m udp --dport 53 -j ACCEPT $IPTABLES -A INPUT -i $VIRT_IF -p tcp -m tcp --dport 53 -j ACCEPT $IPTABLES -A INPUT -i $VIRT_IF -p udp -m udp --dport 67 -j ACCEPT $IPTABLES -A INPUT -i $VIRT_IF -p tcp -m tcp --dport 67 -j ACCEPT $IPTABLES -A FORWARD -d $VM -o $VIRT_IF -m state --state RELATED,ESTABLISHED -j ACCEPT $IPTABLES -t nat -A POSTROUTING -s $VM ! -d $VM -p tcp -j MASQUERADE --to-ports 1024-65535 $IPTABLES -t nat -A POSTROUTING -s $VM ! -d $VM -p udp -j MASQUERADE --to-ports 1024-65535 $IPTABLES -t nat -A POSTROUTING -s $VM ! -d $VM -j MASQUERADE # Forward traffic between VM's $IPTABLES -A FORWARD -i $VIRT_IF -o $VIRT_IF -s $VM -d $VM -j ACCEPT # Allow loop interface traffic $IPTABLES -A INPUT -i $LO_IF -j ACCEPT # ESTABLISHED $IPTABLES -A INPUT -d $KVM_LAN_IP -i $EXT_IF -m state --state RELATED,ESTABLISHED -j ACCEPT # VPN (OpenVPN) $IPTABLES -A INPUT -i $EXT_IF -d $KVM_LAN_IP -p $VPN_PROTOCOL --dport $VPN_PORT -j ACCEPT $IPTABLES -t nat -I PREROUTING -i $EXT_IF -p $VPN_PROTOCOL --dport $VPN_PORT -s $ANY -d $KVM_LAN_IP -j DNAT --to-destination $VPN_VM $IPTABLES -A FORWARD -i $EXT_IF -o $VIRT_IF -d $VPN_VM -p $VPN_PROTOCOL --dport $VPN_PORT -j ACCEPT $IPTABLES -A FORWARD -i $VIRT_IF -o $EXT_IF -s $VPN_VM -p $VPN_PROTOCOL --sport $VPN_PORT -j ACCEPT # VPN access to server's private LAN $IPTABLES -A FORWARD -i $VIRT_IF -o $VIRT_IF -s $VM -d $VPN_NET -j ACCEPT $IPTABLES -A FORWARD -i $VIRT_IF -o $VIRT_IF -s $VPN_NET -d $VM -j ACCEPT $IPTABLES -A FORWARD -i $VIRT_IF -o $EXT_IF -s $VM -d $VPN_NET -j ACCEPT
chmod +x /home/ubuntu/firewall_on.sh cd /etc/init.d sudo ln -s /home/ubuntu/firewall_on.sh sudo update-rc.d firewall_on.sh defaults
4. (Cliente) Reiniciar el cliente VPN y probar conectividad:
sudo /etc/init.d/openvpn restart ping 10.0.0.12
Configurar DNS en el cliente
Para que el cliente reciba del servidor VPN parámetros como servidor DNS o Dominio de búsqueda necesitamos configuración tanto en el servidor como en el cliente, y un script en el lado cliente. Si la máquina es Windows el script no es necesario.
Variables:
10.0.0.10 | Dirección Ip del servidor DNS |
local.jamgo.org | Sufijo de búsqueda DNS |
1. (Servidor) Editar:
sudo vim /etc/openvpn/server.conf
Y asegurarse que las siguientes lineas están presentes:
... push "dhcp-option DNS 10.0.0.10" push "dhcp-option DOMAIN local.jamgo.org" ...
2. (Servidor) Reiniciar el servicio OpenVPN:
sudo /etc/init.d/openvpn restart
3. (Cliente) Instalar el siguiente paquete:
sudo aptitude install resolvconf
4. (Cliente) Asegurarse que tenemos el siguiente archivo (viene con el paquete “openvpn”) y que es ejecutable:
/etc/openvpn/update-resolv-conf
Con el siguiente contenido:
#!/bin/bash # # Parses DHCP options from openvpn to update resolv.conf # To use set as 'up' and 'down' script in your openvpn *.conf: # up /etc/openvpn/update-resolv-conf # down /etc/openvpn/update-resolv-conf # # Used snippets of resolvconf script by Thomas Hood <jdthood@yahoo.co.uk> # and Chris Hanson # Licensed under the GNU GPL. See /usr/share/common-licenses/GPL. # # 05/2006 chlauber@bnc.ch # # Example envs set from openvpn: # foreign_option_1='dhcp-option DNS 193.43.27.132' # foreign_option_2='dhcp-option DNS 193.43.27.133' # foreign_option_3='dhcp-option DOMAIN be.bnc.ch' [ -x /sbin/resolvconf ] || exit 0 case $script_type in up) for optionname in ${!foreign_option_*} ; do option="${!optionname}" echo $option part1=$(echo "$option" | cut -d " " -f 1) if [ "$part1" == "dhcp-option" ] ; then part2=$(echo "$option" | cut -d " " -f 2) part3=$(echo "$option" | cut -d " " -f 3) if [ "$part2" == "DNS" ] ; then IF_DNS_NAMESERVERS="$IF_DNS_NAMESERVERS $part3" fi if [ "$part2" == "DOMAIN" ] ; then IF_DNS_SEARCH="$IF_DNS_SEARCH $part3" fi fi done R="" for SS in $IF_DNS_SEARCH ; do R="${R}search $SS " done for NS in $IF_DNS_NAMESERVERS ; do R="${R}nameserver $NS " done echo -n "$R" | /sbin/resolvconf -a "${dev}.inet" ;; down) /sbin/resolvconf -d "${dev}.inet" ;; esac
5. (Cliente) Editar:
sudo vim /etc/openvpn/cliente.conf
Y asegurarse que las siguientes lineas están presentes:
... script-security 2 up /etc/openvpn/update-resolv-conf down /etc/openvpn/update-resolv-conf ...
6. (Cliente) Reiniciar el servicio OpenVPN:
sudo /etc/init.d/openvpn restart
7. (Cliente) Comprobar los cambios:
cat /etc/resolv.conf
Debería aparecer la configuración especificada en el paso 1):
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 10.0.0.10 search local.jamgo.org
Revocar certificados
http://openvpn.net/index.php/open-source/documentation/howto.html#revoke
1. Comprobar que el certificado a revocar (“usuario.cert” en este ejemplo) se encuentra en el siguiente directorio:
/usr/share/doc/openvpn/examples/easy-rsa/2.0/keys
2. Revocarlo
sudo su cd /usr/share/doc/openvpn/examples/easy-rsa/2.0 . ./vars ./revoke-full usuario
Salida esperada:
Using configuration from /root/openvpn/20/openvpn/tmp/easy-rsa/openssl.cnf DEBUG[load_index]: unique_subject = "yes" Revoking Certificate 04. Data Base Updated Using configuration from /root/openvpn/20/openvpn/tmp/easy-rsa/openssl.cnf DEBUG[load_index]: unique_subject = "yes" client2.crt: /C=KG/ST=NA/O=OpenVPN-TEST/CN=client2/emailAddress=me@myhost.mydomain error 23 at 0 depth lookup:certificate revoked
El “error 23” al final es normal
3. Actualizar la lista de certificads revocados (se encuentra en la ruta especificada en el parámetro “crl-verify” del archivo de configuración del servidor):
cat /usr/share/doc/openvpn/examples/easy-rsa/2.0/keys/crl.pem » /etc/openvpn/crl.pem
4. Supongo que tiene sentido reiniciar/recargar openvpn:
sudo /etc/init.d/openvpn reload
5. La siguiente vez que se intente conectar el usuario “usuario” no podrá hacerlo, y aparecerán las siguientes entradas en los logs:
Cliente
Fri Apr 5 19:27:06 2013 Connection reset, restarting [0] Fri Apr 5 19:27:06 2013 TCP/UDP: Closing socket Fri Apr 5 19:27:06 2013 SIGUSR1[soft,connection-reset] received, process restarting Fri Apr 5 19:27:06 2013 Restart pause, 5 second(s)
Servidor
Fri Apr 5 19:01:02 2013 31.4.107.170:35244 CRL CHECK FAILED: /C=ES/ST=BC/L=Barcelona/O=Jamgo/OU=IT/CN=toberevoked/name=To_Be_Revoked/emailAddress=toberevoked@jamgo.es is REVOKED
Receta 2 (parcialmente incompleta)
Instalar OPENVPN
# apt-get install openvpn
Crear certificados
Generar la CA para firmar los certificados
Copiamos el directorio de ejemplo en la carpeta de configuración de OpenVPN:
#/usr/share/doc/openvpn/examples# cp -R easy-rsa/ /etc/openvpn/
Editamos:
donquixot:/etc/openvpn/easy-rsa/2.0# vi vars
export KEY_COUNTRY="ES" export KEY_PROVINCE="BC" export KEY_CITY="Mataro" export KEY_ORG="Lobo99" export KEY_EMAIL="jose@lobo99.com"
donquixot:/etc/openvpn/easy-rsa/2.0# source ./vars donquixot:/etc/openvpn/easy-rsa/2.0# ./clean-all donquixot:/etc/openvpn/easy-rsa/2.0# ./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) [ES]: State or Province Name (full name) [BC]:Barcelona Locality Name (eg, city) [Mataro]: Organization Name (eg, company) [Lobo99]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [Lobo99 CA]:lobo99.com Name []: Email Address [jose@lobo99.com]:
Esto genera la CA:
donquixot:/etc/openvpn/easy-rsa/2.0/keys# ls -la total 6 drwx------ 2 root root 1024 Nov 6 21:21 . drwxr-xr-x 3 root root 1024 Nov 6 21:20 .. -rw-r--r-- 1 root root 1204 Nov 6 21:21 ca.crt -rw------- 1 root root 887 Nov 6 21:21 ca.key -rw-r--r-- 1 root root 0 Nov 6 21:20 index.txt -rw-r--r-- 1 root root 3 Nov 6 21:20 serial
Creación de Certificado y llaves para Servidor
donquixot:/etc/openvpn/easy-rsa/2.0# ./build-key-server server
Generating a 1024 bit RSA private key .................++++++ ............................++++++ writing new private key to 'server.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) [ES]: State or Province Name (full name) [BC]:Barcelona Locality Name (eg, city) [Mataro]: Organization Name (eg, company) [Lobo99]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [server]:lobo99.com Name []: Email Address [jose@lobo99.com]: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:OpenVpn lobo99.com An optional company name []: Using configuration from /etc/openvpn/easy-rsa/2.0/openssl.cnf Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows countryName :PRINTABLE:'ES' stateOrProvinceName :PRINTABLE:'Barcelona' localityName :PRINTABLE:'Mataro' organizationName :PRINTABLE:'Lobo99' commonName :PRINTABLE:'lobo99.com' emailAddress :IA5STRING:'jose@lobo99.com' Certificate is to be certified until Nov 3 20:25:25 2021 GMT (3650 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated
Generar Certificado para los clientes
./build-key client1 ./build-key client2
donquixot:/etc/openvpn/easy-rsa/2.0# ./build-key jose Generating a 1024 bit RSA private key ...............................++++++ ........++++++ writing new private key to 'jose.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) [ES]: State or Province Name (full name) [BC]:Barcelona Locality Name (eg, city) [Mataro]: Organization Name (eg, company) [Lobo99]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [jose]: Name []:Jose Email Address [jose@lobo99.com]: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:fermin99 An optional company name []: Using configuration from /etc/openvpn/easy-rsa/2.0/openssl.cnf Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows countryName :PRINTABLE:'ES' stateOrProvinceName :PRINTABLE:'Barcelona' localityName :PRINTABLE:'Mataro' organizationName :PRINTABLE:'Lobo99' commonName :PRINTABLE:'jose' name :PRINTABLE:'Jose' emailAddress :IA5STRING:'jose@lobo99.com' Certificate is to be certified until Nov 3 20:30:04 2021 GMT (3650 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated
Generate Diffie Hellman parameters
Diffie Hellman parameters must be generated for the OpenVPN server. On Linux/BSD/Unix:
./build-dh
Ficheros de configuración
donquixot:/etc/openvpn# cp -R /usr/share/doc/openvpn/examples/sample-config-files/ config-files
Habilitar para máquinas virtuales contenedores openvz
vzctl set 101 --devnodes net/tun:rw --save
Fuente: http://wiki.openvz.org/VPN_via_the_TUN/TAP_device
Copiamos ficheros de certificados:
cp -R /usr/share/doc/openvpn/examples/easy-rsa/ /etc/openvpn/
Habilitar IP fordwarding en el servidor:
# echo 1 > /proc/sys/net/ipv4/ip_forward
En el fichero de configuración del servidor, modificamos las siguientes opciones básicas:
server.conf
port 1194 proto udp dev tun ca ca.crt cert server.crt key server.key # This file should be kept secret dh dh1024.pem server 10.8.0.0 255.255.255.0 push "route 192.168.1.0 255.255.255.0" push "route 10.139.0.0 255.255.0.0"
El servidor se arranca con:
# openvpn server.conf
En la parte del cliente, pasamos los ficheros de certificados y el de configuración client.conf
El cliente se conecta con:
# openvpn clien.conf
Para acceder a las subredes, está tiene que enrutar hacía la subred del vpn, en este caso la 10.8.0.0
He añadido la ruta 10.8.0.0 a la miktorik y un nat para que vuelva:
ip > firewall
General Chain: srcnat Src.Address: 10.8.0.0/24
Action Action: src-nat To Addresses: 10.139.56.129
Y la ruta 10.8.0.0/24 → 10.139.67.103 (ip del servidor vpn)
Autenticación LDAP
/etc/openvpn/auth/auth-ldap.conf
URL ldaps://ldap.guifi.net/ <Authorization> # Base DN BaseDN "dc=guifi,dc=net" # User Search Filter SearchFilter "(&(uid=%u)(accountStatus=active))" # Require Group Membership RequireGroup false # Add non-group members to a PF table (disabled) #PFTable ips_vpn_users <Group> BaseDN "o=proxyusers,dc=guifi,dc=net" SearchFilter "(|(cn=developers)(cn=artists))" MemberAttribute uniqueMember # Add group members to a PF table (disabled) #PFTable ips_vpn_eng </Group> </Authorization>