Sie sind auf Seite 1von 22

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 siteto-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
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.enable
net.inet.esp.enable=1
# sysctl net.inet.ah.enable
net.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=1
net.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=1
net.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
net.inet.ah.enable=1

# Enable the ESP IPsec protocol


# Enable the AH IPsec protocol

net.inet.ip.forwarding=1
'2' to
net.inet.ipcomp.enable=1

# Enable IP forwarding for the host. Set it to


#
forward only IPsec traffic
# 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.enc0
up

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.crt
Generating 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 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) []: IT


State or Province Name (full name) []: Italy
Locality Name (eg, city) []: Milan
Organization Name (eg, company) []: Kernel Panic Inc.
Organizational Unit Name (eg, section) []: IPsec
Common Name (eg, fully qualified host name) []: CA.kernel-panic.it
Email Address []: danix@kernel-panic.it
CA#

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.csr
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) []: IT
State or Province Name (full name) []: Italy
Locality Name (eg, city) []: Milan
Organization Name (eg, company) []: Kernel Panic Inc.
Organizational Unit Name (eg, section) []: IPsec
Common Name (eg, fully qualified host name) []: 1.2.3.4
Email Address []: danix@kernel-panic.it
Please enter the following 'extra' attributes
to be sent with your certificate request
A 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_IPAddr
Signature ok
subject=/C=IT/ST=Italy/L=Milan/O=Kernel Panic
Inc./OU=IPsec/CN=1.2.3.4/emailAddress=danix@kernel-panic.it
Getting CA Private Key
Enter pass phrase for /etc/ssl/private/ca.key: <passphrase>
CA#

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:
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.


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
# Macros
ext_if
(1.2.3.4)
local_net
remote_gw
remote_nets
networks

= "rl0"

# External interface

= "172.16.0.0/24"
= "5.6.7.8"
= "{192.168.0.0/24, 192.168.1.0/24}"

# Local private network


# Remote IPsec gateway
# Remote private

# Set up the VPN between the gateway machines


ike esp from $ext_if to $remote_gw
# Between local gateway and remote networks
ike esp from $ext_if to $remote_nets peer $remote_gw
# Between the networks
ike esp from $local_net to $remote_nets peer $remote_gw

and on VPN2:
/etc/ipsec.conf
# Macros
ext_if
(5.6.7.8)
local_nets
remote_gw
remote_net

= "rl0"

# External interface

= "{192.168.0.0/24, 192.168.1.0/24}"
= "1.2.3.4"
= "172.16.0.0/24"

# Local private networks


# Remote IPsec gateway
# Remote private network

# Set up the VPN between the gateway machines


ike esp from $ext_if to $remote_gw
# Between local gateway and remote network
ike passive esp from $ext_if to $remote_net peer $remote_gw
# Between the networks
ike 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

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 all
FLOWS:
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 use
flow 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 require
flow 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 use
flow 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
aes
esp tunnel
aes
esp tunnel
aes
esp tunnel
aes
[ ... ]
VPN1#

from 5.6.7.8 to 1.2.3.4 spi 0x027fa231 auth hmac-sha2-256 enc


from 1.2.3.4 to 5.6.7.8 spi 0x13ebc203 auth hmac-sha2-256 enc
from 1.2.3.4 to 5.6.7.8 spi 0x25da85ac auth hmac-sha2-256 enc
from 5.6.7.8 to 1.2.3.4 spi 0x891aa39b auth hmac-sha2-256 enc

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.local
isakmpd_flags="-K"
ipsec=YES

# Avoid keynote(4) policy checking


# 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
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 inkernel 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 on
interface carp0
# Interface group to use to suppress carp(4) preemption during boot
group
carp
# sasyncd(8) peer IP address or hostname. Multiple 'peer' statements are
allowed
peer
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.local
sasyncd_flags=""

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

Edificio VPNs en OpenBSD


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

3. IPsec en OpenBSD
Ahora que tenemos un conocimiento adecuado de la arquitectura de
IPsec y los protocolos, estamos finalmente listos para pasar de la teora a
la prctica 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 gestin de configuracin de IPsec, intercambio de
claves dinmica y alta disponibilidad; y lo bueno es que, como veremos,
configurar una VPN con IPsec en OpenBSD es una tarea increblemente
sencilla y rpida, sobre todo en comparacin a la mayora otras
implementaciones de IPsec por ah.
Pero antes de proceder a editar archivos de configuracin y ejecutar
comandos de sistema, vamos a echar un vistazo a la topologa de la red
bsica 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 captulo, vamos a establecer la VPN usando IPsec: para ser ms


