Configuracin de un servidor OpenVPN en Ubuntu (versin 10.
10)
Primero Obtenemos datos de configuracin para dicha tarea. Nuestra LAN donde se encontrar nuestro servidor OpenVPN server ip: :192.168.1.106 submascara: 255.255.0.0 gateway: 192.168.1.254 Asignar rango de red virtual que crearemos para los usuarios VPN: ip: 192.168.30.0 submascara: 255.255.255.0 Entrar como usuario root. 1.instalar apt-get install openvpn 2. configurar cp -a /usr/share/doc/openvpn/examples/easy-rsa/2.0/ /etc/openvpn/ cd /etc/openvpn/2.0/ gedit vars 3. en el archivo vars localizar: export KEY_COUNTRY="US" export KEY_PROVINCE="CA" export KEY_CITY="SanFrancisco" export KEY_ORG="Fort-Funston" export KEY_EMAIL="me myhost.mydomain" cambiar por lo personalizado: export KEY_COUNTRY="MX" export KEY_PROVINCE="MX" export KEY_CITY="Mexico" export KEY_ORG="Maticorp" export KEY_EMAIL="[email protected]" #DATE CUENTA que en pas pones las abreviaciones de tu pas y lo dems es personalizado guardar archivo y salir
4. inicializar variables de ambiente con: source ./vars #y ./clean-all 5. ejecutar vars: root S1:/etc/openvpn/2.0# ./vars NOTE: If you run ./clean-all, I will be doing a rm -rf on /etc/openvpn/2.0/key 5. si es la primera vez , o desea eliminar todas las llaves: ./clean-all 6. generamos certificaciones: root S1:/etc/openvpn/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) [MX]: damos puros enters: Country Name (2 letter code) [MX]: State or Province Name (full name) [MX]: Locality Name (eg, city) [Mexico]: Organization Name (eg, company) [Maticorp]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [Maticorp]: Name []: Email Address [[email protected]]: 7. ahora creamos llave de servidor (las tericamente llamadas llaves pblicas): root S1:/etc/openvpn/2.0# ./build-key-server servidor Generating a 1024 bit RSA private key
.......++++++ ..................++++++ writing new private key to 'servidor.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) [MX]: State or Province Name (full name) [MX]: Locality Name (eg, city) [Mexico]: Organization Name (eg, company) [Maticorp]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [servidor]: Name []: Email Address [[email protected]]: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: personalizar con la contrasea elegida y repetirla cada que la solicite (en este caso maticorp) Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:maticorp An optional company name []: Using configuration from /etc/openvpn/2.0/openssl.cnf Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows countryName :PRINTABLE:'MX' stateOrProvinceName :PRINTABLE:'MX' localityName :PRINTABLE:'Mexico' organizationName :PRINTABLE:'Maticorp' commonName :PRINTABLE:'servidor' emailAddress :IA5STRING:'[email protected]' Certificate is to be certified until Aug 17 21:04:51 2020 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 root S1:/etc/openvpn/2.0#
8. copiar llaves creadas (OBSERVEMOS: que se trata de las llaves pblicas del servidor y que las estamos copiando al directorio de configuracin del openvpn) root S1:/etc/openvpn/2.0# cd keys/ root S1:/etc/openvpn/2.0/keys# ls 01.pem ca.key index.txt.attr serial servidor.crt servidor.key ca.crt index.txt index.txt.old serial.old servidor.csr root S1:/etc/openvpn/2.0/keys# cp servidor.crt servidor.key /etc/openvpn/ 9. generar llaves de clientes ejemplo: root S1:/etc/openvpn/2.0# ./build-key cliente1 Generating a 1024 bit RSA private key .......++++++ ...++++++ writing new private key to 'cliente1.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) [MX]: #TENER en cuenta que el challenge password debe ser el mismo que el del servidor (maticorp) 9. correr parametros Diffie-Hellman root S1:/etc/openvpn/2.0# ./build-dh Generating DH parameters, 1024 bit long safe prime, generator 2 This is going to take a long time ...+..................................................................+........ +.............................................................................................................+.................+........................... +....................................+..........................+................................................................+........... +...............................+....+.....................................................+............................................................... +...............................+...+........+....................... +.............................................................................................................+.....+............+...... +......................................................................................................................................................... +...........................................+..................................+...+............................................ +..........................................................................+..+.........................................+..................................... +...................................................+.............+.....+............ +................................................................................................................ +............................................................................................................................................................... +....+...................+................+.............+...........+...............+............................ +.................................................+.............
+............................................................................................................+................+................. +.....................................................................+..................+..........+................................. +................................................................................................................................................................... ....................................................................................................................................... +..................................................................................................+......................................+.. +...............................+..+................................+...................................+..................................... +.......................+.......................+............................................................+................. +........................................................................................................++*++*++* 11. copiar: root S1:/etc/openvpn/2.0# cd keys/ root S1:/etc/openvpn/2.0/keys# ls 01.pem ca.key index.txt.attr serial servidor.csr cliente1.csr 02.pem dh1024.pem index.txt.attr.old serial.old servidor.key cliente1.key ca.crt index.txt index.txt.old servidor.crt cliente1.crt root S1:/etc/openvpn/2.0/keys# cp ca.crt ca.key servidor.crt servidor.key dh1024.pem /etc/openvpn/ 12. creamos en /etc/openvpn gedit servidor.conf y agregamos estas lneas: dev tun persist-tun ca ca.crt cert servidor.crt key servidor.key dh dh1024.pem server 192.168.30.0 255.255.255.0 route add 192.168.1.0 255.255.255.0 //o la subred que se tiene que ver push "route 192.168.1.0 255.255.0.0" la ruta de la subred ifconfig-pool-persist ipp.txt client-to-client keepalive 10 120 comp-lzo user nobody group nogroup persist-key persist-tun status openvpn-status.log verb 4 #OBSERVEMOS: server corresponde a la red y mscara virtual que se crear para los usuarios vpn y en push "route 192.168.1.0 255.255.255.0" lo que declaramos fue el inicio de nuestra red lan. donde reside fsicamente el openvpn server
13. editar el archivo /etc/default/openvpn con gedit y descomentar AUTOSTART="none" cambiarlo ademas por el nombre de servidor AUTOSTART="servidor" #OBSERVACION: asignamos le nombre de nuestro servidor openvpn , si decidiste desde el inicio poner otro nombre a tu server vpn , entonces aqu debe ir ese dato 14.aplicar echo: root S1:/etc/default# echo 1 > /proc/sys/net/ipv4/ip_forward 15. modificar iptables.: root S1:/etc/default# cd /etc/ root S1:/etc# gedit rc.local #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. modprobe iptable_nat iptables -A FORWARD -o tun0 -j ACCEPT iptables -t nat -A POSTROUTING -o eth0 -s 10.5.1.0/255.255.255.0 -j MASQUERADE iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE exit 0 16. editar gedit /etc/sysctl.conf: localizar # Uncomment the next line to enable packet forwarding for IPv4 #net.ipv4.ip_forward=1 y descomentar
quedando: # Uncomment the next line to enable packet forwarding for IPv4 net.ipv4.ip_forward=1 17. reiniciar servidor openvpn: root S1:/var/log# /etc/init.d/openvpn restart Stopping virtual private network daemon(s)... * No VPN is running. Starting virtual private network daemon(s)... * Autostarting VPN 'servidor'
18. por ltimo comprobamos con grep que todo est funcionando bien (si no es as , revisar la configuracin , hubo algo que quedo mal , si no localizas a simple vista el error , verifica el log de archivos del sistema) root S1:/var/log# ps -ef|grep openvpn nobody 7754 1 0 16:52 ? 00:00:00 /usr/sbin/openvpn --writepid /var/run/openvpn.servidor.pid --daemon ovpn-servidor --cd /etc/openvpn --config /etc/openvpn/servidor.conf --script-security 2 root 7760 6752 0 16:54 pts/1 00:00:00 grep --color=auto openvpn root S1:/var/log# Aqu termina la configuracin del servidor OpenVPN en Ubuntu.
Configuracin del cliente OpenVPN en Windows
Lo primero es descargar el OpenVPN para Windows, una vez instalado, lo que tenemos que hacer es ir directamente a la carpeta de instalacin del programa, que por defecto es C:\Archivos de Programa\OpenVPN\config\ y estando all dentro de config hacemos lo siguiente: De la carpeta OpenVPN\sample-config\ Copiaremos el archivo cliente, y lo pegaremos en OpenVPN\config\. Luego de esto abrimos el archivo cliente con el bloc de notas. Debe de quedar como el siguiente: Nota: Lo marcado en texto cursiva es lo que habr de remplazarse por los valores correctos. ############################################## # Sample client-side OpenVPN 2.0 config file # # for connecting to multi-client server. # # # # This configuration can be used by multiple # # clients, however each client should have # # its own cert and key files. # # # # On Windows, you might want to rename this # # file so it has a .ovpn extension # ############################################## # Specify that we are a client and that we # will be pulling certain config file directives # from the server. client # Use the same setting as you are using on # the server. # On most systems, the VPN will not function # unless you partially or fully disable # the firewall for the TUN/TAP interface. ;dev tap dev tun # Windows needs the TAP-Win32 adapter name # from the Network Connections panel # if you have more than one. On XP SP2, # you may need to disable the firewall # for the TAP adapter. ;dev-node MyTap # Are we connecting to a TCP or # UDP server? Use the same setting as # on the server. ;proto tcp
proto udp # The hostname/IP and port of the server. # You can have multiple remote entries # to load balance between the servers. remote 189.144.17.19 1194 ;remote my-server-2 1194 # Choose a random host from the remote # list for load-balancing. Otherwise # try hosts in the order specified. ;remote-random float # Keep trying indefinitely to resolve the # host name of the OpenVPN server. Very useful # on machines which are not permanently connected # to the internet such as laptops. resolv-retry infinite # Most clients don't need to bind to # a specific local port number. nobind # Downgrade privileges after initialization (non-Windows only) ;user nobody ;group nobody # Try to preserve some state across restarts. persist-key persist-tun # If you are connecting through an # HTTP proxy to reach the actual OpenVPN # server, put the proxy server/IP and # port number here. See the man page # if your proxy server requires # authentication. ;http-proxy-retry # retry on connection failures ;http-proxy [proxy server] [proxy port #] # Wireless networks often produce a lot # of duplicate packets. Set this flag # to silence duplicate packet warnings. ;mute-replay-warnings # SSL/TLS parms. # See the server config file for more
# description. It's best to use # a separate .crt/.key file pair # for each client. A single ca # file can be used for all clients. ca ca.crt cert cliente1.crt key cliente1.key # Verify server certificate by checking # that the certicate has the nsCertType # field set to "server". This is an # important precaution to protect against # a potential attack discussed here: # http://openvpn.net/howto.html#mitm # # To use this feature, you will need to generate # your server certificates with the nsCertType # field set to "server". The build-key-server # script in the easy-rsa folder will do this. ns-cert-type server # If a tls-auth key is used on the server # then every client must also have the key. ;tls-auth ta.key 1 # Select a cryptographic cipher. # If the cipher option is used on the server # then you must also specify it here. ;cipher x # Enable compression on the VPN link. # Don't enable this unless it is also # enabled in the server config file. comp-lzo # Set log file verbosity. verb 3 # Silence repeating messages ;mute 20 #Usar TAP ;dev tap
Configuracin del cliente OpenVPN en Linux (Ubuntu 10.10)
Bajar Openvpn de la siguiente forma: user@localhost~#sudo apt-get install openvpn Con el paquete ya instalado tienes que pedirle al administrador de VPN que te entregue los cuatro archivos de configuracin que genera el servidor de VPN, que son las llaves de acceso y cuyas extensiones son crt, key y conf (por ejemplo, llave.conf, ca.crt, cliente1.crt y cliente1.key), Posteriormente, hacer los siguientes pasos: user@localhost~#sudo addgroup nobody (si es que no existe) Regresar al usuario comn y creas una carpeta oculta, as: user@localhost~$mkdir .openvpn/ Ahora los archivos que te entreg el administrador de la VPN los copias en esta carpeta excepto el de la extensin conf, este lo copias en /etc/openvpn. Verifica que el archivo de configuracin este bien, este debe contener lo siguiente: Nota: Modificar los valores que estn en cursiva con los valores correctos. ############################################## # Sample client-side OpenVPN 2.0 config file # # for connecting to multi-client server. # # # # This configuration can be used by multiple # # clients, however each client should have # # its own cert and key files. # # # # On Windows, you might want to rename this # # file so it has a .ovpn extension # ############################################## # Specify that we are a client and that we # will be pulling certain config file directives # from the server. client # Use the same setting as you are using on # the server. # On most systems, the VPN will not function # unless you partially or fully disable # the firewall for the TUN/TAP interface. ;dev tap
dev tun # Windows needs the TAP-Win32 adapter name # from the Network Connections panel # if you have more than one. On XP SP2, # you may need to disable the firewall # for the TAP adapter. ;dev-node MyTap # Are we connecting to a TCP or # UDP server? Use the same setting as # on the server. ;proto tcp proto udp # The hostname/IP and port of the server. # You can have multiple remote entries # to load balance between the servers. remote 189.144.17.19 1194 ;remote my-server-2 1194 # Choose a random host from the remote # list for load-balancing. Otherwise # try hosts in the order specified. ;remote-random float # Keep trying indefinitely to resolve the # host name of the OpenVPN server. Very useful # on machines which are not permanently connected # to the internet such as laptops. resolv-retry infinite # Most clients don't need to bind to # a specific local port number. nobind # Downgrade privileges after initialization (non-Windows only) ;user nobody ;group nobody # Try to preserve some state across restarts. persist-key persist-tun # If you are connecting through an # HTTP proxy to reach the actual OpenVPN # server, put the proxy server/IP and
# port number here. See the man page # if your proxy server requires # authentication. ;http-proxy-retry # retry on connection failures ;http-proxy [proxy server] [proxy port #] # Wireless networks often produce a lot # of duplicate packets. Set this flag # to silence duplicate packet warnings. ;mute-replay-warnings # SSL/TLS parms. # See the server config file for more # description. It's best to use # a separate .crt/.key file pair # for each client. A single ca # file can be used for all clients. ca /home/racortes/.openvpn/ca.crt cert /home/racortes/.openvpn/cliente1.crt key /home/racortes/.openvpn/cliente1.key # Verify server certificate by checking # that the certicate has the nsCertType # field set to "server". This is an # important precaution to protect against # a potential attack discussed here: # http://openvpn.net/howto.html#mitm # # To use this feature, you will need to generate # your server certificates with the nsCertType # field set to "server". The build-key-server # script in the easy-rsa folder will do this. ns-cert-type server # If a tls-auth key is used on the server # then every client must also have the key. ;tls-auth ta.key 1 # Select a cryptographic cipher. # If the cipher option is used on the server # then you must also specify it here. ;cipher x # Enable compression on the VPN link. # Don't enable this unless it is also # enabled in the server config file. comp-lzo
# Set log file verbosity. verb 3 # Silence repeating messages ;mute 20 #Usar TAP ;dev tap
Conexin de la VPN en Linux por primera vez (modo lnea de comandos)
Verificamos que el demonio de openvpn est corriendo. En caso de que no estemos seguros, damos la orden a travs de la lnea de comandos: user@localhost~#sudo /etc/init.d/openvpn start o tambin user@localhost~#sudo /etc/init.d/openvpn restart Para conectar a la VPN solo dar el comando user@localhost~#sudo openvpn llave.conf Nota1: En esta caso el archivo de configuracin se llama llave.conf, en cualquier otro caso, dar el nombre del archivo correspondiente). Nota 2: Cuando la conexin sea exitosa, la terminal que se us para conectar la VPN quedar bloqueada. Verificando lo anterior, la VPN debe funcionar. Para probarla, dar el comando route -n y con eso veremos las redes a las que puede acceder o utilizaremos el comando ifconfig -a y deberemos ver una tarjeta ms con el nombre tun0.
Desconexin de la VPN en Linux (modo lnea de comandos)
Para salir de la VPN, abrir una terminal y teclear el siguiente comando: user@localhost~#sudo /etc/init.d/openvpn stop Esto desconectar la VPN y eliminar el tnel y las rutas creadas.
Conexin de la VPN despus de configurada y probada en Linux (modo lnea de comandos)
Despus de que se configur la VPN como se describi lneas arriba, slo basta con iniciar el demonio para conectarse a la VPN con el siguiente comando: user@localhost~#sudo /etc/init.d/openvpn start *Starting Virtual Private Network daemon(s)... *Autostarting VPN 'llave'
[OK]
Eliminacin de una VPN creada por el mtodo anterior en Linux (modo lnea de comandos)
Bastar con eliminar el archivo de configuracin de la VPN creado con anterioridad. Usar el siguiente comando: user@localhost~#sudo rm -i /etc/openvpn/llave.conf donde llave.conf es el nombre del archivo de configuracin que hemos utilizado en el ejemplo. Sustituir por el nombre real. Nota: De preferencia, apagar el demonio de openvpn antes de realizar esta accin (ver procedimiento Desconexin de la VPN en Linux, mencionada en este mismo documento).