Port error mikrotik vpn

Ошибки при установке VPN соединения с сервером L2TP IPSec Mikrotik При настройке VPN-сервера на Mikrotik, могут быть ошибки. Некоторые из них не связаны с очепятками и недостатком знаний. Могут встречаться нелогичные или специфичные для какой-то ситуации ошибки. Proxy-arp на внутреннем бридже При подключении по VPN вы можете неприятно удивиться, почему вы можете открыть страницу логина […]

Содержание

  1. Ошибки при установке VPN соединения с сервером L2TP IPSec Mikrotik
  2. Proxy-arp на внутреннем бридже
  3. Глюк default policy на микротик
  4. Ошибки firewall на всех этапах
  5. Port error mikrotik vpn
  6. Re: VPN Server: Problems with L2TP IPsec: failed to pre-process ph2 packet
  7. Mikrotik L2TP/IPSec за NAT: ipsec,error failed to pre-process ph2 packet
  8. Не работает проброс портов на Mikrotik, когда подключен как VPN клиент?
  9. Port error mikrotik vpn
  10. L2TP/IPsec with IP pool for more users
  11. IKEv2/IPsec (VPN Reconnect)
  12. IKEv2 with pre shared key
  13. IKEv2 with username and password
  14. IKEv2 with certificates
  15. Connection problems
  16. MikroTik VPN error messages
  17. VPN types
  18. Ports
  19. IKEv2 authentication option
  20. MikroTik authentication methods
  21. Prepare certificates for clients
  22. Windows IKEv2 client certificate setup
  23. macOS client certificate setup
  24. iOS IKEv2 certificate setup
  25. Android IKEv2 certificate setup
  26. Certificate file extensions
  27. Certificate encryptions
  28. Contact Us
  29. Tikdis

Ошибки при установке VPN соединения с сервером L2TP IPSec Mikrotik

При настройке VPN-сервера на Mikrotik, могут быть ошибки. Некоторые из них не связаны с очепятками и недостатком знаний. Могут встречаться нелогичные или специфичные для какой-то ситуации ошибки.

Proxy-arp на внутреннем бридже

При подключении по VPN вы можете неприятно удивиться, почему вы можете открыть страницу логина в роутер, 192.168.88.1 (если у вас такой), но не сможете открыть ни один внутренний ресурс. Штука в том, что надо включить proxy-arp на внутреннем интерфейсе, за которым есть нужный вам ресурс. У меня proxy-arp включен на весь bridge-local. Этот параметр позволяет взаимодействовать хостам, находящимся в разных сегментах сети, между друг другом.

Меню Interfaces -> открываете bridge-local, в пункте ARP выбираете proxy-arp.

Глюк default policy на микротик

При абсолютно верных настройках L2TP/IPSec подключения на клиенте (например, Windows 7) и на сервере (Mikrotik), не удается установить VPN-подключение. При этом в лог Mikrotik идет сообщение «failed to pre-process ph2 packet», а на клиенте Windows 7 выходит ошибка 789: попытка L2TP-подключения не удалась из-за ошибки, произошедшей на уровне безопасности. Данная проблема может иметь место на прошивках вплоть до последней стабильной на текущий момент (6.30).

Решение: удалить созданную по умолчанию группу в меню IP — IPSec — Groups, создать новую и указать ее в IP — IPSec — Peers в поле Policy Template Group.

По сообщению Hopy, еще одним решением проблемы с группами может стать выполнение этой команды после пересоздания группы:

ip ipsec peer set 0 policy-template-group=*FFFFFFFF

Возможно, это наследие от старых конфигураций, точного ответа нет, но тем не менее, это вариант. Кстати, возможно по этой причине (и ей подобным) все же стоит выполнять полный сброс устройства перед начальной настройкой. Но требованием это не является, это уж точно.

Ошибки firewall на всех этапах

Ну и не забывайте про то, что в нормальной ситуации при подключении удаленного клиента действуют сразу несколько ограничений, в числе которых брандмауэр клиента, брандмауэр шлюза клиента (или провайдерский прокси), брандмауэр самого микротик (и не только цепочка input — серьезно помешать может цепочка forward), который вы раньше настроили максимально строго, не так ли? Всякие NAT через NAT и траверсом погонять могут. Так что старайтесь всегда разумно и спокойно локализовывать проблему.

Источник

Port error mikrotik vpn

Wed Oct 28, 2020 1:50 am

RouterOS: 6.47.6
FritzOS: 7.21

The Mikrotik router is to be the vpn server (L2TP IPSec) and I am trying with the win 10 built-in-vpn-client to connect to the vpn server.
So I did a Port-Forwarding on FritzBox 7590:
UDP: 500, 1701, 4500 and ESP-Protocol.

When I try to connect I get this error: «failed to pre-process ph2 packet«.

I also searched for a solution for this error message, but I couldn’t find a clear answer for that.

So maybe you can tell me if there are any errors in my setup or what other things can be the reason for this connection problem.
L2TP-Server setup:

here is the IPsec-setup:

I dont know if it is important, but I wonder that there are no packets count on port 1701 and for protocol 50. But maybe its normal at this time.

If you need further information just let me know.
Thx in advance!

Re: VPN Server: Problems with L2TP IPsec: failed to pre-process ph2 packet

Wed Oct 28, 2020 3:30 am

I’m not completely sure if that’s it, because I don’t use it like this. But Windows client doesn’t like L2TP/IPsec servers behind NAT and needs small config change:

Now few things I’m sure about:

— Don’t forward port 1701 at all, that’s for L2TP and it will be coming encrypted inside IPSec. FritzBox will never see any port 1701 traffic.
— You don’t see any hits on router for port 1701, because IPSec part didn’t finish, so no L2TP came yet.
— You won’t see ESP packets either, because when there’s NAT on either side, ESP packets are encapsulated in UDP (port 4500).
— Config export (/export hide-sensitive file=yourconfig) is usually better than screenshots, much less work and less chance to miss something.

Источник

Mikrotik L2TP/IPSec за NAT: ipsec,error failed to pre-process ph2 packet

При использовании Mikrotik за NAT (в частности за всякими USB GSM модемами) в режиме клиента L2TP/IPSec, у некоторых операторов в определенных режимах, получал проблему с ошибкой ipsec,error failed to pre-process ph2 packet.
Но с появлением RoS 6.38 появилась возможность справиться с ошибкой.

Итак, ошибка появляется в обычной конфигурации клиента L2TP как на картинке:

Основная проблема в том, что политика IPSec, применяемая в такой настройке, прибита гвозьдями и использует ike1. Ike1 в свою очередь, в реализации RoS, имеет проблему при прохождении NAT без проброса портов и как отягчающие обстоятельство: множественные туннели с l2tp тоже не проходят из-а одного NAT (а количество клиентов на модеме огромное).
Решить проблему можно при использование IKE2 (а для кучи клиентов за одним NAT нужно отказаться от авторизации PSK в пользу RSA Signature), который невозможно настроить из меню выше, но можно сделать трюк: заходим в меню IP -> IPSec

Копируем динамически создаваемый пир, и меняем в нем настройки как показано ниже:

А именно меняем Exchange Mode на IKE2, в закладке Encryption настраиваем необходимые параметры шифрования.

Осталось отключить в настройках L2TP/IPSec использование IPSec.

Вот собственно и все, соединение поднимается, шифрование работает.

Источник

Не работает проброс портов на Mikrotik, когда подключен как VPN клиент?

Есть роутер RB950, он является шлюзом для небольшого офиса. Микрот подключен к PPTP серверу как клиент и весь офис выходит в интернет через этот ВПН сервер. В туннель завернуто так: все соединения с src — ЛАН и dst — НЕ ЛАН маркируются и маркированные пакеты отправляются в туннель. При этом, конечно же, прописан маршрут по умолчанию, который направляет маркированный трафик через шлюз=ВПН. Пытаюсь пробросить порт, чтобы извне (когда стучусь на внешний стат. адрес) получить доступ к компьютеру в локалке. Проблема в том что когда маршрута по умолчанию для ВПН нет, всё работает отлично. Как только я прописываю маршрут по умолчанию для ВПН — проброс перестает работать. Раньше так же делал и всё работало, а сейчас не хочет. В чём может быть проблема?
P.S. На втором скрине видно правила маскарадинга и правило проброса.
Фаервол пробовал выключать, проблема НЕ в нем точно.




  • Вопрос задан более двух лет назад
  • 304 просмотра

/ip firewall mangle add chain=prerouting in-interface=INTERNET action=mark-connection new-connection-mask=from_internet
/ip firewall mangle add chain=prerouting src-address=192.168.0.0/24 connection-mark=from_internet action=mark-routing new-routing-mark=main

Источник

Port error mikrotik vpn

In macOS: Go to network settings, Add VPN, using type L2TP via IPSEC . add the routers IP and the chosen user. In authentication add the password for the user and as key/shared secret use the ipsec-secret. In options, enable ‘Send all traffic over VPN connection’, and you are done.

Beware, for several users behind the same NAT (MikroTik or most other), only one can connect at a time to the same server using L2TP/IPsec.

L2TP/IPsec with IP pool for more users

The command /interface l2tp-server server set . , enables the LT2P server and also creates a dynamic ipsec peer. To show the dynamic settings, run: /ip ipsec peer print. If you need advanced changes, you can copy this peer, and then disable the dynamic creation with /interface l2tp-server server set use-ipsec=no.

Some MikroTik routers have hardware acceleration for AES CBC encryption. This might reorder the packets, which can create speed huge issues with some (Windows) OSes. You may use proposal to switch from AES CBC to AES CTR, to switch to software decoding, if you have plenty of CPU power available. Only CBC is hardware accelerated. Or look into changing MSS.

IKEv2/IPsec (VPN Reconnect)

Fast and easy — using pre shared key or certificates. IKEv2 was implemented in MikroTik RouterOS 6.39.

IKEv2 with pre shared key

Only works on macOS and iOS etc. Windows 7, 8 and 10 do not support IKEv2 pre-shared key.

IKEv2 with username and password

Windows 7, 8 and 10 do not support EAP-only. That means EAP (Extensible Authentication Protocol) without using certificates are not possible on Windows.

IKEv2 with certificates

First we create certificates, requirements:

  1. Common name should contain IP or DNS name of the server (required by Windows)
  2. Subject Alt name should have IP or DNS of the server (required by some VPN clients)
  3. EKU tls-server and tls-client is required for Windows.

Now that we have certificates, server can be configured. Note that windows client requires modeconf, so we will use it to give out IP addresses from pool and send DNS, we also need to modify default template a little, to allow policies only from specific source addresses and generate unique level (required by multiple clients behind the same public IP):

On your client, you should now package the CA, the client certificate and the private key in a .p12 container file, to be able to install the certificates on Windows, macOS, iOS and Android. On your Windows/macOS/Linux client, use the openssl tool to create the file client1.p12:

Connection problems

If you can’t connect from your client, start by enabling the ipsec logging in the router. As a default the router only shows errors in the log, and not the issue creating the error.

/system logging add topics=ipsec

Then use Winbox and the Log menu.

Remember to disable the ipsec logging when done, as it consumes extra CPU.

MikroTik VPN error messages

  • Failed to pre-proces ph2 packet
    Your IPsec policy is missing or invalid, check:
    /ip ipsec policy print
    Maybe your IPsec peer is not set to generate a policy. Check: ip ⇢ ipsec ⇢ peer ⇢ advanced tab . or from terminal:
    :put [/ip ipsec peer get value-name=generate-policy number=0].
  • Unstable connection
    /ip ipsec peer
    add address=0.0.0.0/0 dpd-interval=2s enc-algorithm=3des exchange-mode=main-l2tp generate-policy=port-override secret=1234567890
  • On iOS and macOS rekey fails after 480 seconds = 8 minutes and VPN disconnects
    For iOS and macOS clients, make sure that on RouterOS server’s peer settings modp2048 (DH Group 14) is enabled, otherwise rekey will fail after 480 seconds which is 8 minutes (in peer use: sha256 + aes-256 + enable modp2048. In proposals use: sha256 + aes-256 cbc + set PFS Group=none.)
    (Log will say «killing ike», and debug log will say «KE size differs from expected 128 != 256)

VPN types

  • IKEv2: A modern, secure, fast and very stable VPN solution. Bult-in support in Windows and macOS. Can reconnect and re-establish the connection on poor connections or when the client switches access point on a WiFI network. Also called VPN Reconnect and VPN Connect.
  • L2TP/IPsec: Works very well, but a major drawback might be that only one L2TP might exist from clients behind the same NAT to the same server. L2TP is an unencrypted VPN tunnel, and IPsec is encrypting all packets.
  • SSTP: Good Windows proprietary solution, when firewalls restricts you. Tunnels PPP inside a SSL/TLS connection. The macOS default VPN client do not support SSTP.
  • OpenVPN: Very secure, but usually also slower, tunnels PPP packets inside SSL. OpenVPN is not supported in Windows or macOS per default.
  • PPTP: Very old and insecure. If only used internally, if only speed (and not security) is important, it might be usable, bot otherwise you should not use it. Removed from macOS in Sierra (2016).
  • IKEv2. User authentication by password or certificate or machine authentication by certificate or shared secret.
  • L2TP is actually L2TP/IPSec . so yes, it is IPsec encrypted even though it only says L2TP in the menu. User authentication using MS-CHAPV2 and machine authentication by shared secret.
  • IPSec is actually Cisco IPSec. User authentication by password and machine authentication by shared secret and certificate.
  • iOS certificates supported:
    • PKCS#1 (.cer, .crt, .der)
    • PKCS#12 (.p12, .pfx)

Ports

These are the ports you need to open to allow VPN access. You need to work with ports in the IP protocols TCP (protocol 6), UDP (protocol 17) and GRE (protocol 47).

  • PPTP ports
    TCP port 1723 (control)
    GRE (data)
  • L2TP/IPsec ports
    UDP port 500 (IKE control)
    UDP port 4500 (NAT-T)
    UDP port 1701 outbound (L2TP control and data)
  • SSTP port
    TCP port 443 (control and data)
  • IKEv2 ports
    UDP port 500 (control)
    UDP port 4500 (data as ESP encapsulated inside UDP)

IKEv2 authentication option

  • pre-shared key (mac only)
    Supported on iOS and macOS. Not supported on Windows 7, 8, 10.
  • EAP-only (no Windows)
    EAP username and password without certificate. Windows can only authenticate with EAP-MSCHAPv2.
  • PEAP (Protected EAP, Windows 7)
    Wraps another EAP method (like EAP-MSCHAPv2) in a TLS tunnel.
  • EAP-TLS (Windows 7)
    Also wraps EAP.
  • EAP-TTLS, EAP-AKA, EAP-AKA, EAP-SIM (Windows 8)
    Not MikroTik supported, almost all require a trusted certificate on the router.

MikroTik authentication methods

  • eap-radius: IKEv2 EAP RADIUS passthrough authentication for responder (RFC 3579).
    Most clients also need a server certificate set.
    Use certificate=none to authenticate using EAP-only (RFC 5998) for clients supporting only username+password.
  • pre-shared-key — authenticate by a shared password/key/secret.
  • rsa-signature — authenticate using client/server RSA certificates.
  • rsa-key — authenticate using a RSA key imported in Ipsec key menu.
  • pre-shared-key-xauth — mutual PSK authentication + xauth username/password.
    passive parameter identifies server/client side
  • rsa-signature-hybrid — responder certificate authentication with initiator Xauth.
    passive parameter identifies server/client side

Extended information in the MikroTik IPsec wiki.

Prepare certificates for clients

Windows and macOS: Package «ca», «client.cer» and «client.key» in a .p12 file container
openssl pkcs12 -export -out client1.p12 -inkey cert_export_client1.key -in cert_export_client1.crt -certfile cert_export_capfx.crt

macOS, if you are missing the private key for a cert:
openssl pkcs12 -export -clcerts -inkey client.key -in client.crt -out client.p12 -name «username2017»

Windows IKEv2 client certificate setup

  1. Open MMC: Win+R ⇢ mmc ⇢ Ctrl+M ⇢ add «Certificates» from the list and choose «Local Computer».
  2. Import certificates: Right click on «Personal» folder ⇢ «All Tasks» ⇢ «Import. » ⇢ Select client1.p12 file.
    CA and client certificate should now appear in the folder «Personal ⇢ Certificates».
  3. Trust the CA: Drag and drop CA from «Personal ⇢ Certificates» to «Trusted Root Certificates» folder.
    CA certificate needs to be in the Trusted Root list, only the client certificate should stay in «Personal».
  4. Create new VPN: Choose VPN type IKEv2, and router IP in server address field.
  5. Change cert type: Control panel ⇢ Network ⇢ Network connections: Right click VPN ⇢ Settings ⇢ Security: [v] «Use machine certificates».
  6. Advanced
    1. Create VPN using with powershell
      1. Add-VpnConnection -Name VPN -ServerAddress aaa.bbb.ccc.ddd
      2. Set-VpnConnection «VPN» -SplitTunneling $true
      3. Set-VpnConnection «VPN» -RememberCredential $true
    2. Enable split-tunneling manually
      1. Control Panel ⇢ Network and Sharing Center ⇢ Change Adapter Settings ⇢ Right click on the VPN connection: Properties ⇢ Networking ⇢ Internet Protocol Version 4 (TCP/IPv4) ⇢ Properties
      2. Advanced ⇢ Deselect «Use default gateway on remote network»
      3. Add needed routes, ex:

        macOS client certificate setup

        1. Import certificates: Doubleclick the «client1.p12» — key ring will open and import two «Certificates» and also install the private key.
          If asked, choose «Login» as place to store certificate — then type certificate password when asked.
        2. Trust the CA: Click «Login ⇢ Certificates» — double click the «ca» certificate (search for it’s name).
          1. Change to «Using this certificate: always approve» — close window — enter your computers password and OK.
        3. Issues?
          1. If your personal certificate only show in the folder «Certificates» and not in «My Certificates», it is because the private key is missing. When you add the matchin private key to the key ring, the certificate will also show under «My certificates» with an arrow, where you can see the private key below.
          2. Instead of using a .p12, you can also choose to import the .cer files individually, and the private key afterwards. If you get the private key as a .key file, you first need to convert it to .p12:
            openssl pkcs12 -export -clcerts -inkey client1.key -in client.cer -out client.p12 -name «client1»
        4. Create new VPN: Add new VPN choosing VPN type IKEv2.
          Use the router IP in server address and external id. If you have several different VPN connections in the same router using different IPs, the external id should still be the primary IP.
          Under authentication button, choose «Authentication: None» and then browse and select the certificate.
          (You can also choose «Authentication: certificate», but this is not the correct way.)
          You can only choose certificates, that are listed in the macOS key ring folder «My certificates». Certificates . for which there is installed a private key are also listed under «My certificates»

        iOS IKEv2 certificate setup

        1. Use Airdrop or e-mail to transfer the .p12 file to the iOS iPhone/iPad and click on the certificate icon. Enter password etc. The installed certificates can be found in «Settings ⇢ General ⇢ Descriptions».
        2. Typically pkcs12 bundle contains also CA certificate, but iOS do not install this CA, so Self-signed CA certificate must be installed separately.
        3. RemoteID must be set equal to common-name or subjAltName of server’s certificate.

        Android IKEv2 certificate setup

        1. Native Android do not currently support IKEv2 properly, instead install open source and free Strongswan.
        2. Click client.p12 to install ca, cert and key. Enter the .p12 encryption password and choose to save as VPN.
        3. Open Strongswan and add new VPN as «type=IKEv2 Certificate», use router IP and select the certificate.

        Certificate file extensions

        • .csr
          A Certificate Signing Request, in PKCS10 format. Often used on web servers to request an SSL certificate from a certificate provider.
        • .cer (also named .crt and .der)
          An X.509 certificate in binary format.
        • .key
          Can be a public or private PKCS#8 keys as binary DER or ASCII PEM. Usually the private key for a .cer certificate.
        • .pem (.pub)
          An X.509 certificate that is Base-64 encoded and have a header and footer added.
          Can also function as a container that holds several certificates and keys.
          .pub is usually a public key, while .pem is a private key.
          Headers used are «BEGIN RSA PRIVATE KEY» and «BEGIN DSA PRIVATE KEY».
        • .ppk
          A container file including public and private key, created by the popular SSH client Putty, originally created for SSH usage on Windows. The public key is stored in plaintext, while the private key is encrypted. Short for «PuTTY private key».
          # .pub: ssh public key
          # .pem: ssh private key
        • .pfx
          Originally a Windows certificate container, but have for many years now been an alias for .p12 on Windows. Since the .p12 extension works everywhere on all OSes and all Windows versions, you should use the .p12 extension instead of .pfx.
        • .p12 (.pkcs12, PKCS #12)
          An encrypted container, that usually stores a private key, it’s certificate and the CA certificate chain. You will usually need to supply the encryption password, to access the certificates inside the .p12.

        Certificate encryptions

        PKCS are «the Public Key Cryptography Standards», se thorough description on Wikipedia. The most used are:

        • PKCS#8
          A public and private certificate keypair. When writing a private key in PKCS#8 format in a file, it needs to stored in either DER encoding or PEM encoding. DER and PEM encodings are describes in other chapters in this book. Header used in files are «BEGIN PRIVATE KEY».
        • PKCS#12
          See the .pfx and .p12 file format above.

        Tikdis is official danish distributor of MikroTik routers, switches, WiFi equipment and all other MikroTik devices. We are certified administrators and engineers in MikroTik equipment.

        Contact Us

        Tikdis

        Aarhusvej 201
        DK-8464 Galten
        Denmark

        Источник

For over a decade the now very insecure PPTP VPN has been the way most users VPN connect until Apple in 2016 removed it as an option in macOS due to it’s security issues. You can still install another VPN client like Strongswan or Shimo to gain PPTP possibility in macOS, but there really should not exist any reason to do that with MikroTik equipment as the secure VPN options are quite easy to setup, just 2 lines will get you running with a L2TP/IPsec VPN.

The best option is to install IKEv2 with certificates, and IKEv2 is very easy for end users to setup in the native clients in Windows, Mac, iPhone and iPad. Setting up IKEv2 on the router is a slightly longer setup.

L2TP/IPsec

L2TP/IPsec with one user

# Simple L2TP/IPsec VPN server for one user — it enable the server and add one user

# Change the ipsec-secret, username and the password, then open a terminal and copy the lines in.

/interface l2tpserver server set enabled=yes useipsec=yes ipsecsecret=xxthesharedkeyxxx authentication=mschap2

/ppp secret add name=user password=xxxtheuserspasswordxxx service=l2tp profile=defaultencryption localaddress=172.16.0.1 remoteaddress=172.16.0.2

In macOS: Go to network settings, Add VPN, using type L2TP via IPSEC … add the routers IP and the chosen user. In authentication add the password for the user and as key/shared secret use the ipsec-secret. In options, enable ‘Send all traffic over VPN connection’, and you are done.

Beware, for several users behind the same NAT (MikroTik or most other), only one can connect at a time to the same server using L2TP/IPsec.

L2TP/IPsec with IP pool for more users

# Using an IP pool for simultaneous users and set IPs with the default-encryption profile

# Enable the L2TP server and set the ipsec-secret

/interface l2tpserver server set enabled=yes useipsec=yes ipsecsecret=xxthesharedkeyxxx authentication=mschap2

# Create the IP range the users will get and name it VPN

/ip pool add name=VPN ranges=172.16.0.2172.16.0.20

# Change the default-encryption profile to use our VPN IP range

/ppp profile set [ find name=«default-encryption»] localaddress=172.16.0.1 remoteaddress=VPN

# Add a user, repeat this line for each user, changing the name and password

/ppp secret add name=user password=xxxtheuserspasswordxxx profile=defaultencryption service=l2tp

The command /interface l2tp-server server set …, enables the LT2P server and also creates a dynamic ipsec peer. To show the dynamic settings, run: /ip ipsec peer print. If you need advanced changes, you can copy this peer, and then disable the dynamic creation with /interface l2tp-server server set use-ipsec=no.

# If you need internet access through your VPN:

/ip firewall nat

add action=srcnat chain=srcnat srcaddress=172.16.0.0/16 outinterface=ether1 toaddresses=your.public.ip /

comment=«VPN clients ip to internet»

# If you also need access to another local network

add action=srcnat chain=srcnat srcaddress=172.16.0.0/16 dstaddress=10.0.1.0/24 toaddresses=10.0.1.2

# If you need other encryptions, like 3DES for Windows, set the encryptions with:

/ip ipsec proposal set [ find default=yes ] encalgorithms=aes256cbc,aes128cbc,3des

# Create a policy with a destination address, if you only want to route traffic to this network

# across the VPN. Default policy is set to 0.0.0.0/0.

/ip ipsec policy set 0 level=unique dstaddress=192.168.77.0/24

Some MikroTik routers have hardware acceleration for AES CBC encryption. This might reorder the packets, which can create speed huge issues with some (Windows) OSes. You may use proposal to switch from AES CBC to AES CTR, to switch to software decoding, if you have plenty of CPU power available. Only CBC is hardware accelerated. Or look into changing MSS.

IKEv2/IPsec (VPN Reconnect)

Fast and easy — using pre shared key or certificates. IKEv2 was implemented in MikroTik RouterOS 6.39.

IKEv2 with pre shared key

Only works on macOS and iOS etc. Windows 7, 8 and 10 do not support IKEv2 pre-shared key.

# Create the IP range the users will get and name it VPN

/ip pool add name=VPN ranges=172.16.0.2172.16.0.20

# Supply IP addresses and send DNS to the VPN user

/ip ipsec modeconfig add name=cfg1 systemdns=yes addresspool=VPN addressprefix=32

# Create the IPsec peer (VPN)

/ip ipsec peer add encalgorithm=aes256,aes128 exchangemode=ike2 generatepolicy=portstrict modeconfig=cfg1 passive=yes secret=xxxx

IKEv2 with username and password

Windows 7, 8 and 10 do not support EAP-only. That means EAP (Extensible Authentication Protocol) without using certificates are not possible on Windows.

IKEv2 with certificates

First we create certificates, requirements:

  1. Common name should contain IP or DNS name of the server (required by Windows)
  2. Subject Alt name should have IP or DNS of the server (required by some VPN clients)
  3. EKU tls-server and tls-client is required for Windows.

/certificate

add commonname=ca name=ca

sign ca cacrlhost=2.2.2.2

add commonname=2.2.2.2 subjectaltname=IP:2.2.2.2 keyusage=tlsserver name=server1

sign server1 ca=ca

add commonname=client1 keyusage=tlsclient name=client1

sign client1 ca=ca

add commonname=client2 keyusage=tlsclient name=client2

Now that we have certificates, server can be configured. Note that windows client requires modeconf, so we will use it to give out IP addresses from pool and send DNS, we also need to modify default template a little, to allow policies only from specific source addresses and generate unique level (required by multiple clients behind the same public IP):

# Create the IP range the users will get and name it VPN

/ip pool add name=VPN ranges=172.16.0.2172.16.0.20

# Supply IP addresses and send DNS to the VPN user

/ip ipsec modeconfig add name=cfg1 systemdns=yes addresspool=VPN addressprefix=32

# Create the IPsec peer (VPN)

/ip ipsec peer add authmethod=rsasignature certificate=server1 generatepolicy=portstrict

modeconfig=cfg1 passive=yes remotecertificate=none exchangemode=ike2

On your client, you should now package the CA, the client certificate and the private key in a .p12 container file, to be able to install the certificates on Windows, macOS, iOS and Android. On your Windows/macOS/Linux client, use the openssl tool to create the file client1.p12:

openssl pkcs12 export out client1.p12 inkey cert_export_client1.key in cert_export_client1.crt certfile cert_export_ca.crt

The MikroTik IKEv2 manual.

Connection problems

If you can’t connect from your client, start by enabling the ipsec logging in the router. As a default the router only shows errors in the log, and not the issue creating the error.

/system logging add topics=ipsec

Then use Winbox and the Log menu.

Remember to disable the ipsec logging when done, as it consumes extra CPU.

MikroTik VPN error messages

  • Failed to pre-proces ph2 packet
    Your IPsec policy is missing or invalid, check:
    /ip ipsec policy print
    Maybe your IPsec peer is not set to generate a policy. Check: ip ⇢ ipsec ⇢ peer ⇢  advanced tab … or from terminal:
    :put [/ip ipsec peer get value-name=generate-policy number=0].
  • Unstable connection
    /ip ipsec peer
    add address=0.0.0.0/0 dpd-interval=2s enc-algorithm=3des exchange-mode=main-l2tp generate-policy=port-override secret=1234567890
  • On iOS and macOS rekey fails after 480 seconds = 8 minutes and VPN disconnects
    For iOS and macOS clients, make sure that on RouterOS server’s peer settings modp2048 (DH Group 14) is enabled, otherwise rekey will fail after 480 seconds which is 8 minutes (in peer use: sha256 + aes-256 + enable modp2048. In proposals use: sha256 + aes-256 cbc + set PFS Group=none.)
    (Log will say «killing ike», and debug log will say «KE size differs from expected 128 != 256)

VPN types

  • IKEv2: A modern, secure, fast and very stable VPN solution. Bult-in support in Windows and macOS. Can reconnect and re-establish the connection on poor connections or when the client switches access point on a WiFI network. Also called VPN Reconnect and VPN Connect.
  • L2TP/IPsec: Works very well, but a major drawback might be that only one L2TP might exist from clients behind the same NAT to the same server. L2TP is an unencrypted VPN tunnel, and IPsec is encrypting all packets.
  • SSTP: Good Windows proprietary solution, when firewalls restricts you. Tunnels PPP inside a SSL/TLS connection. The macOS default VPN client do not support SSTP.
  • OpenVPN: Very secure, but usually also slower, tunnels PPP packets inside SSL. OpenVPN is not supported in Windows or macOS per default.
  • PPTP: Very old and insecure. If only used internally, if only speed (and not security) is important, it might be usable, bot otherwise you should not use it. Removed from macOS in Sierra (2016).

iOS

  • IKEv2. User authentication by password or certificate or machine authentication by certificate or shared secret.
  • L2TP is actually L2TP/IPSec … so yes, it is IPsec encrypted even though it only says L2TP in the menu. User authentication using MS-CHAPV2 and machine authentication by shared secret.
  • IPSec is actually Cisco IPSec. User authentication by password and machine authentication by shared secret and certificate.
  • iOS certificates supported:
    • PKCS#1 (.cer, .crt, .der)
    • PKCS#12 (.p12, .pfx)

Ports

These are the ports you need to open to allow VPN access. You need to work with ports in the IP protocols TCP (protocol 6), UDP (protocol 17) and GRE (protocol 47).

  • PPTP ports
    TCP port 1723 (control)
    GRE (data)
  • L2TP/IPsec ports
    UDP port 500 (IKE control)
    UDP port 4500 (NAT-T)
    UDP port 1701 outbound (L2TP control and data)
  • SSTP port
    TCP port 443 (control and data)
  • IKEv2 ports
    UDP port 500 (control)
    UDP port 4500 (data as ESP encapsulated inside UDP)

IKEv2 authentication option

  • pre-shared key (mac only)
    Supported on iOS and macOS. Not supported on Windows 7, 8, 10.
  • EAP-only (no Windows)
    EAP username and password without certificate. Windows can only authenticate with EAP-MSCHAPv2.
  • PEAP (Protected EAP, Windows 7)
    Wraps another EAP method (like EAP-MSCHAPv2) in a TLS tunnel.
  • EAP-TLS (Windows 7)
    Also wraps EAP.
  • EAP-TTLS, EAP-AKA, EAP-AKA, EAP-SIM (Windows 8)
    Not MikroTik supported, almost all require a trusted certificate on the router.

MikroTik authentication methods

  • eap-radius: IKEv2 EAP RADIUS passthrough authentication for responder (RFC 3579).
    Most clients also need a server certificate set.
    Use certificate=none to authenticate using EAP-only (RFC 5998) for clients supporting only username+password.
  • pre-shared-key — authenticate by a shared password/key/secret.
  • rsa-signature — authenticate using client/server RSA certificates.
  • rsa-key — authenticate using a RSA key imported in Ipsec key menu.
  • pre-shared-key-xauth — mutual PSK authentication + xauth username/password.
    passive parameter identifies server/client side
  • rsa-signature-hybrid — responder certificate authentication with initiator Xauth.
    passive parameter identifies server/client side

Extended information in the MikroTik IPsec wiki.

Prepare certificates for clients

Windows and macOS: Package «ca», «client.cer» and «client.key» in a .p12 file container
openssl pkcs12 -export -out client1.p12 -inkey cert_export_client1.key -in cert_export_client1.crt -certfile cert_export_capfx.crt

macOS, if you are missing the private key for a cert:
openssl pkcs12 -export -clcerts -inkey client.key -in client.crt -out client.p12 -name «username2017»

Windows IKEv2 client certificate setup

  1. Open MMC: Win+R ⇢ mmc ⇢ Ctrl+M ⇢ add «Certificates» from the list and choose «Local Computer».
  2. Import certificates: Right click on «Personal» folder ⇢ «All Tasks» ⇢ «Import…» ⇢ Select client1.p12 file.
    CA and client certificate should now appear in the folder «Personal ⇢ Certificates».
  3. Trust the CA: Drag and drop CA from «Personal ⇢ Certificates» to «Trusted Root Certificates» folder.
    CA certificate needs to be in the Trusted Root list, only the client certificate should stay in «Personal».
  4. Create new VPN: Choose VPN type IKEv2, and router IP in server address field.
  5. Change cert type: Control panel ⇢ Network ⇢ Network connections: Right click VPN ⇢ Settings ⇢ Security: [v] «Use machine certificates».
  6. Advanced
    1. Create VPN using with powershell
      1. Add-VpnConnection -Name VPN -ServerAddress aaa.bbb.ccc.ddd
      2. Set-VpnConnection «VPN» -SplitTunneling $true
      3. Set-VpnConnection «VPN» -RememberCredential $true
    2. Enable split-tunneling manually
      1. Control Panel ⇢ Network and Sharing Center ⇢ Change Adapter Settings ⇢ Right click on the VPN connection: Properties ⇢ Networking ⇢ Internet Protocol Version 4 (TCP/IPv4) ⇢  Properties
      2. Advanced ⇢ Deselect «Use default gateway on remote network»
      3. Add needed routes, ex:

        netsh interface ipv4 add route DESTINATIONSUBNET INTERFACENAME

    3. Enable split-tunneling with powershell
      1. Get-VPNConnection
      2. Set-VPNConnection» -Name «Connection Name» -SplitTunneling $true
    4. If you are still missing routes:
      1. Show your interfaces and routes:
        route PRINT
      2. Add static route for 10.1.1.x (/24 network) to IKEv2 with IP gateway 172.16.0.1:
        route ADD 10.1.1.0 MASK 255.255.255.0 172.16.0.1
      3. Add static route for 10.1.x.x (/16 network) to IKEv2 with IP gateway 172.16.0.1:
        route ADD 10.1.0.0 MASK 255.255.0.0 172.16.0.1
      4. Note, that using -p to add the routes permanent will have no effect, as the VPN connection is not connected when Windows adds the routes after booting and there is therefore no interface (VPN connection) to add the route to. Instead you may create a .bat file, and add command line to connect the VPN and then add the route.

macOS client certificate setup

  1. Import certificates: Doubleclick the «client1.p12» — key ring will open and import two «Certificates» and also install the private key.
    If asked, choose «Login» as place to store certificate — then type certificate password when asked.
  2. Trust the CA: Click «Login ⇢ Certificates» — double click the «ca» certificate (search for it’s name).
    1. Change to «Using this certificate: always approve» — close window — enter your computers password and OK.
  3. Issues?
    1. If your personal certificate only show in the folder «Certificates» and not in «My Certificates», it is because the private key is missing. When you add the matchin private key to the key ring, the certificate will also show under «My certificates» with an arrow, where you can see the private key below.
    2. Instead of using a .p12, you can also choose to import the .cer files individually, and the private key afterwards. If you get the private key as a .key file, you first need to convert it to .p12:
      openssl pkcs12 -export -clcerts -inkey client1.key -in client.cer -out client.p12 -name «client1»
  4. Create new VPN: Add new VPN choosing VPN type IKEv2.
    Use the router IP in server address and external id. If you have several different VPN connections in the same router using different IPs, the external id should still be the primary IP.
    Under authentication button, choose «Authentication: None» and then browse and select the certificate.
    (You can also choose «Authentication: certificate», but this is not the correct way.)
    You can only choose certificates, that are listed in the macOS key ring folder «My certificates». Certificates . for which there is installed a private key are also listed under «My certificates»

iOS IKEv2 certificate setup

  1. Use Airdrop or e-mail to transfer the .p12 file to the iOS iPhone/iPad and click on the certificate icon. Enter password etc. The installed certificates can be found in «Settings ⇢ General ⇢ Descriptions».
  2. Typically pkcs12 bundle contains also CA certificate, but iOS do not install this CA, so Self-signed CA certificate must be installed separately.
  3. RemoteID must be set equal to common-name or subjAltName of server’s certificate.

Android IKEv2 certificate setup

  1. Native Android do not currently support IKEv2 properly, instead install open source and free Strongswan.
  2. Click client.p12 to install ca, cert and key. Enter the .p12 encryption password and choose to save as VPN.
  3. Open Strongswan and add new VPN as «type=IKEv2 Certificate», use router IP and select the certificate.

Certificate file extensions

  • .csr
    A Certificate Signing Request, in PKCS10 format. Often used on web servers to request an SSL certificate from a certificate provider.
  • .cer (also named .crt and .der)
    An X.509 certificate in binary format.
  • .key
    Can be a public or private PKCS#8 keys as binary DER or ASCII PEM. Usually the private key for a .cer certificate.
  • .pem (.pub)
    An X.509 certificate that is Base-64 encoded and have a header and footer added.
    Can also function as a container that holds several certificates and keys.
    .pub is usually a public key, while .pem is a private key.
    Headers used are «BEGIN RSA PRIVATE KEY» and «BEGIN DSA PRIVATE KEY».
  • .ppk
    A container file including public and private key, created by the popular SSH client Putty, originally created for SSH usage on Windows. The public key is stored in plaintext, while the private key is encrypted. Short for «PuTTY private key».
    # .pub: ssh public key
    # .pem: ssh private key
  • .pfx
    Originally a Windows certificate container, but have for many years now been an alias for .p12 on Windows. Since the .p12 extension works everywhere on all OSes and all Windows versions, you should use the .p12 extension instead of .pfx.
  • .p12 (.pkcs12, PKCS #12)
    An encrypted container, that usually stores a private key, it’s certificate and the CA certificate chain. You will usually need to supply the encryption password, to access the certificates inside the .p12.

Certificate encryptions

PKCS are «the Public Key Cryptography Standards», se thorough description on Wikipedia. The most used are:

  • PKCS#8
    A public and private certificate keypair. When writing a private key in PKCS#8 format in a file, it needs to stored in either DER encoding or PEM encoding. DER and PEM encodings are describes in other chapters in this book. Header used in files are «BEGIN PRIVATE KEY».
  • PKCS#12
    See the .pfx and .p12 file format above.

Тогда:
1. переделываем сначала это:

Код

/ip address
add address=192.168.0.2/24 interface=LAN-bridge1 network=192.168.0.0
add address=192.168.6.1/24 interface=LAN-bridge1 network=192.168.6.0

2. в списках интерфейсов оставляем ТОЛЬКО это
/interface list member
add interface=pppoe-out1 list=WAN
add interface=LAN-bridge1 list=LAN

3. вот тут шлюз зачем закрасили? 192.168.0.2 должен быть

Код

/ip dhcp-server network
add address=192.168.0.0/24 dns-server=109.194.192.3,109.194.193.3,5.3.3.3 gateway=X.X.X.X netmask=24

И сразу: адрес 192.168.0.1 у кого?

4.

Код

/ip dns
set allow-remote-requests=yes servers=8.8.8.8,109.194.192.3,109.194.193.3

если вы клиентам в п.3 отдаете внешние DNS сервера, зачем тогда кэшер включать (set allow-remote-requests=yes ) на роутере?

5.

Цитата
Сообщение от jekh
Посмотреть сообщение

На курсах MTCNA мне с точностью до наоборот было сказано использовать netmap при маппинге как более совершенный вариант, а dst-nat оставить продвинутым специалистам.

это на каких курсах? кто тренер?

переделайте на dst-nat

6. сейчас файрволл посмотрим

через firewall filter l2tp over ipsec nat-t пройдет

7. теперь NAT

и так, я исключил disabled правила
в правилах ниже меняйте netmap на dst-nat и в каждом правиле обязательно укажите ваш внешний адрес pppoe-out1 через параметр dst-address или in-interface=pppoe-out1

Код

/ip firewall nat
add action=netmap chain=dstnat comment="RDP ladaserver" dst-port=13389 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=3389
add action=netmap chain=dstnat comment="Trassir ladaserver" dst-port=3080 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=3080
add action=netmap chain=dstnat comment="Trassir ladaserver" dst-port=3081 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=3081
add action=netmap chain=dstnat comment="Trassir ladaserver" dst-port=1555 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=555
add action=netmap chain=dstnat comment="FTP ladaserver" dst-port=21 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=21
add action=netmap chain=dstnat comment=oracle dst-port=1521 protocol=tcp src-address-list=white 
to-addresses=X.X.X.X to-ports=1521
add action=netmap chain=dstnat comment=ora-ssh dst-port=22 protocol=tcp src-address-list=white 
to-addresses=X.X.X.X to-ports=22
add action=netmap chain=dstnat comment=ezattendant disabled=yes dst-port=6000 protocol=tcp to-addresses=
X.X.X.X to-ports=6000
add action=netmap chain=dstnat comment="1C RDP" dst-port=23389 protocol=tcp src-address-list=white_1C 
to-addresses=X.X.X.X to-ports=3389
add action=netmap chain=dstnat comment="1C TSD" dst-port=8080 protocol=tcp src-address-list=white_1C 
to-addresses=X.X.X.X to-ports=8080
add action=netmap chain=dstnat comment="1C SQL" dst-port=1433 protocol=tcp src-address-list=white_1C 
to-addresses=X.X.X.X to-ports=1433

Например

Код

/ip firewall nat
add action=dst-nat in-interface=pppoe-out1 chain=dstnat comment="RDP ladaserver" dst-port=13389 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=3389

ИЛИ

Код

/ip firewall nat
add action=dst-nat dst-address=Y.Y.Y.Y chain=dstnat comment="RDP ladaserver" dst-port=13389 protocol=tcp src-address-list=
white to-addresses=X.X.X.X to-ports=3389

Y.Y.Y.Y — ваш внешний белый адрес

Если не измените — ждите косяков при обращении по этим портам из локалки

PS — закрашивать каждый адрес не нужно, тем более внутренние, прятать можно было только ваш внешний адрес, а его вы получаете по PPP динамически, потому в конфиге его нет

Понравилась статья? Поделить с друзьями:
  • Port 0 smart status bad backup and replace как исправить
  • Port 0 s m a r t status bad backup and replace как исправить
  • Pos error 4322
  • Porsche cayenne psm ошибка
  • Pops network error