precisos, vamos a configurarlo en modo de tnel (la nica opcin de VPN
red a red) y utilizar la Protocolo ESP para cifrar el trfico VPN que
atraviesa Internet; tambin consideraremos el caso de gateways de IPsec
redundantes con CARP(4) . Entonces, en los prximos captulos,
veremos cmo el mismo VPN puede ser implementado usando
soluciones alternativas, en particular OpenVPN y OpenSSH .

3.1 pasos preliminares de


Antes de proceder a configurar IPsec, tenemos que realizar unos pasos
previos para asegurarse de que los sistemas estn configurados
correctamente para que IPsec funcione correctamente. Los protocolos de
IPsec estn habilitados o deshabilitados en la pila de TCP/IP de los
sistemas operativos a travs 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 sysctl
net.inet.ESP.Enable=1
# net.inet.ah.enable de sysctl
net.inet.ah.Enable=1

Desde nuestros gateways VPN tendr que realizar el enrutamiento de


trfico, tambin tenemos que habilitar el reenvo 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 trfico que se debe reenviar o "2" Si desea restringir el
reenvo de trfico IPsec procesa slo:
# net.inet.ip.forwarding=1 de sysctl
net.inet.IP.Forwarding: 0 -> 1

Opcionalmente , tambin puede habilitar el protocolo de compresin de


carga til IP (IPComp) reducir el tamao de los datagramas IP para un
mayor rendimiento VPN; sin embargo, tenga en cuenta que la reduccin
de ancho de banda viene a expensas de una mayor carga computacional
(ver [RFC3173] para ms detalles):
# net.inet.ipcomp.enable=1 de sysctl
net.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 IPsec
net.inet.ah.Enable=1 # Habilitar el protocolo IPsec AH
net.inet.IP.Forwarding=1 # habilitar IP forwarding para el
host. Establece en '2' para
# adelante solamente el trfico de IPsec
net.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 trfico IPsec saliente antes de se

encapsula y el trfico IPsec entrante despus de decapsulated; Esto es


principalmente til para filtrado de trfico IPsec con PF y para propsitos
de depuracin.
# enc0 ifconfig up

Para que el sistema trae automticamente el enc (4) de interfaz en el


arranque, crear el /etc/hostname.enc0 archivo de configuracin:
/etc/hostname.enc0
hasta

3.2 configuracin de la PKI


De OpenBSD IKE demonio de gestin de claves, isakmpd (8) , se basa
en certificados de clave pblica para la autenticacin y por lo tanto
requiere que primero establezca por una infraestructura de clave pblica
(PKI) para la gestin de certificados digitales.
El primer paso en la configuracin de la PKI es la creacin del certificado
raz CA (/etc/ssl/ca.crt) y la clave privada (/etc/ssl/private/ca.key) en la
mquina de la firma (que no tiene que ser necesariamente una de las
pasarelas VPN) usando OpenSSL (1) ; por ejemplo:
CA # openssl req - x 509 - das 365 - newkey rsa:1024 \
> -keyout /etc/ssl/private/ca.key \
> -a /etc/ssl/ca.crt
Generar una clave privada de RSA de 1024 bits
........................................++++++
......++++++
escribir la nueva clave privada a ' / etc/ssl/private/ca.key'
Ingrese frase PEM: < contrasea >
Verificar - Introduzca frase PEM: < contrasea >
----Va a pedir que introduzca la informacin 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 blanco
Para algunos campos ser un valor predeterminado,
Si introduce '.', el campo quedar en blanco.
----[De] (cdigo de 2 Letras) nombre de pas: se
Estado o provincia de nombre [] (nombre completo): Italia
Localidad nombre (eg, city) []: Miln
Organizacin nombre (eg, company) []: Kernel Panic Inc.
Organizacional [] nombre de la unidad (por ejemplo, la seccin): IPsec
Nombre comn (por ejemplo, completamente calificado nombre)
[]: CA.kernel-panic.it
[] Direccin de correo electrnico: danix@kernel-panic.it
CA #

El siguiente paso es la creacin 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 mquina de
VPN1 (la direccin 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.csr
Va a pedir que introduzca la informacin 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 blanco
Para algunos campos ser un valor predeterminado,
Si introduce '.', el campo quedar en blanco.
----[De] (cdigo de 2 Letras) nombre de pas: se
Estado o provincia de nombre [] (nombre completo): Italia
Localidad nombre (eg, city) []: Miln
Organizacin nombre (eg, company) []: Kernel Panic Inc.
Organizacional [] nombre de la unidad (por ejemplo, la seccin): IPsec
Nombre comn (por ejemplo, completamente calificado nombre) []: 1.2.3.4
[] Direccin de correo electrnico: danix@kernel-panic.it
Introduce los siguientes atributos 'Extras'
a ser enviado con su solicitud de certificado
Un desafo [contrasea]: < entrar >
Una empresa opcional nombre []: < entrar >
VPN1 #

A continuacin, 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 \
> -das 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
extensiones
Ok firma
tema = / C lo = / ST = Italia/L = Miln/O = la emailAddress=danix@kernelpanic.it Inc./OU=IPsec/CN=1.2.3.4/ Kernel Panic
Obtener la clave privada de CA
Introduzca la frase de /etc/ssl/private/ca.key: < contrasea >
CA #

Finalmente, necesitar copiar los certificados generados recientemente


(los archivos terminados en .crt) a las mquinas respectivas en la /
etc/isakmpd/certs /directorio, as como el certificado de la CA
(/etc/ssl/ca.crt) en / etc/isakmpd/ca /.
3.3 configuracin

Por lo que nos hemos situado el sistema de IPsec utiliza y genera todos
los certificados necesarios para la autenticacin de IKE peer; ahora est
finalmente listos para configurar nuestra conexin VPN. En OpenBSD,
toda la configuracin 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 caracterstica de la VPN; el formato
bsico del archivo es el siguiente:

lneas de comentario comienzan con un carcter de hash ("#") y se


extienden hasta el final de la lnea;

las reglas pueden abarcar mltiples lneas con el carcter de barra


diagonal inversa ("\");

direcciones de red pueden ser especificadas en notacin CIDR,


como nombres de host simblico, nombres de interfaces o
nombres de grupo de interfaces;

para simplificar el archivo de configuracin, pueden utilizar las


macros; nombres de macro deben empezar con una letra y pueden
contener letras, nmeros y guiones bajos no deben ser palabras
reservadas;

ciertos parmetros (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 automticamente (usando isakmpd
(8)) o manualmente; slo consideraremos el primer caso (que suele ser
lo que quieras), as que por favor, consulte el documentacin para ms
detalles sobre la configuracin 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 rpido 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 mayora de los parmetros
puede ser omitida, en cuyo caso se utilizan los valores
predeterminados. Pero veamos la sintaxis de las reglas en detalle:
IKE [modo] [truncado] [tmode]

el IKE palabra clave especifica isakmpd (8) debe utilizarse para


establecer automticamente las asociaciones de seguridad de este
flujo; modo de puede ser una "activo " (isakmpd (8) inmediatamente
se iniciar la negociacin de este tnel)," pasivo "(para esperar una
solicitud entrante desde el interlocutor remoto iniciar negociacin)
o" dinmica "(que se utilizar para hosts con direcciones IP
dinmicas) 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,
" tnel "(por defecto) o" transporte".

proto Protocolo

Restringir el flujo a un protocolo especfico 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, tambin puede especificar los puertos fuente y
destino, pero slo en conjuncin con los protocolos TCP o
UDP. La srcnat parmetro puede utilizarse para especificar la
direccin 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 slo es necesario si la mquina tiene varias direcciones el
extremo remoto puede omitirse si corresponde a la horario de
verano parmetro.
modo de auth algoritmo enc algoritmo grupo Grupo

Especificar el modo ("principal"o"agresivo") y transformaciones


criptogrficas para Negociacin de IKE fase 1 ; consulte
el documentacin para una lista completa de los valores posibles y
sus valores por defecto.
auth rpido algoritmo enc algoritmo grupo Grupo

Especificar las transformaciones criptogrficas para Negociacin de


IKE fase 2 ; consulte el documentacin para una lista completa de
los valores posibles y sus valores por defecto.
srcid cadena dstid cadena

Definir la nica identificacin isakmpd (8) a utilizar como la


identidad del local (srcid) y remota (dstid) pares; si se omite, se
utiliza la direccin IP.
PSK string

Utilizar una clave previamente compartida para la autenticacin en


lugar de isakmpd (8) .

cadena de la etiqueta

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


esta regla.

As que vamos a escribir los archivos de configuracin para la VPN de


sitio a sitio Estamos configurando; como veremos, es una tarea
realmente sencilla y harn algunas reglas. En el host VPN1,
el /etc/ipsec.conf(5) archivo tendr el siguiente aspecto:
/etc/IPSec.conf
# Macros
ext_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 mquinas de gateway
IKE esp de $ext_if a $remote_gw
# Entre pasarela local y redes remotas
IKE esp de $ext_if a $remote_nets par $remote_gw
# Entre las redes
IKE esp de $local_net a $remote_nets par $remote_gw

y VPN2:
/etc/IPSec.conf
# Macros
ext_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 mquinas de gateway
IKE esp de $ext_if a $remote_gw
# Entre el gateway local y remoto
IKE pasivo esp de $ext_if a $remote_net par $remote_gw
# Entre las redes
IKE 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" opcin) para fcil
notar los errores:
# isakmpd -K -d

Luego, otra vez en ambas puertas de enlace, podemos


analizar IPSec.conf(5) las reglas ("- n" opcin 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 "opcin; por ejemplo:
VPN1 # ipsecctl -s todos

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 uso
esp 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 requieren
se 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 uso
esp 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:
tnel de
aes
tnel de
aes
tnel de
aes
tnel de
aes
[ ... ]
VPN1 #

ESP de 5.6.7.8 a 1.2.3.4 spi 0x027fa231 auth enc hmac-sha2-256


ESP de 1.2.3.4 a 5.6.7.8 spi 0x13ebc203 auth enc hmac-sha2-256
ESP de 1.2.3.4 a 5.6.7.8 spi 0x25da85ac auth enc hmac-sha2-256
ESP de 5.6.7.8 a 1.2.3.4 spi 0x891aa39b auth enc hmac-sha2-256

Bien, ya que todo parece estar funcionando bien, podemos configurar el


sistema para iniciar automticamente la VPN en el arranque, aadiendo
las siguientes variables en /etc/rc.conf.local(8) en dos gateways de
seguridad:
/etc/rc.conf.local
isakmpd_flags = "-K" # Evite Keynote(4) poltica de control
ipsec = YES # carga IPSec.conf(5) reglas de

3.4 filtrado de paquetes de


Trfico IPsec puede ser filtrada en el enc (4) interfaz de , donde aparece
sin cifrar antes de encapsualtion y despus de la desencapsulacin. Los
siguientes son los principales puntos a tener en cuenta para el filtrado de
trfico IPsec:

Protocolos IPsec (AH o ESP) debe ser explcitamente permitido en


la interfaz externa; por ejemplo:

# Permitir que ESP encapsula trfico 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)

nat-t de

requiere que el trfico UDP puertos 500 (isakmp) y 4500


ipsec) permitido en la interfaz externa; por ejemplo:

# Permite isakmpd (8) trfico en la interfaz externa


pasar en $ext_if proto udp desde $remote_gw al puerto $ext_if
{isakmp, ipsec nat-t}

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 tnel , Trfico IP en IP entre las dos


puertas de entrada debe ser en el enc (4) interfaz: por ejemplo:

Trfico # 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 trfico 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 trfico 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 (ifbound)

3.5 redundante VPN con sasyncd(8)


Una de las caractersticas ms interesantes de la aplicacin de
OpenBSD del protocolo IPsec es la posibilidad de configurar mltiples
gateways VPN en una configuracin redundante, permitiendo failover
transparente de conexiones VPN sin prdida de conectividad.
Por lo general, en OpenBSD, redundancia en el nivel de red se logra a
travs de la CARP(4) Protocolo de , que permite a los hosts mltiples en la
misma red local para compartir una direccin IP comn. Redundancia en
la capa VPN lgica, en cambio, es proporcionada por
el sasyncd(8) daemon, que permite la sincronizacin de
IPsec SA y SPD informacin entre mltiples 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) instalacin y que han
modificado su configuracin 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 documentacin ,
para SAs con proteccin de repeticin activada, como los creados
por isakmpd (8) la sasyncd(8)los hosts deben tener pfsync(4) para
sincronizar los contadores de reproduccin ncleo SA (para una
discusin detallada de la pfsync(4) de protocolo, consulte [carpa]).

El sasyncd(8) daemon se configura a travs de


la /etc/sasyncd.conf(5) archivo, el cual tiene una sintaxis bastante explica
por s mismo, a continuacin es un archivo de configuracin de ejemplo:
/etc/sasyncd.conf
# CARP(4) interfaz de seguimiento de los cambios de estado en
interfaz carp0
Grupo de # interfaz usar para suprimir CARP(4) preferencia durante el
arranque
carpa de grupo
# sasyncd(8) pares IP direccin o nombre de host. Se permiten mltiples
instrucciones de 'pares'
Peer 172.16.0.253
Tecla 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 "opcin, que es obligatoria en configuraciones
redundantes (recuerda aadir tambin
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 aadir la siguiente variable a
la/etc/rc.conf.local(8) archivo que inicie automticamente sasyncd(8) en
el arranque.
/etc/rc.conf.local
sasyncd_flags = ""

Nota : sasyncd(8) debe ser reiniciado manualmente cada vez isakmpd


(8) se reinicia el.
Edificio VPNs en OpenBSD

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


OpenVPN

Das könnte Ihnen auch gefallen