Создание домашней сети на базе устройств mikrotik: часть 5
Содержание:
Properties
Property | Description |
---|---|
arp (disabled | enabled | proxy-arp | reply-only; Default: enabled) | Address Resolution Protocol mode.
|
clamp-tcp-mss (yes | no; Default: yes) | |
dont-fragment (inherit | no; Default: no) | |
dscp (integer: 0-63; Default: inherited) | DSCP value of packet. Inherited option means that dscp value will be inherited from packet which is going to be encapsulated. |
ipsec-secret (string; Default: ) | When secret is specified, router adds dynamic ipsec peer to remote-address with pre-shared key and policy with default values (by default phase2 uses sha1/aes128cbc). |
keepalive (integer,integer 0..4294967295; Default: 10s,10) | Tunnel keepalive parameter sets the time interval in which the tunnel running flag will remain even if the remote end of tunnel goes down. If configured time,retries fail, interface running flag is removed. Parameters are written in following format: where KeepaliveInterval is time interval and KeepaliveRetries — number of retry attempts. By default keepalive is set to 10 seconds and 10 retries. |
l2mtu (integer; read-only) | Layer2 Maximum transmission unit. Not configurable for EoIP. |
local-address (IP; Default: ) | Source address of the tunnel packets, local on the router. |
mac-address (MAC; Default: ) | Media Access Control number of an interface. The address numeration authority IANA allows the use of MAC addresses in the range from 00:00:5E:80:00:00 — 00:00:5E:FF:FF:FF freely |
mtu (integer; Default: auto) | Layer3 Maximum transmission unit |
name (string; Default: ) | Interface name |
remote-address (IP; Default: ) | IP address of remote end of EoIP tunnel |
tunnel-id (integer: 65536; Default: ) | Unique tunnel identifier, which must match other side of the tunnel |
IPSec (сеть-сеть) между серверами Linux
# aptitude install ipsec-tools racoon
Алгоритм настройки IPsec
- Настройка пакета racoon
- Создание политики безопасности
- Виртуальные интерфейсы. Они нужны для маршрутизации сетей находящихся в локальных сетях. Два соединенных сервера будут видеть себя без интерфейсов(иногда без них не заводится и между серверами, странно вообще-то).
Ниже приведены конфиги для случая с предопределёнными ключами.
> nano /etc/racoon/racoon.conf path include "/etc/racoon"; path pre_shared_key "/etc/racoon/psk.txt"; #path certificate "/etc/racoon/certs"; remote 10.5.21.23 { exchange_mode aggressive,main; doi ipsec_doi; situation identity_only; my_identifier address; #Определяет метод идентификации, который будет использоваться при проверке подлинности узлов. lifetime time 2 min; initial_contact on; proposal { encryption_algorithm 3des; hash_algorithm sha1; authentication_method pre_shared_key; # Определяет метод проверки подлинности, используемый при согласовании узлов. dh_group 2; } proposal_check strict; } sainfo anonymous # Отмечает, что SA может автоматически инициализировать соединение с любым партнёром при совпадении учётных сведений IPsec. { pfs_group 2; lifetime time 2 min ; encryption_algorithm 3des, blowfish 448, des, rijndael ; authentication_algorithm hmac_sha1, hmac_md5 ; compression_algorithm deflate ; }
Создадим политику безопасности
> nano pol.cfg #!/sbin/setkey -f flush; spdflush; spdadd 10.5.21.24 10.5.21.23 any -P out ipsec esp/transport//require; spdadd 10.5.21.23 10.5.21.24 any -P in ipsec esp/transport//require; > chmod +x pol.cfg > ./pol.cfg
Создадим выполняемый файл для создания интерфейсов и запустим его.
>nano tun.sh #!/bin/sh ip tunnel del tun0 ip tunnel add tun0 mode ipip remote 10.5.21.23 local 10.5.21.24 dev eth0 # создаем интерфейс tun0 и устанавливаем туннель # между хостами (здесь нужно использовать реальные IP адреса сетевых интерфейсов). ifconfig tun0 10.0.9.1 pointopoint 10.0.9.2 # назначаем интерфейсу IP адреса, для текущего хоста и для другого конца # туннеля (не обязательно). ifconfig tun0 mtu 1472 ifconfig tun0 up # ниже можно прописать нужные нам маршруты, например так route add -net ... netmask 255.255.255.0 gw ... route add -net ... netmask 255.255.255.0 gw ... > ./tun.sh
Для автоматической загрузки правил файл tun.sh правильно поместить для FAQ Debian в директорию /etc/network/if-up.d
Все IPSec тунель между сетями настроен.
Setup option #2: sourcing the tunnel from loopbacks
The scheme above doesn’t work when one of the routers has a dynamic external address though. The classic workaround for this is to setup an address on a loopback interface and use it as a source address for the GRE tunnel, then setup an IPsec policy to match those loopback addresses.
We assume that the LEFT router has static 192.0.2.10 address on eth0, and the RIGHT router has a dynamic address on eth0.
Setting up the GRE tunnel
On the LEFT:
set interfaces loopback lo address 192.168.99.1/32 set interfaces tunnel tun0 encapsulation gre set interfaces tunnel tun0 address 10.10.10.1/30 set interfaces tunnel tun0 local-ip 192.168.99.1 set interfaces tunnel tun0 remote-ip 192.168.99.2
On the RIGHT:
set interfaces loopback lo address 192.168.99.2/32 set interfaces tunnel tun0 encapsulation gre set interfaces tunnel tun0 address 10.10.10.2/30 set interfaces tunnel tun0 local-ip 192.168.99.2 set interfaces tunnel tun0 remote-ip 192.168.99.1
Setting up IPsec
However, now you need to make IPsec work with dynamic address on one side. The tricky part is that pre-shared secret authentication doesn’t work with dynamic address, so we’ll have to use RSA keys.
First, on both routers run the operational command «generate vpn rsa-key bits 2048». You may choose different length than 2048 of course. If your machine is a VM, generating it from /dev/random may take ages, so you may opt for «generate vpn rsa-key 2048 random /dev/urandom» instead.
vyos@left# run generate vpn rsa-key bits 2048 random /dev/urandom Generating rsa-key to /config/ipsec.d/rsa-keys/localhost.key Your new local RSA key has been generated The public portion of the key is: 0sAQO2335
Then on the opposite router, add the RSA key to your config.
set vpn rsa-keys rsa-key-name LEFT rsa-key KEYGOESHERE
Now you are ready to setup IPsec. You’ll need to use an ID instead of address for the peer on the dynamic side.
On the LEFT (static address):
set vpn rsa-keys rsa-key-name RIGHT rsa-key <PUBLIC KEY FROM THE RIGHT> set vpn ipsec ipsec-interfaces interface eth0 set vpn ipsec esp-group MyESPGroup proposal 1 encryption aes128 set vpn ipsec esp-group MyESPGroup proposal 1 hash sha1 set vpn ipsec ike-group MyIKEGroup proposal 1 dh-group 2 set vpn ipsec ike-group MyIKEGroup proposal 1 encryption aes128 set vpn ipsec ike-group MyIKEGroup proposal 1 hash sha1 set vpn ipsec site-to-site peer @RIGHT authentication mode rsa set vpn ipsec site-to-site peer @RIGHT authentication rsa-key-name RIGHT set vpn ipsec site-to-site peer @RIGHT default-esp-group MyESPGroup set vpn ipsec site-to-site peer @RIGHT ike-group MyIKEGroup set vpn ipsec site-to-site peer @RIGHT local-address 192.0.2.10 set vpn ipsec site-to-site peer @RIGHT connection-type respond set vpn ipsec site-to-site peer @RIGHT tunnel 1 local prefix 192.168.99.1/32 # Additional loopback address on the local set vpn ipsec site-to-site peer @RIGHT tunnel 1 remote prefix 192.168.99.2/32 # Additional loopback address on the remote
On the RIGHT (dynamic address):
Настройка GRE туннелей в Debian GNU/Linux
Настройка GRE туннелей в FAQ Debian и Ubuntu одинаковы. Имеется 2 удаленных сервера Debian 7.8 Wheezy с реальными статическими IP адресами.
-
Листинг всех туннелей можно просмотреть посредством
ip tunnel list
-
На обоих серверах в Правила iptables разрешим протокол GRE
$IPT -A INPUT -p gre -j ACCEPT or $IPT -A INPUT -p gre -s x.x.x.x -j ACCEPT
-
1 сервер. Скрипт для ручного создания GRE туннеля. IPIP -туннель поднимается совершенно аналогичным образом, в скрипте только mode gre заменится на mode ipip
- gre_to_m86a_create.sh
-
#!/bin/sh -e #ip tunnel del tun1 ip tunnel add tun1 mode gre remote 91.196.98.162 local 188.230.123.238 dev eth3 ifconfig tun1 10.26.95.254 pointopoint 192.168.35.254 #ifconfig tun1 mtu 1400 #ifconfig tun1 up route add -net 192.168.35.0 netmask 255.255.255.0 gw 192.168.35.254 # Hotel route add -net 192.168.22.0 netmask 255.255.255.0 gw 192.168.35.254 # Service Lan Vlan route add -net 10.90.91.0 netmask 255.255.255.0 gw 192.168.35.254
То же самое только через файл /etc/network/interfaces
auto tun1 iface tun1 inet static address 10.26.95.254 netmask 255.255.255.0 mtu 1400 up ifconfig tun1 multicast pre-up iptunnel add tun1 mode gre local 188.230.123.238 remote 91.196.98.162 dev eth3 post-up route add -net 192.168.35.0 netmask 255.255.255.0 gw 192.168.35.254 post-up route add -net 192.168.22.0 netmask 255.255.255.0 gw 192.168.35.254 post-up route add -net 10.90.91.0 netmask 255.255.255.0 gw 192.168.35.254 pointopoint 192.168.35.254 post-down iptunnel del tun1
-
2 сервер. Скрипт для ручного создания GRE
#!/bin/sh -e ip tunnel add tun1 mode gre remote 188.230.123.238 local 91.196.98.162 dev eth5 ifconfig tun1 192.168.35.254 pointopoint 10.26.95.254 route add -net 10.26.95.0 netmask 255.255.255.0 gw 10.26.95.254 route add -net 172.20.20.0 netmask 255.255.255.0 gw 10.26.95.254
В файл /etc/network/interfaces это будет выгладить так
auto tun1 iface tun1 inet static address 192.168.35.254 netmask 255.255.255.0 mtu 1400 up ifconfig tun1 multicast pre-up iptunnel add tun1 mode gre remote 188.230.123.238 local 91.196.98.162 dev eth5 post-up route add -net 10.26.95.0 netmask 255.255.255.0 gw 10.26.95.254 post-up route add -net 172.20.20.0 netmask 255.255.255.0 gw 10.26.95.254 pointopoint 10.26.95.254 post-down iptunnel del tun1
- Всe! Туннель должен работать. Проверяем ping
-
Если не работает запускаем tcpdump Linux примеры использования
tcpdump -n -i eth3 proto 47
Ниже рабочий пример для ping из локальной сети
13:25:04.444375 IP 188.230.123.238 > 91.196.98.162: GREv0, length 88: IP 10.26.95.251 > 192.168.35.55: ICMP echo request, id 5341, seq 15, length 64 13:25:04.459864 IP 91.196.98.162 > 188.230.123.238: GREv0, length 88: IP 192.168.35.55 > 10.26.95.251: ICMP echo reply, id 5341, seq 15, length 64
Configuration on R2:
interface fasthethernet 0/0 ip address 10.1.102.2 255.255.255.0 ! interface loopback 0 ip address 2.2.2.2 255.255.255.255 ! interface tunnel12 ip address 192.168.12.2 255.255.255.0 tunnel source 10.1.102.2 tunnel destination 10.1.101.1 ! router eigrp 12 network 2.2.2.2 0.0.0.0 network 192.168.12.0 ! access-list 130 permit gre host 10.1.102.2 host 10.1.101.1 ! crypto isakmp key cisco123 address 10.1.101.1 crypto isakmp policy 10 authentication pre-shared-key encryption des hash sha group 1 ! crypto ipsec transform-set esp-3des esp-3des esp-sha-hmac ! crypto map out_map 10 ipsec-isakmp set peer 10.1.101.1 set transform-set esp-3des match address 130 crypto map out_map local-address fastEthernet 0/0 ! interface fasthethernet0/0 crypto map out_map
Настройка IPSEC
В тоннеле GRE по умолчанию нет никакой шифрации, т.е. данные ходят в открытом виде и все можно прекрасно посмотреть любым сниффером (tcpdump, wireshark). Для обеспечения безопасности необходимо настроить IPSEC.
Исходные данные:
Ключ шифрования: VerySecretChipherKey
IPSEC на Mikrotik
IP → IPsec → Proposals
Изменяем default:
- Auth Algorithms: sha256
- Encr Algorithms: aes-128 cbc, aes-192 cbc, aes-256 cbc
- Lifetime: 00:30:00
- PFS Group: modp1024
А в свойствах GRE-тоннеля настраиваем:
IPsec Secret: VerySecretChipherKey
Настройки IPSEC на сервере с Ubuntu
Для Ubuntu и прочих линуксов есть несколько пакетов: racoon и несколько форков *swan (StrongSwan, LibreSwan, OpenSwan). Я остановился на StrongSwan — т.к. он мне больше понравился и в сети много готовых примеров.
Установка проста:
sudo apt install strongswan
Редактируем файл конфигурации /etc/ipsec.conf
# ipsec.conf - strongSwan IPsec configuration file config setup charondebug="ike 2, knl 2, cfg 2, net 2, esp 2, dmn 2, mgr 2" conn %default # keyexchange=ikev2 conn mikrotik # Try connect on daemon start auto=start # Authentication by PSK (see ipsec.secret) authby=secret # Disable compression compress=no # Re-dial setings closeaction=clear dpddelay=30s dpdtimeout=150s dpdaction=restart # ESP Authentication settings (Phase 2) esp=aes128-sh256-modp1024,aes192-sha256-modp1024,aes256-sha256-modp1024 # UDP redirects forceencaps=no # IKE Authentication and keyring settings (Phase 1) ike=aes128-sh256-modp1024,aes192-sha256-modp1024,aes256-sha256-modp1024 ikelifetime=86400s keyingtries=%forever lifetime=1800s # Internet Key Exchange (IKE) version # Default: Charon - ikev2, Pluto: ikev1 keyexchange=ikev1 # connection type type=transport # Peers left=XXX.XXX.XXX.XXX right=YYY.YYY.YYY.YYY # Protocol type. May not work in numeric then need set 'gre' leftprotoport=47 rightprotoport=47
Добавляем ключ шифрования в файл /etc/ipsec.secrets
YYY.YYY.YYY.YYY XXX.XXX.XXX.XXX : PSK VerySecretChipherKey
Перезапускаем IPSEC:
sudo ipsec restart
Проверяем /var/log/syslog на Ubuntu и командой
ipsec status
На Mikrotik смотрим Log и IP → IPsec → Peers
Настройка MTU
Если есть проблемы при работе с тоннелем — желательно уменьшить MTU до 1435 на обоих концах туннеля.
Mikrotik: Изменить в свойствах GRE-тоннеля MTU на 1435
Ubuntu: В файле /etc/network/interfaces добавить строку в настройку интерфейса tun1
mtu 1435
Настройка firewall
Так же может понадобиться настройка firewall на Микротике и Ubuntu, но тут уж сам настраивает под себя.
Чтобы с Микротика все благополучно проходило через тоннель необходимо сделать маскарадинг:
IP → Firewall → NAT со следующими настройками:
- Chain: srcnat
- Out Interface: GRE1
- Action: Accept
Литература
ftp://ftp.isi.edu/in-notes/iana/assignments/ethernet-numbers1
Braden, R., «Requirements for Internet hosts — communication layers», STD 3, RFC 1122, October 1989.
Mogul, J. and S. Deering, «Path MTU Discovery», RFC 1191, November 1990.
Kantor, B., «Internet Protocol Encapsulation of AX.25 Frames», RFC 1226, May 1991.
Provan, D., «Tunneling IPX Traffic through IP Networks», RFC 1234, June 1991.
Woodburn, R. and D. Mills, «Scheme for an Internet Encapsulation Protocol: Version 1», RFC 1241, July 1991.
Tsuchiya, P., «Mutual Encapsulation Considered Dangerous», RFC 1326, May 1992.
Steenstrup, M., «Inter-Domain Policy Routing Protocol Specification: Version 1», RFC 1479, July 1993.
Reynolds, J. and J. Postel, «Assigned Numbers», STD 2, RFC 1700, October 1994.
Hanks, S., Li, T., Farinacci, D. and P. Traina, «Generic Routing Encapsulation», RFC 1701, October 1994.
Hanks, S., Li, T., Farinacci, D. and P. Traina, «Generic Routing Encapsulation over IPv4 networks», RFC 1702, October 1994.
Bradner, S., «Key words for use in RFCs to Indicate Requirement Levels», BCP 14, RFC 2119, March, 1997.
Maughan, D., Schertler, M., Schneider, M. and J. Turner, «Internet Security Association and Key Management Protocol (ISAKMP)», RFC 2408, November 1998.
Narten, T. and H. Alvestrand, «Guidelines for Writing an IANA Considerations Section in RFCs», BCP 26, RFC 2434, October, 1998.
Hamzeh, K., et al., «Point-to-Point Tunneling Protocol (PPTP)», RFC 2637, July, 1999.
Configuring the GRE Tunnel
The Tunnel Interface
We know that the tunnel is a virtual link, obtained with encapsulation. The router can use this link like any other link, even if it’s virtual. A router has access to links through interfaces, so we need to create a virtual one to access the tunnel.
For this lab, we are going to create the Tunnel 0 interface, but any number would do. The tunnel numbers don’t need to match on the two routers. Enter in global configuration, and from there just enter. You will open the prompt for the tunnel. Here, you can enter all the settings we are used to: IP addresses, routing protocol settings, and so on. However, just don’t do it for now.
By default, the protocol that a tunnel will use is GRE. Just to be sure, we can force it by typing inside the Tunnel interface. If this is the default, you won’t see it in the configuration. However, just type it to be sure, even in this lab.
Source and Destination
Before doing anything else, we should specify two tunnel-specific settings: source and destination. In fact, the router needs to know how to populate the outer IP packet when doing tunneling. With these two commands, we tell which IP address use as the source, and which as destination. However, you don’t specify directly the source IP address. You specify an interface instead: the router will automatically take the address of that interface. You can specify any type of interface you want, including loopbacks. The commands to do so are and .
Hop on R1 and with obtain the address of the public interface (). Do the same on R2 and you will know which is your destination address. Of course, R1 will have as destination R2, and vice versa. As a result, the configuration of R1 will look like this:
interface Tunnel0 tunnel source GigabitEthernet0/0 tunnel destination 91.29.73.100
And the one on R2 will be this:
interface Tunnel0 tunnel source GigabitEthernet0/0 tunnel destination 84.96.12.19
At this point, we have created a functioning Layer 2 link. We need to configure routing on it.
Configuring the routing
Configuring the routing is easy. We have one link, the tunnel, connecting two subnets. We will need to configure addresses on it, then add two static routes.
According to the requirements, the addressing plan for the tunnel is . So, we will need to enter on the Tunnel 0 of R1. Instead, we will need to use for R2. Now, ping from a router the address of the other. We expect this to work, but you won’t be able to ping the LAN behind the other router just yet.
To access the remote LAN, we need to add one static route per router. Specifically, we want to reach the remote LAN through the tunnel. So, hop into global configuration and type on R1 . For R2, type instead.
Congratulations! You have now completed this lab about GRE Tunnels!