Vpnc

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Vpnc and the translation is 54% complete.

Other languages:
English • ‎español • ‎русский • ‎日本語 • ‎한국어

Este documento detalla como conectar una estación de trabajo a un concentrador VPN Cisco utilizando vpnc para gestionar la conexión

Introducción

Este documento está orientado a usuarios que quieren conectarse a la red de su oficina desde casa o durante un viaje. Muchas compañías utilizan concentradores VPN Cisco 3000 para las necesidades de VPN, y estoy dispuesto a apostar que los novatos de Linux piensan que están forzados a usar Windows para conectarse a ellas. Bueno, este documento explica que la conexión a las VPN de Cisco es definitivamente posible y seguramente podrá configurar un túnel productivo usando una estación de trabajo o portátil con Gentoo.

Que es este documento

  • Una guía para el trabajo básico de vpnc
  • Un debate sobre los problemas de VPN relativos a DNS y enrutamiento
  • Ejemplos de como gestionar sesiones VPN
  • Consejos y trucos útiles (esperemos)

Que no es este documento

  • Una guía profunda para tecnologías de VPN/encriptación
  • Una explicación característica a característica de vpnc

Supuestos

Las hipótesis formuladas en este punto son:

  • Gentoo está instalado
  • Se dispone de acceso a Internet y está correctamente configurado
  • Se realiza la conexión hacia un concentrador VPN Cisco 3000
  • El lector es capaz de configurar, construir e instalar un nuevo núcleo

Instalación

Núcleo

Para que Linux sea capaz de abrir una conexión VPN se debe habilitar en el núcleo la opción "Universal TUN/TAP device driver". ¿Que es y por que se necesita?. A continuación se muestra una explicación relativamente sencilla desde la opción de configuración del núcleo.

CÓDIGO Habilitar el controlador de dispositivo TUN/TAP (CONFIG_TUN)
TUN/TAP provee la recepción  y transmisión de paquetes para programas que están en el espacio de usuario. Puede ser vista como un simple dispositivo Punto-a-Punto o Ethernet, que en vez de recibir paquetes desde un dispositivo físico, los recibe desde el programa ejecutado en el espacio de usuario y en vez de enviar paquetes via el dispositivo físico lo hace a través del programa en el espacio de usuarios.

Cuando un programa abre /dev/net/tun, un controlar crea y registra el correspondiente dispositivo de red tunX o tapX. Después un programa cierra los dispositivos, el controlador automáticamente borra los dispositivos tunXX o tapXX y todos las rutas correspondiente a este.

When a program opens /dev/net/tun, driver creates and registers corresponding net device tunX or tapX. After a program closed above devices, driver will automatically delete tunXX or tapXX device and all routes corresponding to it. }}

Para verificar que el núcleo dispone de soporte TUN/TAP, hacer grep en el fichero de configuración del núcleo:

root #grep "TUN" /usr/src/linux/.config
CONFIG_INET_TUNNEL=m
# CONFIG_INET6_TUNNEL is not set
# CONFIG_IPV6_TUNNEL is not set
(TUN/TAP enabled as a module)
CONFIG_TUN=m
# CONFIG_8139TOO_TUNE_TWISTER is not set

Como se puede ver arriba, Config_TUN=m está compilado como módulo. Si estuviera deshabilitado en la configuración, habilitar la opción en el núcleo, reconstruir, instalar, reiniciar y volver a este documento antes de continuar con los siguientes pasos.

KERNEL Ubicación de la configuración dentro del núcleo
Device Drivers  --->
  Network device support  --->
    [*] Universal TUN/TAP device driver support

Si se construye el soporte TUN/TAP directamente en el núcleo, la salida de la orden dmesg debería ser similar a la siguiente:

root #dmesg | grep TUN
Universal TUN/TAP device driver 1.5 (C)1999-2002 Maxim Krasnyansky

Si el soporte de TUN/TAP se construye como módulo, entonces se debe cargar en primer lugar el módulo tun:

root #modprobe tun
root #lsmod
Module                  Size  Used by
tun                     7296  0

Ahora que el módulo tun</tun> está cargado, comprobar la salida de dmesg. Se debería mostrar algo similar a lo siguiente:


root #dmesg | grep TUN
Universal TUN/TAP device driver 1.5 (C)1999-2002 Maxim Krasnyansky

Emerge

Ahora que se ha completado la configuración de un núcleo que funciona, instalar el paquete net-misc/vpnc:

root #emerge --ask net-misc/vpnc

Asegúrate de verificar las opciones correctas dentro de los ajustes USE y ver si éstas aplican al entorno. Si se encuentra un problema más tarde, habilitar el ajuste USE hybrid-auth:

CÓDIGO vpnc quejándose sobre el modo hybrid/cert
vpnc was built without openssl: Can't do hybrid or cert mode.

Configuración

In order to make the following sections more clear, we need an example setup to work from. For the purpose of this exercise, we will assume that the home network consists out of several computers. All computers are on the 192.168.0.0 / 255.255.255.0 network. The LAN in question is run by a Gentoo box using an iptables firewall, DHCP, caching DNS, etc ... and it masquerades the LAN behind the public IP address it receives from an ISP. A workstation is also on the LAN from which the VPN into the office will be configured.

Our example workstation configuration looks like the following:

ARCHIVO /etc/resolv.conf
nameserver      192.168.0.1
ARCHIVO /etc/hosts
127.0.0.1       escritorio localhost
192.168.0.1     enrutador
192.168.2.2     centrodemedios
root #ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:11:2F:8D:08:08
          inet addr:192.168.0.2  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::211:2fff:fe8d:808/64 Scope:Link
          UP BROADCAST NOTRAILERS RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3657889 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2305893 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2193722103 (2092.0 Mb)  TX bytes:1415104432 (1349.5 Mb)
          Interrupt:185 Memory:fac00000-0
  
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:35510 errors:0 dropped:0 overruns:0 frame:0
          TX packets:35510 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:16023838 (15.2 Mb)  TX bytes:16023838 (15.2 Mb)
root #netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.0.0     *               255.255.255.0   U         0 0          0 eth0
loopback        desktop         255.0.0.0       UG        0 0          0 lo
default         router          0.0.0.0         UG        0 0          0 eth0

vpnc

Now that vpnc is installed and we have an example to work from, let's discuss the basics of setting up vpnc. The configuration file for vpnc connection settings can be located in a couple places, depending on how many profiles need to be configured. By default, vpnc looks for /etc/vpnc/vpnc.conf for its connection settings. This setup will only address a single profile example and will use the configuration file location /etc/vpnc/vpnc.conf .

ARCHIVO /etc/vpnc.conf
IPSec gateway vpngateway.domain.org
IPSec ID group_id
IPSec secret group_password
Xauth username network_signon
Xauth password network_password

The configuration file example above should be modified to reflect the appropriate values for the local setup. The gateway option vpngateway.domain.org can be a fully qualified domain name or an IP address. The ID and secret options should be given by a network administrator. If this information cannot be obtained but a working setup on a Windows box is available which utilizes the official Cisco VPN client, then it suffices to export the profile. The user name and password options are for the normal network sign-on, such as a Windows NT domain account.

When the profile is exported from a Windows machine, then the result is most likely a file ending in .pcf . This file will have all the necessary information. Below is an example:

ARCHIVO profile.pcf
[main]
Description=
Host=VPNGATEWAY.DOMAIN.ORG
AuthType=1
GroupName=group_id
GroupPwd=
enc_GroupPwd=F3256220AA200A1D532556024F4F314B0388D48B0FBF2DB12
EnableISPConnect=0
ISPConnectType=0
ISPConnect=FOOBAR
ISPCommand=
Username=
SaveUserPassword=0
UserPassword=
enc_UserPassword=
NTDomain=
EnableBackup=0
BackupServer=
EnableMSLogon=1
MSLogonType=0
EnableNat=1
TunnelingMode=0
TcpTunnelingPort=10000
CertStore=0
CertName=
CertPath=
CertSubjectName=
CertSerialHash=00000000000000000000000000000000
SendCertChain=0
VerifyCertDN=
DHGroup=2
ForceKeepAlives=0
PeerTimeout=90
EnableLocalLAN=0
EnableSplitDNS=1
ForceNetLogin=0

