Mikrotik: небольшие полезности. Часть 2
Изображение для привлечения внимания
Интересно? Тогда прошу под кат.
Как закрыть все сайты кроме одного/нескольких
Сразу скажу, что использовать нужно L7 Protocol. Казалось бы, чего сложного: просто применить правило «все кроме».
Но нет, это не работает. Если хотите, проверьте сами. Что делать? Одним фильтром разрешить нужные ресурсы и вторым запретить все остальные.
Разрешающий L7 имеет вид ^.+(какой-то_сайт|еще какой-то_сайт).*$.
С запрещающими сложнее. Можно зафильтровать вообще все через ^.+$. Но я бы посоветовал фильтровать протокол HTTP по URI, то есть так — ^.+(HTTP\/2).+$.
К сожалению, через терминал необходимые L7-фильтры добавляются с пустым полем regexp. Используйте вместо этого Winbox.
Добавление самих фильтры, по 2 на ‘разрешить’ и ‘запретить’ согласно вики Микротик
Небольшое уточнение для тех, кому все-таки требуется разрешить строго определенные сайты: проверяйте, какие еще ресурсы задействованы на сайте. К примеру, это могут быть подгружаемые карты. Я использую Opera для серфинга в сети, а так же входящий в нее DevTools, вкладка «Console» для определения ошибок.
Важное уточнение: в версии 6.36 и новее это можно реализовать использую 3 пункт статьи.
Как получать «человеческие» уведомления о VPN-подключениях
Кто сталкивался с уведомлениями Микротика в секции Logging, тот знает, что уведомления убогие и подходят только для совсем простых случаев. Мне же хотелось, чтобы уведомления несли в себе как можно больше полезной информации. Оказалось, это реализовать достаточно просто: необходимы скрипты на подключение/отключение для профиля PPP. Ниже я приведу скрипты на On Up и On Down, но сначала немного подводных камней:
1) Для обоих скриптов есть предопределенные переменные — подробнее о них.
2) Переменные с дефисом необходимо указывать в кавычках. К примеру, $«caller-id». Иначе не работает!
3) Микротик отсылает сообщения по электронной почте в тексте, поэтому никаких тэгов, гиперссылку вставлять только в явном виде.
4) В теле сообщения для переноса каретки в начало новой строки используется \r\n.
5) На данном этапа (версия 6.33.2) есть проблемы с кодировкой сообщений в некоторых почтовых клиентах и web-интерфейсах.
Доменные имена в адресных листах
*) firewall — allow to add domain name to address-lists (dynamic entries for resolved addresses will be added to specified list);
Если вы еще не прыгаете от радости как я, то самое время начать. Эта фича позволяет практически полностью уйти от использования затратного L7 с его ограничениями.
В качестве примера приведу маршрутизацию разных сайтов в разные шлюзы. Это актуально в связи с действительностью в нашей стране. Заворачивать будем web-интерфейсы почтовых серверов mail.google.com и e.mail.ru. В почту Google будем ходить по OVPN, а в Mail — по L2TP.
Таким образом, при добавлении нужного имени в определенный лист, мы фактически определяем по какому каналу будет установлена связь.
Еще один пример, который многим пригодится: перенаправлять все TCP-соединения в шлюз OVPN, а rkn.gov.ru — в шлюз по умолчанию.
Важное замечание: если вы используете Fasttrack, то обязательно смотрите его описание. А именно:
Fasttracked packets bypass firewall, connection tracking, simple queues, queue tree with parent=global, ip traffic-flow(restriction removed in 6.33), ip accounting, ipsec, hotspot universal client, vrf assignment, so it is up to administrator to make sure fasttrack does not interfere with other configuration;
MikroTik.by
For every complex problem, there is a solution that is simple, neat, and wrong.
сообщение при подключении к VPN
сообщение при подключении к VPN
Сообщение playful2017 » 23 янв 2018, 11:35
Re: сообщение при подключении к VPN
Сообщение Chupaka » 23 янв 2018, 13:16
Re: сообщение при подключении к VPN
Сообщение playful2017 » 23 янв 2018, 13:41
Re: сообщение при подключении к VPN
Сообщение Chupaka » 23 янв 2018, 14:26
Re: сообщение при подключении к VPN
Сообщение playful2017 » 24 янв 2018, 08:01
Re: сообщение при подключении к VPN
Сообщение Vita077 » 28 сен 2018, 12:55
Re: сообщение при подключении к VPN
Сообщение Chupaka » 28 сен 2018, 13:33
Re: сообщение при подключении к VPN
Сообщение Vita077 » 28 сен 2018, 18:57
Re: сообщение при подключении к VPN
Сообщение Chupaka » 28 сен 2018, 19:02
Re: сообщение при подключении к VPN
Сообщение Vita077 » 01 окт 2018, 17:09
Re: сообщение при подключении к VPN
Сообщение Chupaka » 01 окт 2018, 17:25
Вы бы привели конкретный скрипт, который не работает, раз задаёте такие вопросы выше.
А как вы себе представляете смену Caller ID без переподключения?
Re: сообщение при подключении к VPN
Сообщение Vita077 » 02 окт 2018, 06:49
F.A.Q по Mikrotik и RouterOS. Часть 2.
Глава 1.8 Проброс «белого» (реального, внешнего) IP в локальную сеть.
Это нужно, если вышестоящий провайдер выдал вам подсеть «белых» IP-адресов. Один адрес оставляем как адрес самого Микротика, второй адрес обычно это шлюз провайдера, остальные можем выдать клиентам в локальной сети.
Допустим, ваша локальная сеть 192.168.1.0/24, локальный адрес Микротика 192.168.1.1.
Способ 1, при помощи NAT.
В этом примере пробрасываем интернет-адрес 195.195.195.195 на локальный адрес 192.168.1.11. Для практического использования меняем адреса на свои.
/ip firewall nat
add action=netmap chain=srcnat comment=»Mapping 195.195.195.195 > 192.168.1.11″ src-address=192.168.1.11 to-addresses=195.195.195.195
add action=dst-nat chain=dstnat dst-address=195.195.195.195 to-addresses=192.168.1.11
/ip address
add address=195.195.195.195/32 interface=ether1-gateway network=195.195.195.195
Первое правило NAT меняет во всех пакетах, идущих в Интернет (исключая сеть 192.168.1.0/24) локальный адрес 192.168.1.11 на 195.195.195.195
Второе правило все пакеты, приходящие на адрес 195.195.195.195 отправляет на 192.168.1.11.
Эти правила должны находиться выше основного правила NAT (masquerade).
И последнее действие назначает адрес 195.195.195.195, как дополнительный, внешнему интерфейсу Микротика. Это необходимо для того, чтобы Микротик принимал входящие пакеты с таким адресом.
Отличие этого способа заключается в том, что клиент видит как локальную сеть (и соответственно виден внутри сети), так и интернет. Устройство с локальным адресом 192.168.1.11 полностью доступно извне сети по адресу 195.195.195.195. При этом фактически находится за NAT и Firewall, что позволяет применять к трафику этого клиента другие правила обработки трафика, шейпер и т.п..
Способ 2, при помощи создания моста между интерфейсами (Bridge).
Допустим, порт, подключенный к провайдеру, это ether1-gateway, а клиент подключен через порт ether2-local.
/interface bridge
add name=Bridge1
/interface bridge port
add bridge=Bridge1 interface=ether1-gateway
add bridge=Bridge1 interface=ether2-local
В этом примере мы создали мост между внешним и внутренним интерфейсами.
Далее нужно просто назначить на нужном локальном устройстве «белый» IP-адрес, в качестве шлюза указать шлюз провайдера (а не Микротик), DNS-серверы либо провайдерские, либо открытые альтернативные. Всё это можно сделать как вручную, так и назначить клиенту при помощи DHCP.
Среди преимуществ данного способа можно назвать то, что получаем «белый» IP прямо на клиентском устройстве.
Среди недостатков то, что мы выпускаем клиента практически напрямую в Интернет, на его трафик не действуют Simple Queues, а настройки NAT, Firewall (и некоторые другие) необходимо делать отдельные от общих правил, действующих на остальную сеть.
Глава 1.9 Настройка основных типов PPP-серверов.
1.9.1 Настройка PPtP-сервера Mikrotik.
Обычно используется для подключения к Mikrotik удаленных клиентов (через Интернет). Реже для подключения локальных пользователей или других задач.
По умолчанию видим два профиля, один с обязательным шифрованием данных, второй нет.

