[2024-feb-29] Sad news: Eric Layton aka Nocturnal Slacker aka vtel57 passed away on Feb 26th, shortly after hospitalization. He was one of our Wiki's most prominent admins. He will be missed.

Welcome to the Slackware Documentation Project

¡Esta es una revisión vieja del documento!


En proceso de traducción. rramp

Puente ethernet con OpenVPN

Otras guías detallan la configuración de OpenVPN para un puente 'tun', donde el tráfico es enrutado eficientemente entre un par de sitios alejados geográficamente, pero esta guía trata acerca de los puentes 'tap'. De hecho, describe cómo unirse a un par de sitios que reenvían todo el tráfico ethernet, independientemente del protocolo. Esto es útil para el desarrollo, probar redes y si necesitas reenviar protocolos que no sean IP. Esto es también más simple que los puentes tun porque no tiene que preocuparse por el enrutamiento, solo se necesita ejecutar un único servidor DHCP en uno u otro lado del puente.

Acerca de OpenVPN

OpenVPN es cubierto en este otro artículo, así que haré referencias a las secciones en lugar de copiar y pegar partes de esto aquí. Espero que esto cubra las brechas necesarias para obtener un puente ethernet que funcione.

Introducción

Solo para que quede claro de qué estamos hablando, aquí hay un diagrama:

Hay dos máquinas físicas (cliente PM y servidor PM) y cuatro máquinas virtuales. El objetivo es que el 'Cliente privado' se comunique directamente con el 'Servidor privado', como si estuvieran en el mismo segmento de Ethernet. El conmutador (switch) en el medio es solo mi red domestica pero usted puede considerar que se trata de internet si lo desea. Muchas configuraciones reales harán que 'el servidor de puerta de enlace (Server Gateway)' y el 'Servidor privado' sean lo mismo, no hay razón para que sean distintas, sin embargo, siento que es más fácil seguir lo que está sucediendo si son distintas.

VirtualBox

VirtualBox es mi solución preferida para virtualización por que se instala limpiamente en Slackware 14.2 y -current y es fácil de usar. ¡Si tiene cuatro máquinas físicas en las que puede instalar Slackware, por supuesto puede hacer todo esto sin virtualización! En mi caso yo tengo dos máquinas físicas que representan cada 'sitio' que quieres unirte. Todas las máquinas virtuales corren Slackware de 64 bit versión 14.2 sin parchar.

Servidor privado

Sin más preámbulos, sigamos configurando nuestro servidor privado. Le he dado a la máquina virtual los siguientes recursos:

  • 1024 MB RAM,
  • 8GB de disco duro.

Without further ado, let's get on with setting up our private server. I've given the virtual machine the following resources:

  • 1024 MB RAM
  • 8GB Hard disk

</del> En la configuración de red de Virtualbox, le he dicho a la máquina virtual que use 'Red interna' y escribí el nombre de la red 'slacknet' por falta de un nombre mejor. Podrías llamarlo 'privado' si vos querés. Nada alcanzará esta red a menos que configuremos una máquina como enrutador.

In the VirtualBox network settings, I've told the virtual machine to use 'Internal Network' and I've typed in the network name 'slacknet' for want of a better name. You could call it 'private' if you like. Nothing will reach this network unless we setup a machine as some kind of router to it.

Yo instalé Slackware con el conjunto de discos A, AP, N y L por que no necesito ninguna GUI pero es necesario las herramientas de red, pero esto realmente no importa, si querés podes hacer una instalación completa. Configure esta máquina con una dirección IP estática, en este caso 10.0.0.1. De otra forma, la instalación sigue las opciones por defecto.

I've told Slackware to install the A, AP, N and L disk sets because I don't need any GUI but want networking stuff, but it doesn't really matter, make it a full install if it pleases you. I've taken care to give this machine a static IP address, in this case 10.0.0.1. Otherwise the install is following all defaults.

Luego del arranque, solo hay una cosa que debemos hacer para que esta prueba sea realista. Es necesario habilitar Dnsmasq. Puede seguir ese enlace para obtener más detalles, pero solo necesitamos un pequeño archivo de configuración /etc/dnsmasq.conf que contiene solo:

After boot there is just one thing we need to do to make this test realistic. We need to enable Dnsmasq. You can follow that link for details, but we just need a small configuration file /etc/dnsmasq.conf containing only:

interface=eth0
dhcp-range=10.0.0.50,10.0.0.70,12h

¡Eso es! Haga una copia de respaldo del archivo del antiguo dnsmasq.conf en algún lugar primero si está preocupado por perder todos los comentarios, pero no importa realmente ya que es una máquina de pruebas. Lo anterior es todo lo que necesita para trabajar con el servidor dhcp. Eso es lo que hace tan grande a Dnsmasq. That's it! Backup the old dnsmasq.conf somewhere first if you're worried about losing all the comments in it, but it doesn't matter, this is really just a throw-away test machine. The above is all you need for working dhcp server. That's what makes Dnsmasq so great.

Ahora solo necesitamos iniciar el servidor: Now we just need to start the server:

# chmod 755 /etc/rc.d/rc.dnsmasq
# /etc/rc.d/rc.dnsmasq start

Entonces ahora tenemos nuestro servidor privado corriendo sobre tu red privada! Por el momento, nada puede verlo, pero si instalara otra máquina virtual y la conectara a esa red privada (slacknet), obtendría una dirección IP. Hemos hecho esto simplemente para demostrar que el tráfico que no es IP (es decir, DHCP) puede atravesar nuestro puente y DHCP es solo una forma conveniente de hacerlo.

So now we have our private server running on our private network! Nothing can see it for the moment but if you were to install another virtual machine and connect it to that private (slacknet) network it would get an IP address. We have done this purely to demonstrate that non-IP (i.e. DHCP) traffic can get across our bridge and DHCP is just a convenient way of doing this.

Server Gateway

Configuración de la máquina virtual en VirtualBox

El servidor de puerta de enlace es otra máquina Slackware cuya configuración de memoria es la misma, disco duro y conjuntos de discos como el 'Servidor privado' anterior. Se diferencia en que tiene un segundo NIC configurado en VirtualBox. The server gateway is another Slackware machine setup with the same memory, hard disk and disk sets as the 'Private Server' above. It differs, however in that it has a second NIC configured in VirtualBox.

El primer NIC en VirtualBox también conocido como 'adaptador 1' terminará siendo eth0 en la máquina virtual iniciada, tenga en cuenta esto. Estableceré esto como 'Adaptador puenteado' en 'Adjunto a:' en la GUI. Note que para todas las NICs yo estoy configurando 'modo promiscuo' a 'permitir todo', aunque no tengo idea si eso es necesario para todas las NICs en todas las máquinas de esta guía. The first NIC in VirtualBox aka 'Adapter 1' in the VirtualBox GUI will end up being eth0 in the booted Slackware virtual machine, just bear this in mind. I will set this as 'Bridged Adapter' under 'Attached to:' in the GUI. Note that for all NICs I'm setting 'Promiscuous Mode' to 'Allow All', although I've no idea if that's needed for all the NICs on all the machines in this guide.

El 'Adaptador 2' se conectará a la red privada 'slacknet' que se describe en la configuración de 'Servidor privado' más arriba.

'Adapter 2' will be connected to the 'slacknet' private network discussed in the 'Private Server' configuration above.

Configuración de red

Ahora todas las preguntas que Slackware le hace durante la configuración de la red se aplican a la interfaz pública que está conectada directamente (a través del puente de VirtualBox) al conmutador en el centro del diagrama anterior. Lo más probable es que sea el enrutador de banda ancha de su hogar el que proporcionará una dirección IP y tal vez (si tiene suerte) un servidor de nombres (DNS) apropiado. No importa, siempre que haya algo que pueda usar para identificar está interfaz pública en la red. De aquí en adelante, me referiré a la interfaz ethernet de está maquina como 'vpn', o podemos decir 'vpn.localnet', aunque, si solo tiene una dirección IP, solo use esa.

Now all the questions Slackware asks you during network setup apply to the public interface which is connected directly (via VirtualBox's bridge) to the switch in the middle of the diagram above. Chances are it is your home broadband router which will dish out an IP address and maybe (if you're lucky) an appropriate DNS name. It matters not, so long as there is something you can use to identify this public interface on the network. From here on I'm going to refer to this machine's ethernet interface as 'vpn', or we can say 'vpn.localnet', however if you only have an IP address just use that. The good news is that it doesn't matter if it 'clashes' with the IP address range we talked about in 'Private Server' dnsmasq configuration because… well… it's really private. Neat huh? This would obviously be a big issue if we want to later add routing from 'Private Server' to the outside world, but that will be another howto. Las buenas noticias es que no importa si esta 'choca' con el rango de direcciones IP de las que hablamos en la configuración de dnsmasque de el 'servidor privado' por que… bueno… esto es realmente privado. Limpio eh? Obviamente, esto sería un gran problema si queremos agregar más adelante el enrutamiento del 'Servidor privado' al mundo exterior, pero ese será otro ejemplo.

dispositivo tap0

Habiendo instalado una segunda máquina virtual Slackware con dos tarjetas ethernet, solo una de las cuales está activa, necesitamos hacer algunas cosas adicionales antes de hablar sobre OpenVPN.

Having installed a nice shiny 2nd Slackware virtual machine with two ethernet cards, only one of which is active we need to do some extra stuff before we talk about OpenVPN.

El primer paso es instalar tunctl. Voy a hacer la suposición (posiblemente injusta) de que sabes cómo instalar paquetes de Slackware desde slackbuilds. The first step is to install tunctl. I'm going to make the (possibly unfair) assumption that you know how to install Slackware packages from slackbuilds.

Una vez instalado tunctl, edita el archivo /etc/rc.d/rc.inet1, busca las siguientes líneas:

Once tunctl is installed, edit /etc/rc.d/rc.inet1, find the following lines:

# Funciones para iniciar la red:
start() {
  lo_up
...

Haz que diga: Make them say:

# Funciones para iniciar la red:
start() {
  lo_up
  /usr/sbin/tunctl -u nobody -t tap0
...

Esto creará (en el arranque) un dispositivo tap0 con los permisos correctos de modo que OpenVPN pueda acceder a él y, más concretamente, lo creará antes de que comience la configuración de puentes en los scripts de inicio de Slackware. También se podría crear en rc.local pero se iniciaría demasiado tarde.

This will (on boot) create a tap0 device with the correct permissions such that OpenVPN can access it and, more to the point, it will create it before any of the bridging configuration stuff in the Slackware init scripts kicks in. rc.local would have it created way too late.

configuración del puente

Ok, ahora estamos hablando acerca de kernel network bridging, no del puente ethernet que es el tema de este artículo.

OK, so now we are talking about kernel network bridging, not the ethernet bridging that's the subject of this article. Este es un hecho triste que a pesar de que tenemos una NIC asignada a propósito a la tare de hablar con nuestra red privada, es decir, no se comparte con ningún otro tráfico, todavía necesitamos crear un puente del kernel para que OpenVPN pueda hablar correctamente con la NIC. En otras palabras, no podemos decirle a OpenVPN que simplemente 'usá eth1' (o que sea tan simple). It's a sad fact that even though we have a NIC purposely allocated to the task of talking to our private network, i.e. not shared with any other traffic, we still need to create a kernel bridge in order for OpenVPN to talk properly to the NIC, in other words we can't tell OpenVPN to just 'use eth1' (oh that it were so simple). Esto quiere un 'tap'. Y un tap puede solo hablar a un dispositivo NIC a través de un puente. Así que echemos un vistazo a la configuración de red en Slackware. It wants a 'tap'. And a tap can only talk to a NIC via a bridge. So let's have a look at the network config in Slackware.

Para eth0 en /etc/rc.d/rc.inet1.conf ahora tendrá una configuración como esta, suministrado con cortesía por el script netconfig de Slackware; For eth0 in /etc/rc.d/rc.inet1.conf you are going to now have a setup something like this, courteously supplied by the Slackware netconfig script:

IPADDR[0]=""
NETMASK[0]=""
USE_DHCP[0]="yes"
...

O puede tener una dirección IP estática. Debes tener *algo*. Ahora desplácese hacia abajo a la sección sobre puentes: Or you may have a static IP address. You should have *something*. Now scroll down to the section on bridging:

# Ejemplo de como configurar un puente:
# Note el agregado de la variable "BRNICS" la cual contiene un lista separada por espacios
# de las interfaces de red físicas que tu quieres agregar a el puente.
...

Justo debajo se desea que aparezca lo siguiente: Just below that you want the following to appear:

IFNAME[1]="br0"
BRNICS[1]="eth1 tap0"
IPADDR[1]="0.0.0.0"

Se cuidadoso con los números. Los corchetes son los que le dicen a Slackware que este es el segundo dispositivo que configuramos como puente, y nosotros queremos agregar el dispositivo eth1 a el puente junto con el dispositivo tap0. Be careful with the numbers. It's the the square brackets which are telling Slackware this is the 2nd device we're configuring as a bridge, and we want to add eth1 to the bridge along with the tap0 device. Slackware no configura el dispositivo eth1, ni siquiera necesitamos mencionarlo o referirlo de otra manera en los archivos de configuración como esclavo del puente.

Slackware doesn't configure the eth1 device, we don't even need to bring it up or otherwise refer to it in the config files as it's slave to the bridge.</del>
Algunas personas pueden configurar aquí br0 como br1, para indicar que esta conectado al segundo NIC y mantenerlos igual. Usted puede hacer esto. También puedes cambiar el nombre de tap0 si tu lo deseas, la experiencia me dice que es mejor usar siempre números bajos para todo independientemente de lo que hagan. Para mí, al menos, reduce la confusión.
Some people might configure br0 as br1 here, to indicate it's connected to the second NIC and keep them the same. You can do that. And you can change the name of tap0 as well if you want, experience tells me it's best to always use the lowest numbers for everything regardless of what they do. For me, at least, it reduces the confusion.

No necesitas configurar la dirección IP a 0.0.0.0, pero esto es una forma práctica de hacer que el puente sea levantado sin darle una dirección ip, y no es un problema. Si usted no configura alguna dirección ip, usted puede hacer 'ifconfig br0 up' posteriormente. You don't have to set the IP address to 0.0.0.0, but it's a handy way of making the bridge come 'up' without giving it an IP address, and something that is supposed to simply sit there forwarding ethernet frames has no business having an IP address of its own. If you don't set any address at all you can do 'ifconfig br0 up' at some later point.

Cuando se arranca con esta configuración, usted debé chequear que br0 esta arrib con: When you boot with this configuration, you should check that br0 is up with

# ifconfig br0

y usted puede también chequear el puente con 'brctl show br0' y se debería mostrar algo como esto: And you can also check the bridge with 'brctl show br0' and it should show something like this:

# brctl show br0
bridge name	bridge id		STP enabled	interfaces
br0		8000.485b39c042ee	no		eth0
                                                        tap0

Así que eso está hecho la configuración de puente. Ahora OpenVPN (cuando este eventualmente configurado) podrá comunicarse con la red privada, en este ejemplo, 'slacknet' sin problemas, incluso si solo tiene 'nadie' como nombre de usuario.

So that's done the bridging config. Now OpenVPN (when it's eventually configured) will talk nicely to the private network aka 'slacknet' without any trouble, even if it only has 'nobody' as a username.

Configuración de OpenVPN

Así que esta es la parte en la que puedo descansar tranquilamente 'sobre los hombros de gigantes' por así decirlo. Por favor, configure su PKI para un servidor OpenVPN siguiendo guide in the OpenVPN howto. Siga toda la sección 5 para tener un conjunto de claves públicas y privadas para el servidor. No te preocupes por crear el archivo de configuración para hacer referencias a ellos, ya que lo haremos aquí.

¿Esta preparado? bien.

So this is the part where I can just rest easy 'on the shoulders of giants' so to speak. Please setup your the PKI stuff for an OpenVPN server by following the guide in the OpenVPN howto. Follow all of section 5 so you have a set of public and private keys for the server. Don't worry about creating the config file to reference them from though as we'll do that back here. Ready? Good.

Mi /etc/openvpn/server.conf es un archivo pequeño y un poco más simple que el del manual (how to) de OpenVpn. Se han eliminado los comentario por brevedad y también la parte de enrutamiento. Usted puede siempre chequear las opciones en la pagina del manual de OpenVpn si lo desea, pero la mayoría se explican por si misma.

So my /etc/openvpn/server.conf is a little simpler than the one in the OpenVPN howto. We don't care about any of the routing stuff, and I've removed all the comments for brevity. You can always check options in the manual page for OpenVPN if you want but most are self-explanatory.

port 443
proto udp      # o tcp
dev tap0     # o tun
ca /etc/openvpn/certs/ca.crt
cert /etc/openvpn/certs/vpn.crt
key /etc/openvpn/keys/vpn.key
dh /etc/openvpn/certs/dh2048.pem
tls-server
keepalive 10 120
daemon
log-append  /var/log/openvpn.log
verb 3

Yo removí la palabra clave para vpn.key (recuerda que es equivalente de 'server1.key' en el how to de OpenVPN). Eh evitado renunciar a root. Usted ejecutaría una configuración más segura si este fuera un sistema de producción al comprender las opciones en la página de manual de OpenVPN, esto es solo para que pueda trabajar.

I have removed the passphrase from vpn.key (remember that's the equivalent of 'server1.key' in the OpenVPN howto). I've avoided giving up root as well. You would run a more secure setup if this was a production system by understanding the options in the OpenVPN manual page, this is just to get you working.

Ahora usted puede volver a atrás a los otros artículos y leer Configuración del servidor OpenVPN. Ahora usted puede saltar a los scripts que hablan son rc.openvpn, para asegurarte de tener un script que inicie OpenVPN.

Now you can go back to the other article and look at Setting up the server. Skip forward to the stuff that talks about rc.openvpn, to ensure you have a script to start OpenVPN up. Once you have that you should be able to startup without seeing errors in /var/log/openvpn.log.

Client Gateway

Configuración de VirtualBox

Al igual que la máquina 'puerta de enlace privado', esta máquina puede tener dos NICs. 'Adaptador 1', sin embargo, puede ser NAT en lugar de puenteado, ya que nada tiene que ser capaz de encontrarlo. Like the 'Private Gateway' machine, this machine will have two NICs. 'Adapter 1', however can be NAT instead of bridged, as nothing needs to be able to find it. El 'Adaptador 2' puede estar conectado a la red privada 'slacknet'. Yo hice le asigne el mismo nombre que en la otra máquina del servidor, ya que se conectarán entre sí, pero no importa como se llame, siempre que el 'Cliente privado' use el mismo nombre. 'Adapter 2' will be connected to a private 'slacknet' network. I made the name the same as on the other server machine, as they will become connected together but it doesn't matter what you call it so long as 'Private Client' uses the same name.

Instalación de Slackware

Me temo que una vez más, necesitarás instalar tunctl, crear el dispositivo tap0 y habilitar el puente exactamente como sucedio con la puerta de enlace del servidor. Una vez que tap0, y br0 son creadas en el arranque usted puede configurar OpenVPN. I'm afraid once again, you'll need to install tunctl, create a tap0 device and enable the bridging exactly as happened for the Server Gateway. Once tap0, and br0 are created on boot you will be good to configure OpenVPN.

Configuración de OpenVPN

Una vez más, pongo en juego el otro howto para la configuración PKI del lado del cliente. Sin embargo, usted puede saltar la creación del archivo rc.openvpn ya que no estaremos ejecutando OpenVPN como un demonio. El archivo de configuración del cliente es un simple archivo(/etc/openvpn/client.conf):

Once again, I bring into play the other howto for the PKI config on the client side. However you can skip the rc.openvpn creation as we won't be running as a daemon. The client configuration (/etc/openvpn/client.conf) is a little simpler:

client
dev tap0
proto udp
remote vpn.localnet 443
ca /etc/openvpn/certs/ca.crt
cert /etc/openvpn/certs/client.crt
key /etc/openvpn/keys/client.key
dh /etc/openvpn/certs/dh2048.pem
remote-cert-tls server
verb 3

Ahora debería poder conectarse a la 'Puerta de enlace del servidor' con este comando como root: You should now be able to connect to the 'Server Gateway' with this command as root:

openvpn /etc/openvpn/client.conf

Cliente Privado

Al igual que el 'Servidor privado', está maquina tendrá una configuración similar de VirtualBox. Esta tendrá un solo NIC conectado a una red llamada 'slacknet'.

Very much like the 'Private Server' this machine will have similar VirtualBox setup. It will have a single NIC connected to a network called 'slacknet'.

Iba a usar Slackware para esto, pero decidí hacer trampa y usar Slax (distribución de CD de inicio) para ahorrar tiempo en la instalación. Slax solicita una dirección IP mediante DHCP, por lo que realmente tiene todo lo que necesita para probar el puente (solicitud DHCP enviada, respuesta DHCP recibida).

I was going to use Slackware for this, but I decided to cheat and use Slax (Bootable CD distro) to save time on the install. Slax requests a DHCP address on boot, so it really has all you need to test the bridge out (DHCP request sent, DHCP response received). Si en el arranque va todo bien, obtendras una dirección IP como 10.0.0.50 (o al menos en el rango de direcciones proporcionadas por el servidor Dnsmasq que configuramos en el 'Servidor privado'). If all goes well when you boot you'll get an IP address something like 10.0.0.50 ( or at least in the range of addresses provided by the Dnsmasq server we setup on 'Private Server')

Pruebas de extremo a extremo

Entonces, una vez que las cuatro máquinas virtuales (¡sí!) estén en funcionamiento y corriendo, debería ser posible (si todo funciona) iniciar el Cliente privado y obtener una dirección IP en el rango correcto, es decir, entre 10.0.0.50 y 10.0.0.70. Preste mucha atención a /var/logs/openvpn.log sobre la 'puerta de enlace de servidor' y, por supuesto, los mensajes mostrados cuando se ejecuta OpenVPN en la 'puerta de enlace del cliente', ya que deberían informarle lo que está mal. OpenVPN es bastante buena. El paranoico también querrá verificar /var/state/dnsmasq/dnsmasq.leases en el 'Servidor privado' para asegurarse de que todo está bien y que en realidad estamos hablando a través del puente.

So once all four (yes!) virtual machines are up and running, it should be possible (if all is working) to boot the Private Client and get an IP address in the right range, i.e. between 10.0.0.50 and 10.0.0.70. Pay close attention to /var/logs/openvpn.log on 'Server Gateway' and of course the messages displayed when running openvpn on 'Client Gateway' as they should tell you what's wrong. OpenVPN is pretty good like that. The paranoid will also want to check /var/state/dnsmasq/dnsmasq.leases on 'Private Server' to reassure themselves that all's well and we are actually talking across the bridge.

Consolidación

Como explique en la introducción, es posible probar todo esto sin el 'Servidor privado', y combina la función de 'Servidor privado' y 'Servidor de puerta de enlace' en una simple máquina. Sigue leyendo para descubrir cómo.

Lo primero que debe hacer es apagar el 'servidor privado'.

A continuación, debemos asignar una dirección IP a nuestro puente Ethernet en el 'Servidor de puerta de enlace'.

# ifconfig br0 10.0.0.1 netmask 255.255.255.0
¡Asignamos una dirección IP a el puente y no a eth1!

Ahora solamente necesitamos correr una instancia de dnsmasq sobre la interfaz br0, para servir solicitudes a la VPN. Como la configuración del 'Servidor privado', /etc/dnsmasq.conf debería verse así:

interface=br0
dhcp-range=10.0.0.50,10.0.0.70,12h

Entonces es solo cuestión de ejecutar dnsmasq:

# chmod 755 /etc/rc.d/rc.dnsmasq
# /etc/rc.d/rc.dnsmasq start

En este punto, rebooteando el 'Servidor privado' debería obtener una dirección IP del servidor consolidado, y eso es todo. Sin embargo, también cambié el old 'Servidor privado' a dhcp para confirmar que también podría obtener una dirección IP desde 'Server Gateway'.

Fuentes

 es:howtos:network_services:ethernet_bridging_with_openvpn ()