In the above example, we can see entries for Host, GroupName, and enc_GroupPwd. The Username and UserPassword may or may not be exported depending on the setup. To generate a working vpnc configuration out of it, use pcf2vpnc, included with vpnc.

Nota
The password can be decrypted with the help from the cisco-decrypt program, shipped with the latest vpnc.

Testing the setup

Now that a configuration is in place it is time to test the setup. To start vpnc do the following:

root #vpnc
Enter password for username@vpngateway.domain.org:
VPNC started in background (pid: 14788)...

The above command output shows that, once vpnc (as root) is executed, a prompt comes up asking for a password. After entering the password (which will not be echoed to the terminal), the vpnc process will automatically become a background process.

Nota
If the Xauth password option is specified in the vpnc config file, then at vpnc startup no password will be asked. Additionally, if vpnc needs some extra options not specified in the configuration file, or if something is forgotten, don't worry, it will ask for it.
root #ifconfig -a
eth1      Link encap:Ethernet  HWaddr 00:11:2F:8D:08:08
          inet addr:192.168.0.2  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::211:2fff:fe8d:808/64 Scope:Link
          UP BROADCAST NOTRAILERS RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2101119 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1577559 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1757862627 (1676.4 Mb)  TX bytes:732200131 (698.2 Mb)
          Interrupt:177 Memory:faa00000-0
  
sit0      Link encap:IPv6-in-IPv4
          NOARP  MTU:1480  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
  
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:192.168.160.42  P-t-P:192.168.160.42  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1412  Metric:1
          RX packets:1 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:60 (60.0 b)  TX bytes:616 (616.0 b)
root #netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
vpn01.domain.or router          255.255.255.255 UGH    1500 0          0 eth1
192.168.0.0     *               255.255.255.0   U         0 0          0 eth1
loopback        desktop         255.0.0.0       UG        0 0          0 lo
default         *               0.0.0.0         U         0 0          0 tun0

As can be seen from the above command output(s), vpnc has done the following:

  • Created the tun0 network interface, a virtual interface to handle the traffic across the VPN tunnel
  • Obtained the IP address for the tun0 device from the VPN provider
  • Set the default route to the VPN gateway

At this point, the workstation is capable of communicating with hosts via the VPN. Because vpnc sets the default route to the VPN gateway, all network traffic will travel across the VPN, even if it destined for the Internet or elsewhere not specifically specified by additional routes. For some, this basic type of connection may be satisfactory, but for most, additional steps need to be taken.

Additional things that might be interesting to have:

  • DNS for the VPN
  • A routing setup that will only send traffic destined for the VPN down the virtual tunnel. This way, browsing the Internet will originate directly from the local network even when connected to the VPN, without the personal web/p2p etc. traffic going across the tunnel.
  • A script to manage all this, because vpnc just doesn't do enough by default.

To end the VPN session, execute vpnc-disconnect. An example is shown below.

Nota
Don't disconnect yet, because we have additional things to test. The example below is just for informational purposes.
root #vpnc-disconnect
Terminating vpnc daemon (pid: 26250)

Set up DNS

Unfortunately, vpnc doesn't handle the setup and management of DNS for the newly established tunnel. The user is left to decide how DNS should be handled. Although /etc/resolv.conf can be written during the connection, that would utilize the VPN DNS for all DNS queries regardless of whether or not the traffic is destined for the VPN tunnel. This is a very functional solution and if all that is needed is to connect to the tunnel, work, and then disconnect, read no further. But, to be able to leave the tunnel connected for lengthy periods of time without the work DNS servers handling requests for the personal traffic, read on.

The ideal setup would allow users to separate the DNS queries into two categories: VPN-related and other. Under this setup, all VPN-related DNS queries would be answered by DNS servers located at the other end of the VPN tunnel and all other queries would continue to be answered by local or ISP supplied DNS servers. This is the setup that will be demonstrated here.

Nota
We will consider VPN-related DNS queries to be any query belonging to the example.org domain, such as host1.example.org or server1.example.org.

So how to make sure that requests made to hosts on the example.org domain get sent to VPN supplied DNS servers? Well, first install a local DNS server, but don't worry, it's much easier than it sounds. There are several software packages that can handle the type of setup we desire, but for the purposes of this demonstration, dnsmasq will be utilized. Let's emerge it now:

Nota
This DNS server software will not be available to the network, and will only answer requests from localhost, 127.0.0.1.
root #emerge --ask net-dns/dnsmasq

Next add an option to dnsmasq's startup options. Edit the following option and substitute .example.org with the appropriate domain and the IP address with a valid DNS server that belongs to the VPN tunnel.

ARCHIVO /etc/conf.d/dnsmasq
# Leer la página del manual dnsmasq(8) para conocer las posibles opciones que se pueden escribir aquí
DNSMASQ_OPTS="-S /.example.org/192.168.125.10"

Next, make sure that the first entry in /etc/resolv.conf is the local host 127.0.0.1, followed by the location of the backup DNS servers that should handle the DNS traffic in case dnsmasq fails to start, or if it needs to forward a DNS query it doesn't currently have in its cache. An example /etc/resolv.conf is shown below.

ARCHIVO /etc/resolv.conf
nameserver 127.0.0.1
nameserver 192.168.0.1

Now that a rule is setup for the VPN tunnel DNS, start dnsmasq.

root #/etc/init.d/dnsmasq start
root #rc-update add dnsmasq default

The routing table

The ideal scenario would be if only the traffic destined for the VPN tunnel would travel across the link. At this point, a VPN tunnel setup exists and all traffic will travel across the tunnel, unless additional routes are specified. In order to fix this situation, know what networks are available on the VPN. The easiest way to find out the needed information is to ask a network administrator, but sometimes they are reluctant to answer such questions. If the local network admin doesn't provide the needed information, some trial and error experiments will be required.

When the VPN tunnel was started, vpnc set the default route to the tunnel. So set the default route back to normal, so that things work as expected.

root #route add default gw 192.168.0.1

Earlier, when DNS services were being configured for the VPN, a DNS server was specified to handle the example.org domain. Add a route for the 192.168.125.0 subnet so that DNS queries will work:

root #route add -net 192.168.125.0 netmask 255.255.255.0 dev tun0

At this point, any additional routes for known networks (such as for the subnet 192.168.160.0, which includes the IP address received by the TUN/TAP virtual device) should be added. If a friendly network administrator gave the required info, great. Otherwise, start pinging hosts that will be connected to frequently, to give an idea about what the routing table should look like.

Nota
Due to the setup, when using VPN network services by name, specify the fully qualified domain name, for instance: webserver1.example.org
root #ping intranet1.example.org
PING intranet1.example.org (172.25.230.29) 56(84) bytes of data.
  
--- intranet1.example.org ping statistics ---
18 packets transmitted, 0 received, 100% packet loss, time 16997ms

As seen from the above example, the ping probes to intranet1.example.org were unsuccessful. So we need to add a route for that subnet.

root #route add -net 172.25.230.0 netmask 255.255.255.0 dev tun0

A few ping and route commands later, and the system should be well on its way to a well working routing table.

Manage the connection

Calling vpnc when needed

Next is an example script to manage the VPN connection. Execute it (as root) from an xterm to start a connection to the VPN. Then all that is left to do is to press return to disconnect the VPN. Obviously this needs to be modified on the current setup, remembering to add all the additional routes that may be necessary.

ARCHIVO sessionmgmt.shGuión ejemplo de gestión de sesión
#!/bin/bash
  
source /sbin/functions.sh
  
ebegin "Conectando a la VPN"
vpnc
eend
  
ebegin "Modificando la tabla de rutas"
route add default gw 192.168.0.1
route add -net 172.25.230.0 netmask 255.255.255.0 dev tun0
route add -net 192.168.160.0 netmask 255.255.255.0 dev tun0
route add -net 192.168.125.0 netmask 255.255.255.0 dev tun0
eend
  
einfo "Pulse cualquier tecla para desconectar ..."
  
read $disconnect
  
ebegin "Desconectando de la VPN"
vpnc-disconnect
eend
ebegin "Reconfigurando la tabla de rutas por defecto"
route add default gw 192.168.0.1
eend
  