Настраиваем нужный профиль или создаем новый.
Настройки протоколов:
— Use MPLS: использовать ли механизм MPLS. При «default» определяется клиентом, «no» никогда не использовать, «yes» согласование с клиентом, «required» использовать всегда.
— Use Compression: использовать ли сжатие данных. Имеет смысл включать только при очень медленных каналах.
— Use VJ Compression: использовать ли сжатие заголовков TCP/IP. Актуально только для медленных каналов.
— Use Encruption: использовать ли шифрование данных. При «default» определяется клиентом, «no» никогда не использовать, «yes» согласование с клиентом, «required» использовать всегда (без шифрования доступ не будет разрешен).
Настройки лимитов пользовательской сессии:
— Session Timeout: ограничение времени одной клиентской сессии. По истечении этого времени сессия будет сброшена.
— Idle Timeout: ограничение времени бездействия. Подключение будет сброшено, если по нему нет активности в течение указанного времени.
— Rate Limit (rx/tx): общее ограничение скорости подключения.
— Only One: если установлено «yes», то пользователю будет разрешено только одно подключение в один момент времени.
1.9.2 Настройка PPPoE-сервера Mikrotik.
Используется исключительно для подключения к Mikrotik локальных клиентов.
Все настройки аналогичны PPtP, за исключением самого сервера.
Особенности использования PPPoE-серверов в Mikrotik.
Если у вас Mikrotik со встроенным свичем и один порт настроен как master, остальные slave, достаточно создать PPPoE-сервер только для порта master. Порты slave также будут принимать подключения к этому серверу.
Аналогично, если несколько интерфейсов объединены в мост (bridge), то достаточно создать PPPoE-сервер для этого моста. Подключения к нему будут приниматься на всех интерфейсах, входящих в мост.
На одном интерфейсе можно создать несколько PPPoE-серверов, отличающихся именем службы (Service Name). В этом случае то, к какой именно службе будет подключен клиент, определяется настройками имени службы на клиентском устройстве. Если на клиентском устройстве имя службы не определено, то клиент будет подключен к службе, первой ответившей на запрос.
Внимание! Не стоит создавать PPPoE-серверы на интернет-интерфейсах или интерфейсах, подключенных к локальной сети провайдера. Это может привести к неприятным последствиям как для провайдера, так и для вас.
1.9.3 Остальные PPP-серверы настраиваются аналогично PPtP или PPPoE, за исключением некоторых специфических параметров.
Manual:Interface/PPTP
Applies to RouterOS: v3, v4, v5+
Contents
Summary
Standards: RFC 2637
PPTP is a secure tunnel for transporting IP traffic using PPP. PPTP encapsulates PPP in virtual lines that run over IP. PPTP incorporates PPP and MPPE (Microsoft Point to Point Encryption) to make encrypted links. The purpose of this protocol is to make well-managed secure connections between routers as well as between routers and PPTP clients (clients are available for and/or included in almost all OSs including Windows).
Multilink PPP (MP) is supported in order to provide MRRU (the ability to transmit full-sized 1500 and larger packets) and bridging over PPP links (using Bridge Control Protocol (BCP) that allows the sending of raw Ethernet frames over PPP links). This way it is possible to setup bridging without EoIP. The bridge should either have an administratively set MAC address or an Ethernet-like interface in it, as PPP links do not have MAC addresses.
PPTP includes PPP authentication and accounting for each PPTP connection. Full authentication and accounting of each connection may be done through a RADIUS client or locally.
MPPE 128bit RC4 encryption is supported.
PPTP traffic uses TCP port 1723 and IP protocol GRE (Generic Routing Encapsulation, IP protocol ID 47), as assigned by the Internet Assigned Numbers Authority (IANA). PPTP can be used with most firewalls and routers by enabling traffic destined for TCP port 1723 and protocol 47 traffic to be routed through the firewall or router.
PPTP connections may be limited or impossible to setup though a masqueraded/NAT IP connection. Please see the Microsoft and RFC links listed below for more information.
PPTP Client
Sub-menu: /interface pptp-client
Properties
| Property | Description |
|---|---|
| add-default-route (yes | no; Default: no) | Whether to add PPTP remote address as a default route. |
| allow (mschap2 | mschap1 | chap | pap; Default: mschap2, mschap1, chap, pap) | Allowed authentication methods. |
| connect-to (IP; Default: ) | Remote address of PPTP server |
| default-route-distance (byte [0..255]; Default: 1) | sets distance value applied to auto created default route, if add-default-route is also selected |
| dial-on-demand (yes | no; Default: no) | connects to PPTP server only when outbound traffic is generated. If selected, then route with gateway address from 10.112.112.0/24 network will be added while connection is not established. |
| disabled (yes | no; Default: yes) | Whether interface is disabled or not. By default it is disabled |
| keepalive-timeout (integer; Default: 60) | Sets keepalive timeout in seconds. |
| max-mru (integer; Default: 1460) | Maximum Receive Unit. Max packet size that PPTP interface will be able to receive without packet fragmentation. |
| max-mtu (integer; Default: 1460) | Maximum Transmission Unit. Max packet size that PPTP interface will be able to send without packet fragmentation. |
| mrru (disabled | integer; Default: disabled) | Maximum packet size that can be received on the link. If a packet is bigger than tunnel MTU, it will be split into multiple packets, allowing full size IP or Ethernet packets to be sent over the tunnel. Read more >> |
| name (string; Default: ) | Descriptive name of the interface. |
| password (string; Default: «») | Password used for authentication. |
| profile (name; Default: default-encryption) | Used PPP profile. |
| user (string; Default: ) | User name used for authentication. |
Quick example
This example demonstrates how to set up PPTP client with username «pptp-hm», password «123» and server 10.1.101.100
PPTP Server
Sub-menu: /interface pptp-server
This sub-menu shows interfaces for each connected PPTP clients.
An interface is created for each tunnel established to the given server. There are two types of interfaces in PPTP server’s configuration
Dynamic interfaces appear when a user connects and disappear once the user disconnects, so it is impossible to reference the tunnel created for that use in router configuration (for example, in firewall), so if you need persistent rules for that user, create a static entry for him/her. Otherwise it is safe to use dynamic configuration.
Server configuration
Sub-menu: /interface pptp-server server
| Property | Description |
|---|---|
| authentication (pap | chap | mschap1 | mschap2; Default: mschap1,mschap2) | Authentication methods that server will accept. |
| default-profile (name; Default: default-encryption) | Default PPP Profile to use |
| enabled (yes | no; Default: no) | Defines whether PPTP server is enabled or not. |
| keepalive-timeout (time; Default: 30) | If server during keepalive period does not receive any packet, it will send keepalive packets every second five times. If the server does not receives response from the client, then disconnect after 5 seconds. Logs will show 5x «LCP missed echo reply» messages and then disconnect. |
| max-mru (integer; Default: 1460) | Maximum Receive Unit. Max packet size that PPTP interface will be able to receive without packet fragmentation. |
| max-mtu (integer; Default: 1460) | Maximum Transmission Unit. Max packet size that PPTP interface will be able to send without packet fragmentation. |
| mrru (disabled | integer; Default: disabled) | Maximum packet size that can be received on the link. If a packet is bigger than tunnel MTU, it will be split into multiple packets, allowing full size IP or Ethernet packets to be sent over the tunnel. Read more >> |
To enable PPTP server:
Monitoring
Monitor command can be used to monitor status of the tunnel on both client and server.
| Property | Description |
|---|---|
| status ( ) | Current PPTP status. Value other than «connected» indicates that there are some problems establishing tunnel. |
| uptime (time) | Elapsed time since tunnel was established. |
| idle-time (time) | Elapsed time since last activity on the tunnel. |
| encoding ( ) | Used encryption method |
| mtu (integer) | Negotiated and used MTU |
| mru (integer) | Negotiated and used MRU |
Application Examples
Connecting Remote Client
The following example shows how to connect a computer to a remote office network over a PPTP encrypted tunnel giving that computer an IP address from the same network that the remote office has (without any need of bridging over EoIP tunnels).
Consider following setup:

Office router is connected to internet through ether1. Workstations are connected to ether2. Laptop is connected to the internet and can reach Office router’s public IP (in our example it is 192.168.80.1).
First step is to create a user
Notice that the PPTP local address is the same as the router’s address on the local interface and the remote address is from the same range as the local network (10.1.101.0/24).
Next step is to enable the PPTP server and the PPTP client on the laptop.
PPTP client from the laptop should connect to routers public IP which in our example is 192.168.80.1.
(Consult the respective manual on how to set up a PPTP client with the operating system software you are using).
At this point (when PPTP client is successfully connected) if you try to ping any workstation form the laptop, the ping will time out because the Laptop is unable to get ARPs from workstations. The solution is to set up proxy-arp on the local interface.
After proxy-arp is enabled, the remote client can successfully reach all workstations in the local network behind the router.
Site-to-Site PPTP
The following is an example of connecting two Intranets using PPTP tunnel over the Internet.
Consider following setup:

Office and Home routers are connected to the internet through ether1, workstations and laptops are connected to ether2. Both local networks are routed through a PPTP client, thus they are not in the same broadcast domain. If both networks should be in the same broadcast domain then you need to use BCP and bridge the PPTP tunnel with the local interface.
First step is to create a user
Notice that we set up PPTP server’s PPP secret where a route is added automatically whenever the client connects. If this option is not set, then you will need to add static routing on the server to route traffic between the two sites through the PPTP tunnel. (See PPP User Database for more info on routes variable).
Next step is to enable the PPTP server on the office router and configure the PPTP client on the Home router.
Now we need to add the route to reach the local network behind the Home router
Now after the tunnel is established and routes are set, you should be able to ping remote network.
Manual:PPP AAA
Applies to RouterOS: 2.9, v3, v4, v5
Contents
Summary
The MikroTik RouterOS provides scalable Authentication, Authorization and Accounting (AAA) functionality.
Local authentication is performed using the User Database and the Profile Database. The actual configuration for the given user is composed using the respective user record from the User Database, associated item from the Profile Database, and the item in the Profile database which is set as default for a given service the user is authenticating to. Default profile settings from the Profile database have the lowest priority while the user access record settings from the User Database have the highest priority with the only exception being particular IP addresses take precedence over IP pools in the local-address and remote-address settings, which described later on.
Support for RADIUS authentication gives the ISP or network administrator the ability to manage PPP user access and accounting from one server throughout a large network. The MikroTik RouterOS has a RADIUS client which can authenticate for PPP, PPPoE, PPTP, L2TP and ISDN connections. The attributes received from RADIUS server override the ones set in the default profile, but if some parameters are not received they are taken from the respective default profile.
User Profiles
Sub-menu: /ppp profile
PPP profiles are used to define default values for user access records stored under /ppp secret submenu. Settings in /ppp secret User Database override corresponding /ppp profile settings except that single IP addresses always take precedence over IP pools when specified as local-address or remote-address parameters.
Properties
Notes
There are two default profiles that cannot be removed:
Use Van Jacobson compression only if you have to because it may slow down the communications on bad or congested channels.
incoming-filter and outgoing-filter arguments add dynamic jump rules to chain ppp, where the jump-target argument will be equal to incoming-filter or outgoing-filter argument in /ppp profile. Therefore, chain ppp should be manually added before changing these arguments.
only-one parameter is ignored if RADIUS authentication is used.
If there are more that 10 simultaneous PPP connections planned, it is recommended to turn the change-mss property off, and use one general MSS changing rule in mangle table instead, to reduce CPU utilization.
User Database
Sub-menu: /ppp secret
PPP User Database stores PPP user access records with PPP user profile assigned to each user.
Properties
| Property | Description |
|---|---|
| caller-id (string; Default: ) | For PPTP and L2TP it is the IP address a client must connect from. For PPPoE it is the MAC address (written in CAPITAL letters) a client must connect from. For ISDN it is the caller’s number (that may or may not be provided by the operator) the client may dial-in from |
| comment (string; Default: ) | Short description of the user. |
| disabled (yes | no; Default: no) | Whether secret will be used. |
| limit-bytes-in (integer; Default: 0) | Maximal amount of bytes for a session that client can upload. |
| limit-bytes-out (integer; Default: 0) | Maximal amount of bytes for a session that client can download. |
| local-address (IP address; Default: ) | IP address that will be set locally on ppp interface. |
| name (string; Default: ) | Name used for authentication |
| password (string; Default: ) | Password used for authentication |
| profile (string; Default: default) | Which user profile to use. |
| remote-address (IP; Default: ) | IP address that will be assigned to remote ppp interface. |
| remote-ipv6-prefix (IPv6 prefix; Default: ) | IPv6 prefix assigned to ppp client. Prefix is added to ND prefix list enabling stateless address auto-configuration on ppp interface.Available starting from v5.0. |
| routes (string; Default: ) | Routes that appear on the server when the client is connected. The route format is: dst-address gateway metric (for example, 10.1.0.0/ 24 10.0.0.1 1). Other syntax is not acceptable since it can be represented in incorrect way. Several routes may be specified separated with commas. This parameter will be ignored for OpenVPN. |
| service (any | async | isdn | l2tp | pppoe | pptp | ovpn | sstp; Default: any) | Specifies the services that particular user will be able to use. |
Active Users
Sub-menu: /ppp active
This submenu allows to monitor active (connected) users.
/ppp active print command will show all currently connected users.
/ppp active print stats command will show received/sent bytes and packets
Properties
| Property | Description |
|---|---|
| address (IP address) | IP address the client got from the server |
| bytes (integer) | Amount of bytes transfered through tis connection. First figure represents amount of transmitted traffic from the router’s point of view, while the second one shows amount of received traffic. |
| caller-id (string) | For PPTP and L2TP it is the IP address the client connected from. For PPPoE it is the MAC address the client connected from. |
| encoding (string) | Shows encryption and encoding (separated with ‘/’ if asymmetric) being used in this connection |
| limit-bytes-in (integer) | Maximal amount of bytes the user is allowed to send to the router. |
| limit-bytes-out (integer) | Maximal amount of bytes the user is allowed to send to the client. |
| name (string) | User name supplied at authentication stage |
| packets (integer/integer) | Amount of packets transfered through tis connection. First figure represents amount of transmitted traffic from the router’s point of view, while the second one shows amount of received traffic |
| service (async | isdn | l2tp | pppoe | pptp | ovpn | sstp) | Type of service the user is using. |
| session-id (string) | Shows unique client identifier. |
| uptime (time) | User’s uptime |
Remote AAA
Settings in this submenu allows to set RADIUS accounting and authentication. Note that RADIUS user database is consulted only if the required username is not found in local user database.
Properties
| Property | Description |
|---|---|
| accounting (yes | no; Default: yes) | Enable RADIUS accounting |
| interim-update (time; Default: 0s) | Interim-Update time interval |
| use-radius (yes | no; Default: no) | Enable user authentication via RADIUS. If entry in local secret database is not found, then client will be authenticated via RADIUS. |
Examples
Add new profile
To add the profile ex that assigns the router itself the 10.0.0.1 address, and the addresses from the ex pool to the clients, filtering traffic coming from clients through mypppclients chain:
Add new user
To add the user ex with password lkjrht and profile ex available for PPTP service only, enter the following command:




