28
Building VPNs on OpenBSD Previous: 2. IPsec overview Up: Table of contents Next: 4. OpenVPN 3. IPsec on OpenBSD Now that we have an adequate working knowledge of the IPsec architecture and protocols, we are finally ready to move from theory to practice and start having some fun with OpenBSD! OpenBSD ships by default with full IPsec support in the stock kernel and provides a set of user-space daemons and tools for managing IPsec configuration, dynamic key exchange and high availability; and the great thing is that, as you'll see, setting up an IPsec VPN on OpenBSD is an incredibly simple and fast task, especially compared to most other IPsec implementations out there. But before proceeding to edit configuration files and run system commands, let's take a brief look at the basic network topology of the VPN that we are going to set up in this document; it's a very simple site-to- site VPN , with a couple of multi-homed security gateways (VPN1 and VPN2) linking two remote private networks (172.16.0.0/24 and 192.168.0.0/24).

Building VPNs on OpenBSD

Embed Size (px)

DESCRIPTION

Building VPNs on OpenBSD

Citation preview

Page 1: Building VPNs on OpenBSD

Building VPNs on OpenBSD

Previous: 2. IPsec overview   Up: Table of contents  Next: 4. OpenVPN

3. IPsec on OpenBSD

Now that we have an adequate working knowledge of the IPsec architecture and protocols, we are finally ready to move from theory to practice and start having some fun with OpenBSD!

OpenBSD ships by default with full IPsec support in the stock kernel and provides a set of user-space daemons and tools for managing IPsec configuration, dynamic key exchange and high availability; and the great thing is that, as you'll see, setting up an IPsec VPN on OpenBSD is an incredibly simple and fast task, especially compared to most other IPsec implementations out there.

But before proceeding to edit configuration files and run system commands, let's take a brief look at the basic network topology of the VPN that we are going to set up in this document; it's a very simple site-to-site VPN, with a couple of multi-homed security gateways (VPN1 and VPN2) linking two remote private networks (172.16.0.0/24 and 192.168.0.0/24).

In this chapter, we will set up the VPN using IPsec: to be more precise, we will configure it in tunnel mode (the only option for network-to-network VPNs) and use the ESP protocol in order to encrypt the VPN traffic as it traverses the Internet; we will also consider the case of redundant IPsec gateways with carp(4). Then, in the next chapters, we will see how the

Page 2: Building VPNs on OpenBSD

same VPN can be implemented using alternative solutions, in particular OpenVPN and OpenSSH.

3.1 Preliminary steps

Before proceeding to configure IPsec, we have to perform a few preliminary steps to make sure the systems are correctly set up for IPsec to work properly. The IPsec protocols are enabled or disabled in the OS's TCP/IP stack via two sysctl(3) variables: net.inet.esp.enable and net.inet.ah.enable, both enabled by default; you can check this by running the sysctl(8) command:

# sysctl net.inet.esp.enablenet.inet.esp.enable=1# sysctl net.inet.ah.enablenet.inet.ah.enable=1

Since our VPN gateways will have to perform traffic routing, we also need to enable IP forwarding, which is turned off by default. This is done, again, with sysctl(8), by setting the value of the net.inet.ip.forwarding variable to "1" if you want any kind of traffic to be forwarded or "2" if you want to restrict forwarding to only IPsec-processed traffic:

# sysctl net.inet.ip.forwarding=1net.inet.ip.forwarding: 0 -> 1

Optionally, you may also want to enable the IP Payload Compression Protocol (IPComp) to reduce the size of IP datagrams for higher VPN throughput; however, bear in mind that the reduction of bandwidth usage comes at the expense of a higher computational overhead (see [RFC3173] for further details):

# sysctl net.inet.ipcomp.enable=1net.inet.ipcomp.enable: 0 -> 1

To make these settings permanent across reboots, add the following variables to the /etc/sysctl.conf(5) file:

/etc/sysctl.conf[ ... ]net.inet.esp.enable=1 # Enable the ESP IPsec protocolnet.inet.ah.enable=1 # Enable the AH IPsec protocol

Page 3: Building VPNs on OpenBSD

net.inet.ip.forwarding=1 # Enable IP forwarding for the host. Set it to '2' to # forward only IPsec trafficnet.inet.ipcomp.enable=1 # Optional: compress IP datagrams

Finally, we need to bring up the enc(4) virtual network interface. This interface allows you to inspect outgoing IPsec traffic before it is encapsulated and incoming IPsec traffic after it is decapsulated; this is primarily useful for filtering IPsec traffic with PF and for debugging purposes.

# ifconfig enc0 up

To make the system automatically bring up the enc(4) interface at boot, create the /etc/hostname.enc0 configuration file:

/etc/hostname.enc0up

3.2 Setting up the PKI

OpenBSD's IKE key management daemon, isakmpd(8), relies on public key certificates for authentication and therefore requires that you first set up a Public Key Infrastructure (PKI) for managing digital certificates.