einfo "La VPN debería estar desconectada ahora"

Start vpnc on boot

Version 0.4.0-r1 of vpnc contains an init script (/etc/init.d/vpnc) which can handle multiple configurations. The default script looks for /etc/vpnc/vpnc.conf, but as many configurations as can be imagined are possible. Before and after shutdown and start-up custom-made scripts can be executed that are connected by their name to the corresponding init script (since version 0.5.1-r1). Their names end in -preup.sh, -postup.sh, -predown.sh and -postdown.sh, stored in the /etc/init.d/scripts.d/ directory. The general naming scheme is sketched in the following table.

Nombre del guión de inicio Fichero de configuración necesario Nombre del guión de pre-inicio
/etc/init.d/vpnc /etc/vpnc/vpnc.conf /etc/vpnc/scripts.d/vpnc-preup.sh
/etc/init.d/vpnc.work /etc/vpnc/work.conf /etc/vpnc/scripts.d/work-preup.sh

Añadir vpnc al nivel de ejecución por defecto con las siguientes órdenes (en este caso para la configuración estándar). No se debe olvidar añadir el módulo tun (si se ha construido de esta forma) al mecanismo de autocarga del núcleo en el inicio.

root #rc-update add vpnc default

To not have to save the password in the configuration file, tell the init script to show all output and prompts on standard output by editing /etc/conf.d/vpnc. Set the VPNCOUTPUT variable to yes or no, where its default is to not display screen output.

Nota
The init scripts don't handle DNS separation, but can use custom scripts to achieve that.

Tips and tricks

Graphical remote access

When looking for a Linux application that supports RDP (Remote Desktop Protocol) then give net-misc/grdesktop a try. It is a GUI app written in GTK+ that fits in well with a Gnome desktop, but doesn't require it. As an alternative to the GUI configuration dialog that grdesktop provides, just install net-misc/rdesktop. Ultimately, grdesktop is just a frontend for rdesktop.

KDE users might want to try out net-misc/kvpnc. It appears to be a very mature VPN management GUI.

To connect to a Windows machine which doesn't have a DNS entry, but for which the address of an available WINS server is known, use a tool called nmblookup to query the WINS server for the host name of the machine to connect to. Unfortunately, net-fs/samba needs to be installed to get it, but when working with boxes running Windows installing samba is usually a given, because it includes several other useful tools.

root #emerge --ask net-fs/samba

When samba and its tools are installed, test nmblookup by asking the WINS server at IP address 192.168.125.11 about a host named wintelbox1.

root #nmblookup -U 192.168.125.11 -R 'wintelbox1'
querying wintelbox1 on 192.168.125.11
172.25.230.76 wintelbox1

Custom scripts on boot

The custom-made scripts for the init.d file can be used to setup a user-defined routing for the vpnc connection. The examples below show how to setup the routing table so that only connections to 123.234.x.x are routed over the VPN and all other connections use the default gateway. The example uses work-preup.sh to save the current default gateway before starting vpnc (which resets the default gateway using the VPN connection). Once vpnc has been started, work-postup.sh deletes this new default gateway, restores the old default gateway and sets the route for all connections to 123.234.x.x to use the vpnc connection.

ARCHIVO /etc/vpnc/scripts.d/work-preup.sh
#!/bin/sh
route -n | grep -E '^0.0.0.0 ' | cut -c 17-32 >/var/tmp/defaultgw
ARCHIVO /etc/vpnc/scripts.d/work-postup.sh
#!/bin/sh
route del -net 0.0.0.0 netmask 0.0.0.0 dev tun1
route add default gw $(cat /var/tmp/defaultgw)
route add -net 123.234.0.0 netmask 255.255.0.0 dev tun1

The example scripts assume that the vpnc connection uses tun1 as tun device. Set the device name in the connection's configuration file.

ARCHIVO /etc/vpnc/work.conf
Interface name tun1
IPSec gateway vpn.mywork.com
Pidfile /var/run/vpnc.work.pid

Recursos externos


This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: David H. Askew, Christian Faulhammer, Thomas Fischer, nightmorph
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.