The first step in setting up the PKI is the creation of the root CA certificate (/etc/ssl/ca.crt) and private key (/etc/ssl/private/ca.key) on the signing machine (which doesn't have to be necessarily one of the VPN gateways) using openssl(1); e.g.:

CA# openssl req -x509 -days 365 -newkey rsa:1024 \> -keyout /etc/ssl/private/ca.key \> -out /etc/ssl/ca.crtGenerating a 1024 bit RSA private key........................................++++++......++++++writing new private key to '/etc/ssl/private/ca.key'Enter PEM pass phrase: <passphrase>Verifying - Enter PEM pass phrase: <passphrase>-----You are about to be asked to enter information that will be incorporatedinto 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 blankFor some fields there will be a default value,If you enter '.', the field will be left blank.-----

Page 4: Building VPNs on OpenBSD

Country Name (2 letter code) []: ITState or Province Name (full name) []: ItalyLocality Name (eg, city) []: MilanOrganization Name (eg, company) []: Kernel Panic Inc.Organizational Unit Name (eg, section) []: IPsecCommon Name (eg, fully qualified host name) []: CA.kernel-panic.itEmail Address []: [email protected]#

The next step is the creation of a Certificate Signing Request (CSR) on each of the IKE peers; for instance, the following command will generate the CSR (/etc/isakmpd/private/1.2.3.4.csr) for the VPN1 machine (the IP address, in this case "1.2.3.4", is used as unique ID):

VPN1# openssl req -new -key /etc/isakmpd/private/local.key \> -out /etc/isakmpd/private/1.2.3.4.csrYou are about to be asked to enter information that will be incorporatedinto 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 blankFor some fields there will be a default value,If you enter '.', the field will be left blank.-----Country Name (2 letter code) []: ITState or Province Name (full name) []: ItalyLocality Name (eg, city) []: MilanOrganization Name (eg, company) []: Kernel Panic Inc.Organizational Unit Name (eg, section) []: IPsecCommon Name (eg, fully qualified host name) []: 1.2.3.4Email Address []: [email protected]

Please enter the following 'extra' attributesto be sent with your certificate requestA challenge password []: <enter>An optional company name []: <enter>VPN1#

Next, the CSRs must be sent to the CA, which will generate the signed certificates out of the certificate requests. For instance, assuming the CSR file is in the current directory:

CA# env CERTIP=1.2.3.4 openssl x509 -req \> -days 365 -in 1.2.3.4.csr -out 1.2.3.4.crt \> -CA /etc/ssl/ca.crt -CAkey /etc/ssl/private/ca.key \> -CAcreateserial -extfile /etc/ssl/x509v3.cnf -extensions x509v3_IPAddrSignature oksubject=/C=IT/ST=Italy/L=Milan/O=Kernel Panic Inc./OU=IPsec/CN=1.2.3.4/[email protected] CA Private KeyEnter pass phrase for /etc/ssl/private/ca.key: <passphrase>CA#

Page 5: Building VPNs on OpenBSD

Finally, you need to copy the newly-generated certificates (the files ending in .crt) to the respective machines in the /etc/isakmpd/certs/ directory, as well as the CA certificate (/etc/ssl/ca.crt) in /etc/isakmpd/ca/.

3.3 Configuration

So we have conveniently set up the system for IPsec use and generated all the required certificates for IKE peer authentication; now we're finally ready to configure our VPN connection. On OpenBSD, all the configuration for IPsec takes place in a single file, /etc/ipsec.conf(5), which uses a very compact syntax, similar to pf.conf(5), to define almost every characteristic of the VPN; the basic format of the file is as follows:

comment lines begin with a hash character ("#") and extend to the end of the line;

rules may span across multiple lines using the backslash character ("\");

network addresses can be specified in CIDR notation, as symbolic host names, interface names, or interface group names;

to simplify the configuration file, macros can be used; macro names must start with a letter, may contain letters, numbers and underscores and must not be reserved words;

certain parameters (such as IP addresses) can be expressed as lists; lists are comma-separated and enclosed in curly braces.

There are different types of ipsec.conf(5) rules, depending on whether you want IPsec flows and SAs to be set up automatically (using isakmpd(8)) or manually; we will only consider the former case (which is usually what you want), so please refer to the documentation for further details on manual setups. The syntax is as follows:

ike [mode] [encap] [tmode] [proto protocol] \ from src [port sport] [(srcnat)] to dst [port dport] \ [local localip] [peer remote] \ [mode auth algorithm enc algorithm group group] \ [quick auth algorithm enc algorithm group group] \ [srcid string] [dstid string] \ [psk string] [tag string]

Though it may look rather complex at first, actual rules are usually very short and simple because most of the parameters can be omitted, in which case the default values are used. But let's examine the rule syntax in detail:

Page 6: Building VPNs on OpenBSD

ike [mode] [encap] [tmode]

the ike keyword specifies that isakmpd(8) must be used to automatically establish the Security Associations for this flow; mode can be either "active" (isakmpd(8) will immediately start negotiation of this tunnel), "passive" (to wait for an incoming request from the remote peer to start negotiation) or "dynamic" (to be used for hosts with dynamic IP addresses) and defaults to "active"; encap specifies the encapsulation protocol and can be either "esp" (default) or "ah"; tmode is the transport mode to use, i.e. "tunnel" (default) or "transport".

proto protocol

Restrict the flow to a specific IP protocol (e.g. TCP, UDP, ICMP); by default all protocols are allowed.

from src [port sport] [(srcnat)] to dst [port dport]

Specify the source and destination addresses of the packets that this rule applies to; you may also specify source and/or destination ports, but only in conjunction with the TCP or UDP protocols. The srcnat parameter can be used to specify the actual source address in outgoing NAT/BINAT scenarios.

local localip peer remote

Specify the local and remote endpoints of the VPN; the local endpoint is required only if the machine has multiple addresses; the remote endpoint can be omitted if it corresponds to the dst parameter.

mode auth algorithm enc algorithm group group

Specify the mode ("main" or "aggressive") and cryptographic transforms to be used for IKE phase 1 negotiation; please refer to the documentation for a complete list of the possible values and their defaults.

quick auth algorithm enc algorithm group group

Specify the cryptographic transforms to be used for IKE phase 2 negotiation; please refer to the documentation for a complete list of the possible values and their defaults.

srcid string dstid string

Define the unique ID that isakmpd(8) will use as the identity of the local (srcid) and remote (dstid) peer; if omitted, the IP address is used.

psk string

Use a pre-shared key for authentication instead of isakmpd(8).tag string

Add a pf(4) tag to IPsec packets matching this rule.

Page 7: Building VPNs on OpenBSD

So let's write the configuration files for the site-to-site VPN we're setting up; as you'll see, it's a really trivial task and a few rules will do. On the VPN1 host, the /etc/ipsec.conf(5) file will look like this:

/etc/ipsec.conf# Macrosext_if = "rl0" # External interface (1.2.3.4)local_net = "172.16.0.0/24" # Local private networkremote_gw = "5.6.7.8" # Remote IPsec gatewayremote_nets = "{192.168.0.0/24, 192.168.1.0/24}" # Remote private networks

# Set up the VPN between the gateway machinesike esp from $ext_if to $remote_gw# Between local gateway and remote networksike esp from $ext_if to $remote_nets peer $remote_gw# Between the networksike esp from $local_net to $remote_nets peer $remote_gw

and on VPN2:

/etc/ipsec.conf# Macrosext_if = "rl0" # External interface (5.6.7.8)local_nets = "{192.168.0.0/24, 192.168.1.0/24}" # Local private networksremote_gw = "1.2.3.4" # Remote IPsec gatewayremote_net = "172.16.0.0/24" # Remote private network

# Set up the VPN between the gateway machinesike esp from $ext_if to $remote_gw# Between local gateway and remote networkike passive esp from $ext_if to $remote_net peer $remote_gw# Between the networksike esp from $local_nets to $remote_net peer $remote_gw

Now we are ready to start the isakmpd(8) daemon on both gateways; we will make it run in the foreground ("-d" option) in order to easily notice any errors:

# isakmpd -K -d

Then, again on both gateways, we can parse ipsec.conf(5) rules ("-n" option of ipsecctl(8)) and, if no errors show up, load them:

# ipsecctl -n -f /etc/ipsec.conf# ipsecctl -f /etc/ipsec.conf

Page 8: Building VPNs on OpenBSD

You can check that IPsec flows and SAs have been correctly set up by running ipsecctl(8) with the "-s all" option; for example:

VPN1# ipsecctl -s allFLOWS:flow esp in from 192.168.0.0/24 to 1.2.3.4 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 type useflow esp out from 1.2.3.4 to 192.168.0.0/24 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 type requireflow esp in from 192.168.1.0/24 to 1.2.3.4 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 type useflow esp out from 1.2.3.4 to 192.168.1.0/24 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 type require[ ... ]

SAD:esp tunnel from 5.6.7.8 to 1.2.3.4 spi 0x027fa231 auth hmac-sha2-256 enc aesesp tunnel from 1.2.3.4 to 5.6.7.8 spi 0x13ebc203 auth hmac-sha2-256 enc aesesp tunnel from 1.2.3.4 to 5.6.7.8 spi 0x25da85ac auth hmac-sha2-256 enc aesesp tunnel from 5.6.7.8 to 1.2.3.4 spi 0x891aa39b auth hmac-sha2-256 enc aes[ ... ]VPN1#

Well, since everything seems to be working fine, we can configure the system to automatically start the VPN at boot by adding the following variables in /etc/rc.conf.local(8) on both security gateways:

/etc/rc.conf.localisakmpd_flags="-K" # Avoid keynote(4) policy checkingipsec=YES # Load ipsec.conf(5) rules

3.4 Packet filtering

IPsec traffic can be filtered on the enc(4) interface, where it appears unencrypted before encapsualtion and after decapsulation. The following are the main points to keep in mind for filtering IPsec traffic:

IPsec protocols  (AH and/or ESP) must be explicitely allowed on the external interface; e.g.:

# Allow ESP encapsulated IPsec traffic on the external interface pass in on $ext_if proto esp from $remote_gw to $ext_if pass out on $ext_if proto esp from $ext_if to $remote_gw

isakmpd(8)  requires that UDP traffic on ports 500 (isakmp) and 4500 (ipsec-nat-t) be allowed on the external interface; e.g.:

# Allow isakmpd(8) traffic on the external interface

Page 9: Building VPNs on OpenBSD

pass in on $ext_if proto udp from $remote_gw to $ext_if port {isakmp, ipsec-nat-t}

pass out on $ext_if proto udp from $ext_if to $remote_gw port {isakmp, ipsec-nat-t}

if the VPN is in tunnel mode, IP-in-IP traffic between the two gateways must be allowed on the enc(4) interface: e.g.:

# Allow IP-in-IP traffic between the gateways on the enc(4) interface

pass in on enc0 proto ipencap from $remote_gw to $ext_if keep state (if-bound)

pass out on enc0 proto ipencap from $ext_if to $remote_gw keep state (if-bound)

as stated before, IPsec traffic filtering is done on the enc(4) interface, where it appears unencrypted. State on the enc(4) interface should be interface bound; e.g.:

# Filter unencrypted VPN traffic on the enc(4) interface pass in on enc0 from $remote_nets to $int_if:network keep state

(if-bound) pass out on enc0 from $int_if:network to $remote_nets keep state

(if-bound)

3.5 Redundant VPNs with sasyncd(8)

One of the most interesting features of OpenBSD's implementation of the IPsec protocol is the possibility to set up multiple VPN gateways in a redundant configuration, allowing for transparent failover of VPN connections without any loss of connectivity.

Typically, in OpenBSD, redundancy at the network level is achieved through the carp(4) protocol, which allows multiple hosts on the same local network to share a common IP address. Redundancy at the logical VPN layer, instead, is provided by the sasyncd(8) daemon, which allows the synchronization of IPsec SA and SPD information between multiple IPsec gateways.

We have already covered the carp(4) protocol in a previous document about redundant firewalls, so we won't come back to this topic now; therefore, I assume that you already have a working carp(4) setup and that you have modified your configuration accordingly (in particular the ipsec.conf(5) and pf.conf(5) files).

Please note that, as stated in the documentation, for SAs with replay protection enabled, such as those created by isakmpd(8), the sasyncd(8) hosts must have pfsync(4) enabled to synchronize the in-

Page 10: Building VPNs on OpenBSD

kernel SA replay counters (for a detailed discussion of the pfsync(4) protocol, please refer to [CARP]).

The sasyncd(8) daemon is configured through the /etc/sasyncd.conf(5) file, which has a rather self-explanatory syntax; below is a sample configuration file:

/etc/sasyncd.conf# carp(4) interface to track state changes oninterface carp0# Interface group to use to suppress carp(4) preemption during bootgroup carp# sasyncd(8) peer IP address or hostname. Multiple 'peer' statements are allowedpeer 172.16.0.253# Shared AES key used to encrypt messages between sasyncd(8) hosts. It can be# generated with the openssl(1) command 'openssl rand -hex 32'sharedkey 0x115c413529ba5ac96b208d83a50473b3e6ade60e66c59a10a944ad3d273148dd

Since sasyncd.conf(5) contains the shared secret key used to encrypt data between the sasyncd(8) hosts, it should have restrictive permissions (600) and belong to the "root" or "_isakmpd" user:

# chown root /etc/sasyncd.conf# chmod 600 /etc/sasyncd.conf

Well, now we're ready to run the sasyncd(8) daemon on the redundant gateways; but first we need to restart isakmpd(8) with the "-S" option, which is mandatory on redundant setups (remember to add it also to isakmpd_flags in /etc/rc.conf.local(8)):

# pkill isakmpd# isakmpd -S -K# sasyncd

You can use ipsecctl(8) to verify that SAs are correctly synchronized between the IPsec gateways. Finally, if everything is working fine, we only have to add the following variable to the/etc/rc.conf.local(8) file to automatically start sasyncd(8) on boot.

/etc/rc.conf.localsasyncd_flags=""

Page 11: Building VPNs on OpenBSD

Note: sasyncd(8) must be manually restarted every time isakmpd(8) is restarted.

Building VPNs on OpenBSD

Previous: 2. IPsec overview   Up: Table of contents  Next: 4. OpenVPN

Page 12: Building VPNs on OpenBSD

Edificio VPNs en OpenBSD

Anterior: 2.   Resumen de IPsec   Up: tabla de contenidos   siguiente: 4. OpenVPN

3. IPsec en OpenBSDAhora que tenemos un conocimiento adecuado de la arquitectura de IPsec y los protocolos, estamos finalmente listos para pasar de la teoría a la práctica y empezar a divertirse con OpenBSD!

OpenBSD incluye por defecto con soporte completo de IPsec en el kernel stock y proporciona un conjunto de demonios de espacio de usuario y herramientas para la gestión de configuración de IPsec, intercambio de claves dinámica y alta disponibilidad; y lo bueno es que, como veremos, configurar una VPN con IPsec en OpenBSD es una tarea increíblemente sencilla y rápida, sobre todo en comparación a la mayoría otras implementaciones de IPsec por ahí.

Pero antes de proceder a editar archivos de configuración y ejecutar comandos de sistema, vamos a echar un vistazo a la topología de la red básica de la VPN que vamos a establecer en este documento, es una forma muy sencilla VPN de sitio a sitio   , con un par de pasarelas de seguridad multi-homed (VPN1 y VPN2) une dos redes remotas privadas (172.16.0.0/24 y 192.168.0.0/24).

En este capítulo, vamos a establecer la VPN usando IPsec: para ser más precisos, vamos a configurarlo en modo de túnel   (la única opción de VPN red a red) y utilizar la Protocolo ESP   para cifrar el tráfico VPN que atraviesa Internet; también consideraremos el caso de gateways de IPsec redundantes   con CARP(4)   . Entonces, en los próximos capítulos, veremos cómo el mismo VPN puede ser implementado usando soluciones alternativas, en particular OpenVPN   y OpenSSH   .

Page 13: Building VPNs on OpenBSD

3.1 pasos preliminares de

Antes de proceder a configurar IPsec, tenemos que realizar unos pasos previos para asegurarse de que los sistemas están configurados correctamente para que IPsec funcione correctamente. Los protocolos de IPsec están habilitados o deshabilitados en la pila de TCP/IP de los sistemas operativos a través de dos sysctl (3)las variables: net.inet.esp.enable y net.inet.ah.enable, ambos habilitados de forma predeterminada, puede comprobarlo ejecutando el sysctl (8)   comando:

# net.inet.esp.enable de sysctlnet.inet.ESP.Enable=1# net.inet.ah.enable de sysctlnet.inet.ah.Enable=1

Desde nuestros gateways VPN tendrá que realizar el enrutamiento de tráfico, también tenemos que habilitar el reenvío de IP, que es desactivado por defecto. Hecho esto, otra vez, con sysctl (8), estableciendo el valor de la net.inet.ip.forwarding variable a "1" Si desea cualquier tipo de tráfico que se debe reenviar o "2" Si desea restringir el reenvío de tráfico IPsec procesa sólo:

# net.inet.ip.forwarding=1 de sysctlnet.inet.IP.Forwarding: 0 -> 1

Opcionalmente , también puede habilitar el protocolo de compresión de carga útil IP (IPComp) reducir el tamaño de los datagramas IP para un mayor rendimiento VPN; sin embargo, tenga en cuenta que la reducción de ancho de banda viene a expensas de una mayor carga computacional (ver [RFC3173] para más detalles):

# net.inet.ipcomp.enable=1 de sysctlnet.inet.ipcomp.Enable: 0 -> 1

Para hacer estos ajustes permanentes en los rearranques, agregue las siguientes variables para la /etc/sysctl.conf(5)   archivo:

/etc/sysctl.conf[ ... ]net.inet.ESP.Enable=1 # Habilitar el protocolo ESP IPsecnet.inet.ah.Enable=1 # Habilitar el protocolo IPsec AHnet.inet.IP.Forwarding=1 # habilitar IP forwarding para el host. Establece en '2' para                          # adelante solamente el tráfico de IPsecnet.inet.ipcomp.Enable=1 # opcional: comprimir datagramas IP

Por último, tenemos que traer la enc (4)   interfaz de red virtual de . Esta interfaz le permite inspeccionar el tráfico IPsec saliente antes de se encapsula y

Page 14: Building VPNs on OpenBSD

el tráfico IPsec entrante después de decapsulated; Esto es principalmente útil para filtrado de tráfico IPsec   con PF y para propósitos de depuración.

# enc0 ifconfig up

Para que el sistema trae automáticamente el enc (4)   de interfaz en el arranque, crear el /etc/hostname.enc0   archivo de configuración:

/etc/hostname.enc0hasta

3.2 configuración de la PKI

De OpenBSD IKE   demonio de gestión de claves, isakmpd (8)   , se basa en certificados de clave pública para la autenticación y por lo tanto requiere que primero establezca por una infraestructura de clave pública (PKI) para la gestión de certificados digitales.

El primer paso en la configuración de la PKI es la creación del certificado raíz CA (/etc/ssl/ca.crt) y la clave privada (/etc/ssl/private/ca.key) en la máquina de la firma (que no tiene que ser necesariamente una de las pasarelas VPN) usando OpenSSL (1)   ; por ejemplo:

CA # openssl req - x 509 - días 365 - newkey rsa:1024 \> -keyout /etc/ssl/private/ca.key \> -a /etc/ssl/ca.crtGenerar una clave privada de RSA de 1024 bits........................................++++++......++++++escribir la nueva clave privada a ' / etc/ssl/private/ca.key'Ingrese frase PEM: < contraseña >Verificar - Introduzca frase PEM: < contraseña >-----Va a pedir que introduzca la información que se incorporaráen su solicitud de certificado.Lo que usted está a punto de entrar es lo que se llama un nombre distintivo o un DN.Hay bastantes campos pero puedes dejar algunas en blancoPara algunos campos será un valor predeterminado,Si introduce '.', el campo quedará en blanco.-----[De] (código de 2 Letras) nombre de país: seEstado o provincia de nombre [] (nombre completo): ItaliaLocalidad nombre (eg, city) []: MilánOrganización nombre (eg, company) []: Kernel Panic Inc.Organizacional [] nombre de la unidad (por ejemplo, la sección): IPsecNombre común (por ejemplo, completamente calificado nombre) []: CA.kernel-panic.it[] Dirección de correo electrónico: [email protected] #

Page 15: Building VPNs on OpenBSD

El siguiente paso es la creación de un certificado de firma solicitar (CSR) en cada uno de los pares de IKE; por ejemplo, el siguiente comando va a generar el CSR (/etc/isakmpd/private/1.2.3.4.csr) para la máquina de VPN1 (la dirección IP, en este caso "1.2.3.4", se utiliza como identificador único):

VPN1 # openssl req-nuevo - clave /etc/isakmpd/private/local.key \>  -a /etc/isakmpd/private/1.2.3.4.csrVa a pedir que introduzca la información que se incorporaráen su solicitud de certificado.Lo que usted está a punto de entrar es lo que se llama un nombre distintivo o un DN.Hay bastantes campos pero puedes dejar algunas en blancoPara algunos campos será un valor predeterminado,Si introduce '.', el campo quedará en blanco.-----[De] (código de 2 Letras) nombre de país: seEstado o provincia de nombre [] (nombre completo): ItaliaLocalidad nombre (eg, city) []: MilánOrganización nombre (eg, company) []: Kernel Panic Inc.Organizacional [] nombre de la unidad (por ejemplo, la sección): IPsecNombre común (por ejemplo, completamente calificado nombre) []: 1.2.3.4[] Dirección de correo electrónico: [email protected] Introduce los siguientes atributos 'Extras'a ser enviado con su solicitud de certificadoUn desafío [contraseña]: < entrar >Una empresa opcional nombre []: < entrar >VPN1 #

A continuación, el CSR debe enviarse a la CA, que generará los certificados de las solicitudes de certificado. Por ejemplo, suponiendo que la RSE es el archivo en el directorio actual:

CA # env CERTIP = 1.2.3.4 openssl x 509 - req \>  -días 365 - en 1.2.3.4.csr-a 1.2.3.4.crt \>  /Etc/ssl/ca.crt -CA-CAkey /etc/ssl/private/ca.key \>  -CAcreateserial - extfile /etc/ssl/x509v3.cnf-x509v3_IPAddr de extensionesOk firmatema = / C lo = / ST = Italia/L = Milán/O = la [email protected] Inc./OU=IPsec/CN=1.2.3.4/ Kernel PanicObtener la clave privada de CAIntroduzca la frase de /etc/ssl/private/ca.key: < contraseña >CA #

Finalmente, necesitará copiar los certificados generados recientemente (los archivos terminados en .crt) a las máquinas respectivas en la / etc/isakmpd/certs /directorio, así como el certificado de la CA (/etc/ssl/ca.crt) en / etc/isakmpd/ca /.

3.3 configuración

Page 16: Building VPNs on OpenBSD

Por lo que nos hemos situado el sistema de IPsec utiliza y genera todos los certificados necesarios para la autenticación de IKE peer; ahora está finalmente listos para configurar nuestra conexión VPN. En OpenBSD, toda la configuración de IPsec lleva a cabo en un solo archivo, /etc/ipsec.conf(5), que utiliza una sintaxis muy compacta, similar a PF.conf (5), para definir casi cada característica de la VPN; el formato básico del archivo es el siguiente:

líneas de comentario comienzan con un carácter de hash ("#") y se extienden hasta el final de la línea;

las reglas pueden abarcar múltiples líneas con el carácter de barra diagonal inversa ("\");

direcciones de red pueden ser especificadas en notación CIDR, como nombres de host simbólico, nombres de interfaces o nombres de grupo de interfaces;

para simplificar el archivo de configuración, pueden utilizar las macros; nombres de macro deben empezar con una letra y pueden contener letras, números y guiones bajos no deben ser palabras reservadas;

ciertos parámetros (por ejemplo direcciones IP) pueden ser expresados como listas; las listas son separados por comas y encerradas en llaves.

Hay diferentes tipos de IPSec.conf(5)   normas, dependiendo de si desea flujos de IPsec y SAs que se creará automáticamente (usando isakmpd (8)) o manualmente; sólo consideraremos el primer caso (que suele ser lo que quieras), así que por favor, consulte el documentación   para más detalles sobre la configuración manual. La sintaxis es la siguiente:

IKE [modo] [truncado] [tmode] [proto Protocolo] \de la fuente [puerto sport] [(srcnat)] a dst [puerto dport] \[local localip] [peer remoto] \    [modo auth algoritmo enc algoritmo grupo Grupo] \[auth rápido algoritmo enc algoritmo grupo Grupo] \[srcid cadena] [dstid cadena] \[psk string] [ cadena de la etiqueta]

Aunque parezca algo complejo en primera, reales las normas son generalmente muy corto y simple porque la mayoría de los parámetros puede ser omitida, en cuyo caso se utilizan los valores predeterminados. Pero veamos la sintaxis de las reglas en detalle:

IKE [modo] [truncado] [tmode]

Page 17: Building VPNs on OpenBSD

el IKE palabra clave especifica isakmpd (8)   debe utilizarse para establecer automáticamente las asociaciones de seguridad de este flujo; modo de puede ser una "activo " (isakmpd (8)   inmediatamente se iniciará la negociación de este túnel)," pasivo "(para esperar una solicitud entrante desde el interlocutor remoto iniciar negociación) o" dinámica "(que se utilizará para hosts con direcciones IP dinámicas) y a" activo "; truncado especifica el Protocolo de encapsulamiento   y puede ser una " ESP "(por defecto) o" ah "; TMODE es el modo de transporte   a utilizar, es decir, " túnel "(por defecto) o" transporte".

proto Protocolo

Restringir el flujo a un protocolo específico de IP (TCP, UDP, ICMP); por defecto se admiten todos los protocolos.

de la fuente [puerto sport] [(srcnat)] a dst [puerto dport]

Especificar las direcciones origen y destino de los paquetes que se aplica esta regla, también puede especificar los puertos fuente y destino, pero sólo en conjunción con los protocolos TCP o UDP. La srcnat parámetro puede utilizarse para especificar la dirección de la fuente real en escenarios NAT/BINAT salidas.

local localip peer remoto

Especificar los extremos locales y remotos de la VPN; el extremo local sólo es necesario si la máquina tiene varias direcciones el extremo remoto puede omitirse si corresponde a la horario de verano parámetro.

modo de auth algoritmo enc algoritmo grupo GrupoEspecificar el modo ("principal"o"agresivo") y transformaciones criptográficas para Negociación de IKE fase 1   ; consulte el documentación   para una lista completa de los valores posibles y sus valores por defecto.

auth rápido algoritmo enc algoritmo grupo Grupo

Especificar las transformaciones criptográficas para Negociación de IKE fase 2   ; consulte el documentación   para una lista completa de los valores posibles y sus valores por defecto.

srcid cadena dstid cadena

Definir la única identificación isakmpd (8)   a utilizar como la identidad del local (srcid) y remota (dstid) pares; si se omite, se utiliza la dirección IP.

PSK string

Utilizar una clave previamente compartida para la autenticación en lugar de isakmpd (8)   .

cadena de la etiqueta

Agregar un PF (4)   etiqueta para paquetes de IPsec que empareja esta regla.

Page 18: Building VPNs on OpenBSD

Así que vamos a escribir los archivos de configuración para la VPN de sitio a sitio   Estamos configurando; como veremos, es una tarea realmente sencilla y harán algunas reglas. En el host VPN1, el /etc/ipsec.conf(5)   archivo tendrá el siguiente aspecto:

/etc/IPSec.conf# Macrosext_if = "rl0" interfaz externa # (1.2.3.4)local_net = "172.16.0.0/24" red privada Local #remote_gw = "5.6.7.8" gateway de IPsec remoto #remote_nets = "{192.168.0.0/24 y 192.168.1.0/24}" redes privadas remoto # # Configurar la VPN entre las máquinas de gatewayIKE esp de $ext_if a $remote_gw# Entre pasarela local y redes remotasIKE esp de $ext_if a $remote_nets par $remote_gw# Entre las redesIKE esp de $local_net a $remote_nets par $remote_gw

y VPN2:

/etc/IPSec.conf# Macrosext_if = "rl0" interfaz externa # (5.6.7.8)local_nets = "{192.168.0.0/24 y 192.168.1.0/24}" redes privadas locales #remote_gw = "1.2.3.4" gateway de IPsec remoto #remote_net = "172.16.0.0/24" red privada remoto # # Configurar la VPN entre las máquinas de gatewayIKE esp de $ext_if a $remote_gw# Entre el gateway local y remotoIKE pasivo esp de $ext_if a $remote_net par $remote_gw# Entre las redesIKE esp de $local_nets a $remote_net par $remote_gw

Ahora estamos listos para iniciar la isakmpd (8)   demonio en ambas entradas; lo haremos ejecutar en primer plano ("-d" opción) para fácil notar los errores:

# isakmpd -K -d 

Luego, otra vez en ambas puertas de enlace, podemos analizar IPSec.conf(5)   las reglas ("- n" opción de ipsecctl(8)) y, si se presenta sin errores, cargar:

# ipsecctl - n -f /etc/ipsec.conf# ipsecctl -f /etc/ipsec.conf

Usted puede comprobar que IPsec fluye y SAs ha sido correctamente configurado ejecutando ipsecctl(8)   con el " -s todos "opción; por ejemplo:

VPN1 # ipsecctl -s todos

Page 19: Building VPNs on OpenBSD

FLUJOS:flujo esp en de 192.168.0.0/24 a 1.2.3.4 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 tipo usoesp de flujo hacia fuera de 1.2.3.4 a 192.168.0.0/24 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 tipo requierense derivan especialmente en 192.168.1.0/24 a 1.2.3.4 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 tipo usoesp de flujo hacia fuera de 1.2.3.4 a 192.168.1.0/24 peer 5.6.7.8 srcid 1.2.3.4/32 dstid 5.6.7.8/32 tipo requieren[ ... ] SAD:túnel de ESP de 5.6.7.8 a 1.2.3.4 spi 0x027fa231 auth enc hmac-sha2-256 aestúnel de ESP de 1.2.3.4 a 5.6.7.8 spi 0x13ebc203 auth enc hmac-sha2-256 aestúnel de ESP de 1.2.3.4 a 5.6.7.8 spi 0x25da85ac auth enc hmac-sha2-256 aestúnel de ESP de 5.6.7.8 a 1.2.3.4 spi 0x891aa39b auth enc hmac-sha2-256 aes[ ... ]VPN1 #

Bien, ya que todo parece estar funcionando bien, podemos configurar el sistema para iniciar automáticamente la VPN en el arranque, añadiendo las siguientes variables en /etc/rc.conf.local(8)   en dos gateways de seguridad:

/etc/rc.conf.localisakmpd_flags = "-K" # Evite Keynote(4)   política de controlipsec = YES # carga IPSec.conf(5)   reglas de

3.4 filtrado de paquetes de

Tráfico IPsec puede ser filtrada en el enc (4)   interfaz de , donde aparece sin cifrar antes de encapsualtion y después de la desencapsulación. Los siguientes son los principales puntos a tener en cuenta para el filtrado de tráfico IPsec:

Protocolos IPsec   (AH o ESP) debe ser explícitamente permitido en la interfaz externa; por ejemplo:

         # Permitir que ESP encapsula tráfico IPsec en la interfaz externa         pasar en $ext_if proto esp de $remote_gw a $ext_if         paso en $ext_if proto esp de $ext_if a $remote_gw

isakmpd (8)   requiere que el tráfico UDP puertos 500 (isakmp) y 4500 (- nat-t de ipsec) permitido en la interfaz externa; por ejemplo:

         # Permite isakmpd (8)   tráfico en la interfaz externa         pasar en $ext_if proto udp desde $remote_gw al puerto $ext_if

{isakmp, ipsec nat-t}

Page 20: Building VPNs on OpenBSD

         paso hacia fuera en $ext_if proto udp de $ext_if al puerto de $remote_gw {isakmp, ipsec nat-t}

si el VPN es de modo de túnel   , Tráfico IP en IP entre las dos puertas de entrada debe ser en el enc (4)   interfaz: por ejemplo:

         Tráfico # permitir IP en IP entre las puertas de entrada en el enc (4)   interfaz de

         transmitir en enc0 proto ipencap de $remote_gw $ext_if mantener estado (if-bound)

         paso hacia fuera en enc0 proto ipencap de $ext_if $remote_gw mantener estado (if-bound)

como se dijo antes, filtrado de tráfico IPsec se realiza en el enc (4)   interfaz de , donde aparece sin cifrar. Estado en el enc (4)   debe ser la interfaz interfaz atado; por ejemplo:

         # Filtro de tráfico no cifrado de VPN en el enc (4)   interfaz de         pase en enc0 de $remote_nets a $int_if: mantener estado (if-bound)

de la red         paso a enc0 de $int_if: red de $remote_nets Guardar estado (if-

bound)

3.5 redundante VPN con sasyncd(8)

Una de las características más interesantes de la aplicación de OpenBSD del protocolo IPsec es la posibilidad de configurar múltiples gateways VPN en una configuración redundante, permitiendo failover transparente de conexiones VPN sin pérdida de conectividad.

Por lo general, en OpenBSD, redundancia en el nivel de red se logra a través de la CARP(4)   Protocolo de , que permite a los hosts múltiples en la misma red local para compartir una dirección IP común. Redundancia en la capa VPN lógica, en cambio, es proporcionada por el sasyncd(8)   daemon, que permite la sincronización de IPsec SA   y SPD   información entre múltiples pasarelas IPsec.

Ya hemos cubierto el CARP(4)   Protocolo en un documento anterior   sobre firewalls redundantes, por lo que no volvemos a este tema ahora; por lo tanto, supongo que ya tienes un trabajo CARP(4)   instalación y que han modificado su configuración en consecuencia (en particular la ipsec.conf(5)   y PF.conf (5)   los archivos).

Por favor, tenga en cuenta que, como se indica en el documentación   , para SAs con protección de repetición activada, como los creados por isakmpd (8)   la sasyncd(8)los hosts deben tener pfsync(4)   para sincronizar los contadores de reproducción núcleo SA (para una discusión detallada de la pfsync(4)   de protocolo, consulte [carpa]).

Page 21: Building VPNs on OpenBSD

El sasyncd(8)   daemon se configura a través de la /etc/sasyncd.conf(5)   archivo, el cual tiene una sintaxis bastante explica por sí mismo, a continuación es un archivo de configuración de ejemplo:

/etc/sasyncd.conf# CARP(4)   interfaz de seguimiento de los cambios de estado eninterfaz carp0Grupo de # interfaz usar para suprimir CARP(4)   preferencia durante el arranquecarpa de grupo# sasyncd(8)   pares IP dirección o nombre de host. Se permiten múltiples instrucciones de 'pares'Peer 172.16.0.253Tecla de # compartido AES utilizada para cifrar los mensajes entre sasyncd(8)   hosts. Puede ser# generado con el OpenSSL (1)   comando ' openssl rand-hexagonal 32'sharedkey 0x115c413529ba5ac96b208d83a50473b3e6ade60e66c59a10a944ad3d273148dd

Puesto que sasyncd.conf(5)   contiene la clave secreta compartida utilizada para cifrar los datos entre las sasyncd(8)   anfitriones, debe tener permisos restrictivos (600) y pertenecen al usuario "root" o "_isakmpd":

# chown root /etc/sasyncd.conf# chmod 600 /etc/sasyncd.conf

Pues bien, ahora estamos listos para ejecutar el sasyncd(8)   demonio en los gateways redundantes; pero primero tenemos que reiniciar isakmpd (8)   con el " -S "opción, que es obligatoria en configuraciones redundantes (recuerda añadir también a isakmpd_flags en /etc/rc.conf.local(8)   ):

# pkill isakmpd# isakmpd -S -K# sasyncd

Se puede utilizar ipsecctl(8)   para verificar que el SAs se sincronizan correctamente entre las pasarelas IPsec. Por último, si todo funciona bien, solo tenemos que añadir la siguiente variable a la/etc/rc.conf.local(8)   archivo que inicie automáticamente sasyncd(8)   en el arranque.

/etc/rc.conf.localsasyncd_flags = ""

Nota : sasyncd(8)   debe ser reiniciado manualmente cada vez isakmpd (8)   se reinicia el.

Edificio VPNs en OpenBSD

Page 22: Building VPNs on OpenBSD

Anterior: 2.   Resumen de IPsec   Up: tabla de contenidos   siguiente: 4. OpenVPN