I think that I shall never see
A graph more lovely than a tree.
A tree whose crucial propertyеу
Is loop-free connectivity.
A tree that must be sure to span
So packets can reach every LAN.
First, the root must be selected.
By ID, it is elected.
Least-cost paths from root are traced.
In the tree, these paths are placed.
A mesh is made by folks like me,
Then bridges find a spanning tree.
— Radia Joy Perlman
Все выпуски
6. Сети для самых маленьких. Часть шестая. Динамическая маршрутизация
5. Сети для самых маленьких: Часть пятая. NAT и ACL
4. Сети для самых маленьких: Часть четвёртая. STP
3. Сети для самых маленьких: Часть третья. Статическая маршрутизация
2. Сети для самых маленьких. Часть вторая. Коммутация
1. Сети для самых маленьких. Часть первая. Подключение к оборудованию cisco
0. Сети для самых маленьких. Часть нулевая. Планирование
В прошлом выпуске мы остановились на статической маршрутизации. Теперь надо сделать шаг в сторону и обсудить вопрос стабильности нашей сети.
Однажды, когда вы — единственный сетевой админ фирмы “Лифт ми Ап” — отпросились на полдня раньше, вдруг упала связь с серверами, и директора не получили несколько важных писем. После короткой, но ощутимой взбучки вы идёте разбираться, в чём дело, а оказалось, по чьей-то неосторожности выпал из разъёма единственный кабель, ведущий к коммутатору в серверной. Небольшая проблема, которую вы могли исправить за две минуты, и даже вообще избежать, существенно сказалась на вашем доходе в этом месяце и возможностях роста.
Итак, сегодня обсуждаем:
- проблему широковещательного шторма
- работу и настройку протокола STP и его модификаций (RSTP, MSTP, PVST, PVST+)
- технологию агрегации интерфейсов и перераспределения нагрузки между ними
- некоторые вопросы стабильности и безопасности
- как изменить схему существующей сети, чтобы всем было хорошо
Оборудование, работающее на втором уровне модели OSI (коммутатор), должно выполнять 3 функции: запоминание адресов, перенаправление (коммутация) пакетов, защита от петель в сети. Разберем по пунктам каждую функцию.
Запоминание адресов и перенаправление пакетов: Как мы уже говорили ранее, у каждого свича есть таблица сопоставления MAC-адресов и портов (aka CAM-table — Content Addressable Memory Table). Когда устройство, подключенное к свичу, посылает кадр в сеть, свич смотрит MAC-адрес отправителя и порт, откуда получен кадр, и добавляет эту информацию в свою таблицу. Далее он должен передать кадр получателю, адрес которого указан в кадре. По идее, информацию о порте, куда нужно отправить кадр, он берёт из этой же CAM-таблицы. Но, предположим, что свич только что включили (таблица пуста), и он понятия не имеет, в какой из его портов подключен получатель. В этом случае он отправляет полученный кадр во все свои порты, кроме того, откуда он был принят. Все конечные устройства, получив этот кадр, смотрят MAC-адрес получателя, и, если он адресован не им, отбрасывают его. Устройство-получатель отвечает отправителю, а в поле отправителя ставит свой адрес, и вот свич уже знает, что такой-то адрес находится на таком-то порту (вносит запись в таблицу), и в следующий раз уже будет переправлять кадры, адресованные этому устройству, только в этот порт. Чтобы посмотреть содержимое CAM-таблицы, используется команда show mac address-table. Однажды попав в таблицу, информация не остаётся там пожизненно, содержимое постоянно обновляется и если к определенному mac-адресу не обращались 300 секунд (по умолчанию), запись о нем удаляется.
Тут всё должно быть понятно. Но зачем защита от петель? И что это вообще такое?
Широковещательный шторм
Часто, для обеспечения стабильности работы сети в случае проблем со связью между свичами (выход порта из строя, обрыв провода), используют избыточные линки (redundant links) — дополнительные соединения. Идея простая — если между свичами по какой-то причине не работает один линк, используем запасной. Вроде все правильно, но представим себе такую ситуацию: два свича соединены двумя проводами (пусть будет, что у них соединены fa0/1 и fa0/24).
Одной из их подопечных — рабочих станций (например, ПК1) вдруг приспичило послать широковещательный кадр (например, ARP-запрос). Раз широковещательный, шлем во все порты, кроме того, с которого получили.
Второй свич получает кадр в два порта, видит, что он широковещательный, и тоже шлет во все порты, но уже, получается, и обратно в те, с которых получил (кадр из fa0/24 шлет в fa0/1, и наоборот).
Первый свич поступает точно также, и в итоге мы получаем широковещательный шторм (broadcast storm), который намертво блокирует работу сети, ведь свичи теперь только и занимаются тем, что шлют друг другу один и тот же кадр.
Как можно избежать этого? Ведь мы, с одной стороны, не хотим штормов в сети, а с другой, хотим повысить ее отказоустойчивость с помощью избыточных соединений? Тут на помощь нам приходит STP (Spanning Tree Protocol)
STP
Основная задача STP — предотвратить появление петель на втором уровне. Как это сделать? Да просто отрубить все избыточные линки, пока они нам не понадобятся. Тут уже сразу возникает много вопросов: какой линк из двух (или трех-четырех) отрубить? Как определить, что основной линк упал, и пора включать запасной? Как понять, что в сети образовалась петля? Чтобы ответить на эти вопросы, нужно разобраться, как работает STP.
STP использует алгоритм STA (Spanning Tree Algorithm), результатом работы которого является граф в виде дерева (связный и без простых циклов)
Для обмена информацией между собой свичи используют специальные пакеты, так называемые BPDU (Bridge Protocol Data Units). BPDU бывают двух видов: конфигурационные (Configuration BPDU) и панические “ААА, топология поменялась!” TCN (Topology Change Notification BPDU). Первые регулярно рассылаются корневым свичом (и ретранслируются остальными) и используются для построения топологии, вторые, как понятно из названия, отсылаются в случае изменения топологии сети (проще говоря, подключении\отключении свича). Конфигурационные BPDU содержат несколько полей, остановимся на самых важных:
- идентификатор отправителя (Bridge ID)
- идентификатор корневого свича (Root Bridge ID)
- идентификатор порта, из которого отправлен данный пакет (Port ID)
- стоимость маршрута до корневого свича (Root Path Cost)
Что все это такое и зачем оно нужно, объясню чуть ниже. Так как устройства не знают и не хотят знать своих соседей, никаких отношений (смежности/соседства) они друг с другом не устанавливают. Они шлют BPDU из всех работающих портов на мультикастовый ethernet-адрес 01-80-c2-00-00-00 (по умолчанию каждые 2 секунды), который прослушивают все свичи с включенным STP.
Итак, как же формируется топология без петель?
Сначала выбирается так называемый корневой мост/свич (root bridge). Это устройство, которое STP считает точкой отсчета, центром сети; все дерево STP сходится к нему. Выбор базируется на таком понятии, как идентификатор свича (Bridge ID). Bridge ID это число длиной 8 байт, которое состоит из Bridge Priority (приоритет, от 0 до 65535, по умолчанию 32768+номер vlan или инстанс MSTP, в зависимости от реализации протокола), и MAC-адреса устройства. В начале выборов каждый коммутатор считает себя корневым, о чем и заявляет всем остальным с помощью BPDU, в котором представляет свой идентификатор как ID корневого свича. При этом, если он получает BPDU с меньшим Bridge ID, он перестает хвастаться своим и покорно начинает анонсировать полученный Bridge ID в качестве корневого. В итоге, корневым оказывается тот свич, чей Bridge ID меньше всех.
Такой подход таит в себе довольно серьезную проблему. Дело в том, что, при равных значениях Priority (а они равные, если не менять ничего) корневым выбирается самый старый свич, так как мак адреса прописываются на производстве последовательно, соответственно, чем мак меньше, тем устройство старше (естественно, если у нас все оборудование одного вендора). Понятное дело, это ведет к падению производительности сети, так как старое устройство, как правило, имеет худшие характеристики. Подобное поведение протокола следует пресекать, выставляя значение приоритета на желаемом корневом свиче вручную, об этом в практической части.
Роли портов
После того, как коммутаторы померились айдями и выбрали root bridge, каждый из остальных свичей должен найти один, и только один порт, который будет вести к корневому свичу. Такой порт называется корневым портом (Root port). Чтобы понять, какой порт лучше использовать, каждый некорневой свич определяет стоимость маршрута от каждого своего порта до корневого свича. Эта стоимость определяется суммой стоимостей всех линков, которые нужно пройти кадру, чтобы дойти до корневого свича. В свою очередь, стоимость линка определяется просто- по его скорости (чем выше скорость, тем меньше стоимость). Процесс определения стоимости маршрута связан с полем BPDU “Root Path Cost” и происходит так:
- Корневой свич посылает BPDU с полем Root Path Cost, равным нулю
- Ближайший свич смотрит на скорость своего порта, куда BPDU пришел, и добавляет стоимость согласно таблице
Скорость порта Стоимость STP (802.1d) 10 Mbps 100 100 Mbps 19 1 Gbps 4 10 Gbps 2 - Далее этот второй свич посылает этот BPDU нижестоящим коммутаторам, но уже с новым значением Root Path Cost, и далее по цепочке вниз
Если имеют место одинаковые стоимости (как в нашем примере с двумя свичами и двумя проводами между ними — у каждого пути будет стоимость 19) — корневым выбирается меньший порт.
Далее выбираются назначенные (Designated) порты. Из каждого конкретного сегмента сети должен существовать только один путь по направлению к корневому свичу, иначе это петля. В данном случае имеем в виду физический сегмент, в современных сетях без хабов это, грубо говоря, просто провод. Назначенным портом выбирается тот, который имеет лучшую стоимость в данном сегменте. У корневого свича все порты — назначенные.
И вот уже после того, как выбраны корневые и назначенные порты, оставшиеся блокируются, таким образом разрывая петлю.
*На картинке маршрутизаторы выступают в качестве коммутаторов. В реальной жизни это можно сделать с помощью дополнительной свитчёвой платы.
Состояния портов
Чуть раньше мы упомянули состояние блокировки порта, теперь поговорим о том, что это значит, и о других возможных состояниях порта в STP. Итак, в обычном (802.1D) STP существует 5 различных состояний:
- блокировка (blocking): блокированный порт не шлет ничего. Это состояние предназначено, как говорилось выше, для предотвращения петель в сети. Блокированный порт, тем не менее, слушает BPDU (чтобы быть в курсе событий, это позволяет ему, когда надо, разблокироваться и начать работать)
- прослушивание (listening): порт слушает и начинает сам отправлять BPDU, кадры с данными не отправляет.
- обучение (learning): порт слушает и отправляет BPDU, а также вносит изменения в CAM- таблицу, но данные не перенаправляет.
- перенаправление\пересылка (forwarding): этот может все: и посылает\принимает BPDU, и с данными оперирует, и участвует в поддержании таблицы mac-адресов. То есть это обычное состояние рабочего порта.
- отключен (disabled): состояние administratively down, отключен командой shutdown. Понятное дело, ничего делать не может вообще, пока вручную не включат.
Порядок перечисления состояний не случаен: при включении (а также при втыкании нового провода), все порты на устройстве с STP проходят вышеприведенные состояния именно в таком порядке (за исключением disabled-портов). Возникает закономерный вопрос: а зачем такие сложности? А просто STP осторожничает. Ведь на другом конце провода, который только что воткнули в порт, может быть свич, а это потенциальная петля. Вот поэтому порт сначала 15 секунд (по умолчанию) пребывает в состоянии прослушивания — он смотрит BPDU, попадающие в него, выясняет свое положение в сети — как бы чего ни вышло, потом переходит к обучению еще на 15 секунд — пытается выяснить, какие mac-адреса “в ходу” на линке, и потом, убедившись, что ничего он не поломает, начинает уже свою работу. Итого, мы имеем целых 30 секунд простоя, прежде чем подключенное устройство сможет обмениваться информацией со своими соседями. Современные компы грузятся быстрее, чем за 30 секунд. Вот комп загрузился, уже рвется в сеть, истерит на тему “DHCP-сервер, сволочь, ты будешь айпишник выдавать, или нет?”, и, не получив искомого, обижается и уходит в себя, извлекая из своих недр айпишник автонастройки. Естественно, после таких экзерсисов, в сети его слушать никто не будет, ибо “не местный” со своим 169.254.x.x. Понятно, что все это не дело, но как этого избежать?
Portfast
Для таких случаев используется особый режим порта — portfast. При подключении устройства к такому порту, он, минуя промежуточные стадии, сразу переходит к forwarding-состоянию. Само собой, portfast следует включать только на интерфейсах, ведущих к конечным устройствам (рабочим станциям, серверам, телефонам и т.д.), но не к другим свичам.
Есть очень удобная команда режима конфигурации интерфейса для включения нужных фич на порту, в который будут включаться конечные устройства: switchport host. Эта команда разом включает PortFast, переводит порт в режим access (аналогично switchport mode access), и отключает протокол PAgP (об этом протоколе подробнее в разделе агрегация каналов).
Виды STP
STP довольно старый протокол, он создавался для работы в одном LAN-сегменте. А что делать, если мы хотим внедрить его в нашей сети, которая имеет несколько VLANов?
Стандарт 802.1Q, о котором мы упоминали в статье о коммутации, определяет, каким образом вланы передаются внутри транка. Кроме того, он определяет один процесс STP для всех вланов. BPDU по транкам передаются нетегированными (в native VLAN). Этот вариант STP известен как CST (Common Spanning Tree). Наличие только одного процесса для всех вланов очень облегчает работу по настройке и разгружает процессор свича, но, с другой стороны, CST имеет недостатки: избыточные линки между свичами блокируются во всех вланах, что не всегда приемлемо и не дает возможности использовать их для балансировки нагрузки.
Cisco имеет свой взгляд на STP, и свою проприетарную реализацию протокола — PVST (Per-VLAN Spanning Tree) — которая предназначена для работы в сети с несколькими VLAN. В PVST для каждого влана существует свой процесс STP, что позволяет независимую и гибкую настройку под потребности каждого влана, но самое главное, позволяет использовать балансировку нагрузки за счет того, что конкретный физический линк может быть заблокирован в одном влане, но работать в другом. Минусом этой реализации является, конечно, проприетарность: для функционирования PVST требуется проприетарный же ISL транк между свичами.
Также существует вторая версия этой реализации — PVST+, которая позволяет наладить связь между свичами с CST и PVST, и работает как с ISL- транком, так и с 802.1q. PVST+ это протокол по умолчанию на коммутаторах Cisco.
RSTP
Все, о чем мы говорили ранее в этой статье, относится к первой реализация протокола STP, которая была разработана в 1985 году Радией Перлман (ее стихотворение использовано в качестве эпиграфа). В 1990 году эта реализации была включена в стандарт IEEE 802.1D. Тогда время текло медленнее, и перестройка топологии STP, занимающая 30-50 секунд (!!!), всех устраивала. Но времена меняются, и через десять лет, в 2001 году, IEEE представляет новый стандарт RSTP (он же 802.1w, он же Rapid Spanning Tree Protocol, он же Быстрый STP). Чтобы структурировать предыдущий материал и посмотреть различия между обычным STP (802.1d) и RSTP (802.1w), соберем таблицу с основными фактами:
| STP (802.1d) | RSTP (802.1w) |
| В уже сложившейся топологии только корневой свич шлет BPDU, остальные ретранслируют | Все свичи шлют BPDU в соответствии с hello-таймером (2 секунды по умолчанию) |
| Состояния портов | |
| — блокировка (blocking) — прослушивание (listening) — обучение (learning) — перенаправление\пересылка (forwarding) — отключен (disabled) |
— отбрасывание (discarding), заменяет disabled, blocking и listening — learning — forwarding |
| Роли портов | |
| — корневой (root), участвует в пересылке данных, ведет к корневому свичу — назначенный (designated), тоже работает, ведет от корневого свича — неназначенный (non-designated), не участвует в пересылке данных |
— корневой (root), участвует в пересылке данных — назначенный (designated), тоже работает — дополнительный (alternate), не участвует в пересылке данных — резервный (backup), тоже не участвует |
| Механизмы работы | |
| Использует таймеры: Hello (2 секунды) Max Age (20 секунд) Forward delay timer (15 секунд) |
Использует процесс proposal and agreement (предложение и соглашение) |
| Свич, обнаруживший изменение топологии, извещает корневой свич, который, в свою очередь, требует от всех остальных очистить их записи о текущей топологии в течение forward delay timer | Обнаружение изменений в топологии влечет немедленную очистку записей |
| Если не-корневой свич не получает hello- пакеты от корневого в течение Max Age, он начинает новые выборы | Начинает действовать, если не получает BPDU в течение 3 hello-интервалов |
| Последовательное прохождение порта через состояния Blocking (20 сек) — Listening (15 сек) — Learning (15 сек) — Forwarding | Быстрый переход к Forwarding для p2p и Edge-портов |
Как мы видим, в RSTP остались такие роли портов, как корневой и назначенный, а роль заблокированного разделили на две новых роли: Alternate и Backup. Alternate — это резервный корневой порт, а backup — резервный назначенный порт. Как раз в этой концепции резервных портов и кроется одна из причин быстрого переключения в случае отказа. Это меняет поведение системы в целом: вместо реактивной (которая начинает искать решение проблемы только после того, как она случилась) система становится проактивной, заранее просчитывающей “пути отхода” еще до появления проблемы. Смысл простой: для того, чтобы в случае отказа основного переключится на резервный линк, RSTP не нужно заново просчитывать топологию, он просто переключится на запасной, заранее просчитанный.
Ранее, для того, чтобы убедиться, что порт может участвовать в передаче данных, требовались таймеры, т.е. свич пассивно ждал в течение означенного времени, слушая BPDU. Ключевой фичей RSTP стало введение концепции типов портов, основанных на режиме работы линка- full duplex или half duplex (типы портов p2p или shared, соответственно), а также понятия пограничный порт (тип edge p2p), для конечных устройств. Пограничные порты назначаются, как и раньше, командой spanning-tree portfast, и с ними все понятно- при включении провода сразу переходим к forwarding-состоянию и работаем. Shared-порты работают по старой схеме с прохождением через состояния BLK — LIS — LRN — FWD. А вот на p2p-портах RSTP использует процесс предложения и соглашения (proposal and agreement). Не вдаваясь в подробности, его можно описать так: свич справедливо считает, что если линк работает в режиме полного дуплекса, и он не обозначен, как пограничный, значит, на нем только два устройства- он и другой свич. Вместо того, чтобы ждать входящих BPDU, он сам пытается связаться со свичом на том конце провода с помощью специальных proposal BPDU, в которых, конечно, есть информация о стоимости маршрута к корневому свичу. Второй свич сравнивает полученную информацию со своей текущей, и принимает решение, о чем извещает первый свич посредством agreement BPDU. Так как весь этот процесс теперь не привязан к таймерам, происходит он очень быстро- только подключили новый свич- и он практически сразу вписался в общую топологию и приступил к работе (можете сами оценить скорость переключения в сравнении с обычным STP на видео). В Cisco-мире RSTP называется PVRST (Per-Vlan Rapid Spanning Tree).
MSTP
Чуть выше, мы упоминали о PVST, в котором для каждого влана существует свой процесс STP. Вланы это довольно удобный инструмент для многих целей, и поэтому, их может быть достаточно много даже в некрупной организации. И в случае PVST, для каждого будет рассчитываться своя топология, тратиться процессорное время и память свичей. А нужно ли нам рассчитывать STP для всех 500 вланов, когда единственное место, где он нам нужен- это резервный линк между двумя свичами? Тут нас выручает MSTP. В нем каждый влан не обязан иметь собственный процесс STP, их можно объединять. Вот у нас есть, например, 500 вланов, и мы хотим балансировать нагрузку так, чтобы половина из них работала по одному линку (второй при этом блокируется и стоит в резерве), а вторая- по другому. Это можно сделать с помощью обычного STP, назначив один корневой свич в диапазоне вланов 1-250, а другой- в диапазоне 250-500. Но процессы будут работать для каждого из пятисот вланов по отдельности (хотя действовать будут совершенно одинаково для каждой половины). Логично, что тут хватит и двух процессов. MSTP позволяет создавать столько процесов STP, сколько у нас логических топологий (в данном примере- 2), и распределять по ним вланы. Думаем, нет особого смысла углубляться в теорию и практику MSTP в рамках этой статьи (ибо теории там ого-го), интересующиеся могут пройти по ссылке.
Агрегация каналов
Но какой бы вариант STP мы не использовали, у нас все равно существует так или иначе неработающий линк. А возможно ли задействовать параллельные линки по полной и при этом избежать петель? Да, отвечаем мы вместе с циской, начиная рассказ о EtherChannel.
Иначе это называется link aggregation, link bundling, NIC teaming, port trunkinkg
Технологии агрегации (объединения) каналов выполняют 2 функции: с одной стороны, это объединение пропускной способности нескольких физических линков, а с другой — обеспечение отказоустойчивости соединения (в случае падения одного линка нагрузка переносится на оставшиеся). Объединение линков можно выполнить как вручную (статическое агрегирование), так и с помощью специальных протоколов: LACP (Link Aggregation Control Protocol) и PAgP (Port Aggregation Protocol). LACP, опеределяемый стандартом IEEE 802.3ad, является открытым стандартом, то есть от вендора оборудования не зависит. Соответственно, PAgP — проприетарная цисковская разработка.
В один такой канал можно объединить до восьми портов. Алгоритм балансировки нагрузки основан на таких параметрах, как IP/MAC-адреса получателей и отправителей и порты. Поэтому в случае возникновения вопроса: “Хей, а чего так плохо балансируется?” в первую очередь смотрите на алгоритм балансировки.
Тема агрегации каналов заслуживает отдельной статьи, а то и книги, поэтому углубляться не будем, интересующимся- ссылка.
Port security
Теперь расскажем вкратце, как обеспечить безопасность сети на втором уровне OSI. В этой части статьи теория и практическая конфигурация совмещены. Увы, Packet Tracer не умеет ничего из упомянутых в этом разделе команд, поэтому все без иллюстраций и проверок.
Для начала, следует упомянуть команду конфигурации интерфейса switchport port-security, включающую защиту на определенном порту свича. Затем, с помощью switchport port-security maximum 1 мы можем ограничить количество mac-адресов, связанных с данным портом (т.е., в нашем примере, на данном порту может работать только один mac-адрес). Теперь указываем, какой именно адрес разрешен: его можно задать вручную switchport port-security mac-address адрес, или использовать волшебную команду switchport port-security mac-address sticky, закрепляющую за портом тот адрес, который в данный момент работает на порту. Далее, задаем поведение в случае нарушения правила switchport port-security violation {shutdown | restrict | protect}: порт либо отключается, и потом его нужно поднимать вручную (shutdown), либо отбрасывает пакеты с незарегистрированного мака и пишет об этом в консоль (restrict), либо просто отбрасывает пакеты (protect).
Помимо очевидной цели — ограничение числа устройств за портом — у этой команды есть другая, возможно, более важная: предотвращать атаки. Одна из возможных — истощение CAM-таблицы. С компьютера злодея рассылается огромное число кадров, возможно, широковещательных, с различными значениями в поле MAC-адрес отправителя. Первый же коммутатор на пути начинает их запоминать. Одну тысячу он запомнит, две, но память-то оперативная не резиновая, и среднее ограничение в 16000 записей будет довольно быстро достигнуто. При этом дальнейшее поведение коммутатора может быть различным. И самое опасное из них с точки зрения безопасности: коммутатор может начать все кадры, приходящие на него, рассылать, как широковещательные, потому что MAC-адрес получателя не известен (или уже забыт), а запомнить его уже просто некуда. В этом случае сетевая карта злодея будет получать все кадры, летающие в вашей сети.
DHCP Snooping
Другая возможная атака нацелена на DHCP сервер. Как мы знаем, DHCP обеспечивает клиентские устройства всей нужной информацией для работы в сети: ip-адресом, маской подсети, адресом шюза по умолчанию, DNS-сервера и прочим. Атакующий может поднять собственный DHCP, который в ответ на запрос клиентского устройства будет отдавать в качестве шлюза по умолчанию (а также, например, DNS-сервера) адрес подконтрольной атакующему машины. Соответственно, весь трафик, направленный за пределы подсети обманутыми устройствами, будет доступен для изучения атакующему — типичная man-in-the-middle атака. Либо такой вариант: подлый мошенник генерируют кучу DHCP-запросов с поддельными MAC-адресами и DHCP-сервер на каждый такой запрос выдаёт IP-адрес до тех пор, пока не истощится пул.
Для того, чтобы защититься от подобного вида атак, используется фича под названием DHCP snooping. Идея совсем простая: указать свичу, на каком порту подключен настоящий DHCP-сервер, и разрешить DHCP-ответы только с этого порта, запретив для остальных. Включаем глобально командой ip dhcp snooping, потом говорим, в каких вланах должно работать ip dhcp snooping vlan номер(а). Затем на конкретном порту говорим, что он может пренаправлять DHCP-ответы (такой порт называется доверенным): ip dhcp snooping trust.
IP Source Guard
После включения DHCP Snooping’а, он начинает вести у себя базу соответствия MAC и IP-адресов устройств, которую обновляет и пополняет за счет прослушивания DHCP запросов и ответов. Эта база позволяет нам противостоять еще одному виду атак — подмене IP-адреса (IP Spoofing). При включенном IP Source Guard, каждый приходящий пакет может проверяться на:
- соответствие IP-адреса источника адресу, полученному из базы DHCP Snooping (иными словами, айпишник закрепляется за портом свича)
- соответствие MAC-адреса источника адресу, полученному из базы DHCP Snooping
Включается IP Source Guard командой ip verify source на нужном интерфейсе. В таком виде проверяется только привязка IP-адреса, чтобы добавить проверку MAC, используем ip verify source port-security. Само собой, для работы IP Source Guard требуется включенный DHCP snooping, а для контроля MAC-адресов должен быть включен port security.
Dynamic ARP Inspection
Как мы уже знаем, для того, чтобы узнать MAC-адрес устройства по его IP-адресу, используется проткол ARP: посылается широковещательный запрос вида “у кого ip-адрес 172.16.1.15, ответьте 172.16.1.1”, устройство с айпишником 172.16.1.15 отвечает. Подобная схема уязвима для атаки, называемой ARP-poisoning aka ARP-spoofing: вместо настоящего хоста с адресом 172.16.1.15 отвечает хост злоумышленника, заставляя таким образом трафик, предназначенный для 172.16.1.15 следовать через него. Для предотвращения такого типа атак используется фича под названием Dynamic ARP Inspection. Схема работы похожа на схему DHCP-Snooping’а: порты делятся на доверенные и недоверенные, на недоверенных каждый ARP-ответ подвергаются анализу: сверяется информация, содержащаяся в этом пакете, с той, которой свич доверяет (либо статически заданные соответствия MAC-IP, либо информация из базы DHCP Snooping). Если не сходится- пакет отбрасывается и генерируется сообщение в syslog. Включаем в нужном влане (вланах): ip arp inspection vlan номер(а). По умолчанию все порты недоверенные, для доверенных портов используем ip arp inspection trust.
Практика
Наверное, большинство ошибок в Packet Tracer допущено в части кода, отвечающего за симуляцию STP, будте готовы. В случае сомнения сохранитесь, закройте PT и откройте заново
Итак, переходим к практике. Для начала внесем некоторые изменения в топологию — добавим избыточные линки. Учитывая сказанное в самом начале, вполне логично было бы сделать это в московском офисе в районе серверов — там у нас свич msk-arbat-asw2 доступен только через asw1, что не есть гуд. Мы отбираем (пока, позже возместим эту потерю) гигабитный линк, который идет от msk-arbat-dsw1 к msk-arbat-asw3, и подключаем через него asw2. Asw3 пока подключаем в порт Fa0/2 dsw1. Перенастраиваем транки:
msk-arbat-dsw1(config)#interface gi1/2
msk-arbat-dsw1(config-if)#description msk-arbat-asw2
msk-arbat-dsw1(config-if)#switchport trunk allowed vlan 2,3
msk-arbat-dsw1(config-if)#int fa0/2
msk-arbat-dsw1(config-if)#description msk-arbat-asw3
msk-arbat-dsw1(config-if)#switchport mode trunk
msk-arbat-dsw1(config-if)#switchport trunk allowed vlan 2,101-104msk-arbat-asw2(config)#int gi1/2
msk-arbat-asw2(config-if)#description msk-arbat-dsw1
msk-arbat-asw2(config-if)#switchport mode trunk
msk-arbat-asw2(config-if)#switchport trunk allowed vlan 2,3
msk-arbat-asw2(config-if)#no shutdown
Не забываем вносить все изменения в документацию!
Скачать актуальную версию документа.
Теперь посмотрим, как в данный момент у нас самонастроился STP. Нас интересует только VLAN0003, где у нас, судя по схеме, петля.
msk-arbat-dsw1>en
msk-arbat-dsw1#show spanning-tree vlan 3
Разбираем по полочкам вывод команды
Итак, какую информацию мы можем получить? Так как по умолчанию на современных цисках работает PVST+ (т.е. для каждого влана свой процесс STP), и у нас есть более одного влана, выводится информация по каждому влану в отдельности, каждая запись предваряется номером влана. Затем идет вид STP: ieee значит PVST, rstp — Rapid PVST, mstp то и значит. Затем идет секция с информацией о корневом свиче: установленный на нем приоритет, его mac-адрес, стоимость пути от текущего свича до корневого, порт, который был выбран в качестве корневого (имеет лучшую стоимость), а также настройки таймеров STP. Далее- секция с той же информацией о текущем свиче (с которого выполняли команду). Затем- таблица состояния портов, которая состоит из следующих колонок (слева направо):
- собственно, порт
- его роль (Root- корневой порт, Desg- назначенный порт, Altn- дополнительный, Back- резервный)
- его статус (FWD- работает, BLK- заблокирован, LIS- прослушивание, LRN- обучение)
- стоимость маршрута до корневого свича
- Port ID в формате: приоритет порта.номер порта
- тип соединения
Итак, мы видим, что Gi1/1 корневой порт, это дает некоторую вероятность того, что на другом конце линка корневой свич. Смотрим по схеме, куда ведет линк: ага, некий msk-arbat-asw1.
msk-arbat-asw1#show spanning-tree vlan 3
И что же мы видим?
VLAN0003
Spanning tree enabled protocol ieee
Root ID Priority 32771
Address 0007.ECC4.09E2
This bridge is the root
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Вот он, наш корневой свич для VLAN0003.
А теперь посмотрим на схему. Ранее, мы увидели в состоянии портов, что dsw1 блокирует порт Gi1/2, разрывая таким образом петлю. Но является ли это оптимальным решением? Нет, конечно. Сейчас наша новая сеть работает точь-в-точь как старая- трафик от asw2 идет только через asw1. Выбор корневого маршрутизатора никогда не нужно оставлять на совесть глупого STP. Исходя из схемы, наиболее оптимальным будет выбор в качестве корневого свича dsw1- таким образом, STP заблокирует линк между asw1 и asw2. Теперь это все надо объяснить недалекому протоколу. А для него главное что? Bridge ID. И он неслучайно складывается из двух чисел. Приоритет- это как раз то слагаемое, которое отдано на откуп сетевому инженеру, чтобы он мог повлиять на результат выбора корневого свича. Итак, наша задача сводится к тому, чтобы уменьшить (меньше-лучше, думает STP) приоритет нужного свича, чтобы он стал Root Bridge. Есть два пути:
1) вручную установить приоритет, заведомо меньший, чем текущий:
msk-arbat-dsw1>enable
msk-arbat-dsw1#configure terminal
msk-arbat-dsw1(config)#spanning-tree vlan 3 priority?
<0-61440> bridge priority in increments of 4096
msk-arbat-dsw1(config)#spanning-tree vlan 3 priority 4096
Теперь он стал корневым для влана 3, так как имеет меньший Bridge ID:
msk-arbat-dsw1#show spanning-tree vlan 3
VLAN0003
Spanning tree enabled protocol ieee
Root ID Priority 4099
Address 000B.BE2E.392C
This bridge is the root
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
2) дать умной железке решить все за тебя:
msk-arbat-dsw1(config)#spanning-tree vlan 3 root primary
Проверяем:
msk-arbat-dsw1#show spanning-tree vlan 3
VLAN0003
Spanning tree enabled protocol ieee
Root ID Priority 24579
Address 000B.BE2E.392C
This bridge is the root
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Мы видим, что железка поставила какой-то странный приоритет. Откуда взялась эта круглая цифра, спросите вы? А все просто- STP смотрит минимальный приоритет (т.е. тот, который у корневого свича), и уменьшает его на два шага инкремента (который составляет 4096, т.е. в итоге 8192). Почему на два? А чтобы была возможность на другом свиче дать команду spanning-tree vlan n root secondary (назначает приоритет=приоритет корневого-4096), что позволит нам быть уверенными, что, если с текущим корневым свичом что-то произойдет, его функции перейдут к этому, “запасному”. Вероятно, вы уже видите на схеме, как лампочка на линке между asw2 и asw1 пожелтела? Это STP разорвал петлю. Причем именно в том месте, в котором мы хотели. Sweet! Зайдем проверим: лампочка — это лампочка, а конфиг — это факт.
msk-arbat-asw2#show spanning-tree vlan 3
VLAN0003
Spanning tree enabled protocol ieee
Root ID Priority 24579
Address 000B.BE2E.392C
Cost 4
Port 26(GigabitEthernet1/2)
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Bridge ID Priority 32771 (priority 32768 sys-id-ext 3)
Address 000A.F385.D799
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Aging Time 20
Interface Role Sts Cost Prio.Nbr Type
---------------- ---- --- --------- -------- --------------------------------
Fa0/1 Desg FWD 19 128.1 P2p
Gi1/1 Altn BLK 4 128.25 P2p
Gi1/2 Root FWD 4 128.26 P2p
Теперь полюбуемся, как работает STP: заходим в командную строку на ноутбуке PTO1 и начинаем бесконечно пинговать наш почтовый сервер (172.16.0.4). Пинг сейчас идет по маршруту ноутбук-asw3-dsw1-gw1-dsw1(ну тут понятно, зачем он крюк делает — они из разных вланов)-asw2-сервер. А теперь поработаем Годзиллой из SimСity: нарушим связь между dsw1 и asw2, вырвав провод из порта (замечаем время, нужное для пересчета дерева).
Пинги пропадают, STP берется за дело, и за каких-то 30 секунд коннект восстанавливается. Годзиллу прогнали, пожары потушили, связь починили, втыкаем провод обратно. Пинги опять пропадают на 30 секунд! Мда-а-а, как-то не очень быстро, особенно если представить, что это происходит, например, в процессинговом центре какого-нибудь банка.
Но у нас есть ответ медленному PVST+! И ответ этот — Быстрый PVST+ (так и называется, это не шутка: Rapid-PVST). Посмотрим, что он нам дает. Меняем тип STP на всех свичах в москве командой конфигурационного режима: spanning-tree mode rapid-pvst
Снова запускаем пинг, вызываем Годзиллу… Эй, где пропавшие пинги? Их нет, это же Rapid-PVST. Как вы, наверное, помните из теоретической части, эта реализация STP, так сказать, “подстилает соломку” на случай падения основного линка, и переключается на дополнительный (alternate) порт очень быстро, что мы и наблюдали. Ладно, втыкаем провод обратно. Один потерянный пинг. Неплохо по сравнению с 6-8, да?
EtherChannel
Помните, мы отобрали у офисных работников их гигабитный линк и отдали его в пользу серверов? Сейчас они, бедняжки, сидят, на каких-то ста мегабитах, прошлый век! Попробуем расширить канал, и на помощь призовем EtherChannel. В данный момент у нас соединение идет от fa0/2 dsw1 на Gi1/1 asw3, отключаем провод. Смотрим, какие порты можем использовать на asw3: ага, fa0/20-24 свободны, кажется. Вот их и возьмем. Со стороны dsw1 пусть будут fa0/19-23. Соединяем порты для EtherChannel между собой. На asw3 у нас на интерфейсах что-то настроено, обычно в таких случаях используется команда конфигурационного режима default interface range fa0/20-24, сбрасывающая настройки порта (или портов, как в нашем случае) в дефолтные. Packet tracer, увы, не знает такой хорошей команды, поэтому в ручном режиме убираем каждую настройку, и тушим порты (лучше это сделать, во избежание проблем)
msk-arbat-asw3(config)#interface range fa0/20-24
msk-arbat-asw3(config-if-range)#no description
msk-arbat-asw3(config-if-range)#no switchport access vlan
msk-arbat-asw3(config-if-range)#no switchport mode
msk-arbat-asw3(config-if-range)#shutdown
ну а теперь волшебная команда
msk-arbat-asw3(config-if-range)#channel-group 1 mode on
то же самое на dsw1:
msk-arbat-dsw1(config)#interface range fa0/19-23
msk-arbat-dsw1(config-if-range)#channel-group 1 mode on
поднимаем интерфейсы asw3, и вуаля: вот он, наш EtherChannel, раскинулся аж на 5 физических линков. В конфиге он будет отражен как interface Port-channel 1. Настраиваем транк (повторить для dsw1):
msk-arbat-asw3(config)#int port-channel 1
msk-arbat-asw3(config-if)#switchport mode trunk
msk-arbat-asw3(config-if)#switchport trunk allowed vlan 2,101-104
Как и с STP, есть некая трудность при работе с etherchannel в Packet Tracer’e. Настроить-то мы, в принципе, можем по вышеописанному сценарию, но вот проверка работоспособности под большим вопросом: после отключения одного из портов в группе, трафик перетекает на следующий, но как только вы вырубаете второй порт — связь теряется и не восстанавливается даже после включения портов.
Отчасти в силу только что озвученной причины, отчасти из-за ограниченности ресурсов мы не сможем раскрыть в полной мере эти вопросы и посему оставляем бОльшую часть на самоизучение.
Материалы выпуска
Новый план коммутации
Файл PT с лабораторной.
Конфигурация устройств
STP или STP
Безопасность канального уровня
Агрегация каналов
По сложившейся традиции все неотвеченные вопросы безымянными читателями хабра задаются в блоге цикла в ЖЖ.
За видео и помощь в подготовке статьи спасибо eucariot
Спаннинг-три—протокол (STP) является одним из ключевых протоколов, используемых в сетях Ethernet для предотвращения циклических петель и обеспечения надежности и отказоустойчивости. Он позволяет автоматически определять и блокировать порты, которые могут создать петлю в сети.
Принцип работы STP заключается в создании дерева распространения, в котором каждый роутер выбирает один порт в качестве корневого. Остальные порты роутера могут быть либо назначены в режиме прослушивания, либо заблокированы в случае обнаружения петли.
Когда STP включен на роутере, он периодически отправляет BPDU (Bridge Protocol Data Units) на все порты, чтобы узнать текущее состояние сети и обменяться информацией с другими роутерами. Когда роутер получает BPDU, он выполняет несколько проверок, чтобы определить, нужно ли изменить состояние портов.
Статус STP на роутере может быть в одном из трех состояний: заблокирован, прослушивание и передача данных. Заблокированный порт не передает пакеты данных и используется только для передачи BPU. Порты в режиме прослушивания могут принимать пакеты, но не отправлять их. Порты передачи данных передают пакеты и активно участвуют в передаче данных в сети.
Включение и настройка STP на роутере позволяет значительно повысить надежность сети, предотвратить возникновение петель и обеспечить бесперебойную передачу данных.
Содержание
- Определение и назначение STP
- Принцип работы протокола STP
- Роли и состояния портов в STP
- Алгоритм выбора корневого моста в STP
- Процесс обнаружения и блокирования петель в STP
- Преимущества и недостатки использования STP на роутере
Определение и назначение STP
STP создает дерево, которое определяет наиболее оптимальные пути в сети и блокирует некоторые из них, чтобы избежать формирования петель данных. Он определяет и отключает резервные пути, которые не являются частью основного пути.
Когда в сети возникает петля, пакеты данных могут зацикливаться на несколько раз, вызывая непредсказуемое поведение сети, такое как задержки, потеря пакетов и повышение нагрузки на сетевое оборудование. STP решает эту проблему путем определения и блокировки лишних путей.
STP работает на канальном уровне OSI-модели и использует алгоритм вычисления корневого моста, который выбирает коммутатор с наименьшим идентификатором в качестве корневого моста. Затем протокол определяет кратчайший путь от корневого моста до каждого коммутатора в сети и блокирует все остальные пути.
STP имеет несколько важных параметров, таких как протокол STP (802.1D), MAC-адрес корневого моста, стоимость пути и приоритет порта. Они используются для определения конфигурации STP на устройствах.
Примечание: STP является основным протоколом для обеспечения безопасной и надежной работы сетей Ethernet.
Принцип работы протокола STP
Протокол STP работает следующим образом:
- В начале работы каждый коммутатор выбирает один из портов в режиме корневого порта, который будет служить корневым коммутатором для топологии сети.
- Каждый коммутатор обменивается сообщениями BPDU (Bridge Protocol Data Unit), в которых содержится информация о его приоритете и пути к корневому коммутатору.
- После обмена BPDU, каждый коммутатор выбирает один из портов в режиме порта корневого коммутатора, который будет представлять собой наилучший путь к корневому коммутатору для данного коммутатора.
- Остальные порты на коммутаторах переводятся в состояние блокировки, что предотвращает создание петель в топологии.
- При обнаружении изменений в топологии сети, протокол STP автоматически адаптирует свою конфигурацию, перераспределяя роли портов и переводя их в активное состояние.
Таким образом, протокол STP позволяет создать резервный путь в сети, который автоматически активируется в случае отказа основного пути. Это обеспечивает высокую отказоустойчивость и надежность работы сети Ethernet.
Роли и состояния портов в STP
В STP существуют различные роли и состояния портов, которые определяют, какой порт будет использоваться для передачи данных.
Роли портов:
Root port (RP): Это порт, через который данные будут передаваться от моста-корня (root bridge) к другим мостам в сети. Каждый мост имеет только один root port, и он выбирается на основе стоимости пути от моста до root bridge. Root port должен быть в состоянии «forwarding» (проходящий).
Designated port (DP): Это порт, через который мост будет передавать данные на root port. Каждый сегмент сети Ethernet, включая каждый мост, должен иметь только один designated port, через который данные будут пересылаться на root bridge. Designated port должен быть в состоянии «forwarding».
Blocked port (BL): Это порт, который заблокирован STP и не будет использоваться для передачи данных. Заблокированный порт нужен для предотвращения петель в сети.
Состояния портов:
Blocking (BLK): Порт находится в состоянии блокировки, что означает, что он не может передавать данные. В это состояние порт переходит после запуска STP и до момента, когда завершится процесс определения root bridge и designated port.
Listening (LIS): Порт находится в состоянии прослушивания сети, что означает, что он прослушивает BPDU (Bridge Protocol Data Unit), передаваемые мостами в сети. В это состояние порт переходит после состояния блокировки и до состояния обучения.
Learning (LRN): В это состояние порт переходит после состояния прослушивания. Порт начинает изучать данные, проходящие через него, но не передает их.
Forwarding (FWD): Порт находится в состоянии проходящего трафика, и данные могут свободно передаваться через этот порт. Порт переходит в это состояние, когда он выбран в качестве root port или designated port.
Алгоритм выбора корневого моста в STP
В начале работы алгоритма каждый мост в сети выбирает себя в качестве корневого моста, считая свою приоритетность наивысшей. Далее, мосты начинают обмениваться BPDU (Bridge Protocol Data Units) — протоколами данных, содержащими информацию о приоритете, MAC-адресе, ID корневого моста и стоимости связи до него.
Каждый мост сравнивает полученные BPDU с фиксированными критериями: приоритетность, MAC-адрес и стоимость связи. Мост, у которого наименьшая сумма этих трех параметров, становится корневым мостом.
После выбора корневого моста каждый мост выполняет расчеты для определения стоимости связи до корневого моста через каждый из его портов. Это значение называется «путь к корневому мосту». Рассчитывается путь к корневому мосту для каждого моста в сети.
В процессе расчета мосты определяют, какие порты являются «портами к корневому мосту». Эти порты имеют наименьшую стоимость связи до корневого моста и являются физическими интерфейсами, через которые мосты в сети могут обмениваться данными. Остальные порты считаются «заблокированными» и временно не используются для передачи данных.
Таким образом, алгоритм выбора корневого моста в STP позволяет определить оптимальные пути между мостами, обеспечивая надежность и устойчивость сети.
Процесс обнаружения и блокирования петель в STP
Процесс обнаружения и блокирования петель выполняется путем выбора одного из коммутаторов в сети в качестве корневого моста (root bridge). Корневой мост является центральным элементом, от которого происходит расчет пути для каждого коммутатора в сети.
Каждый коммутатор в сети отправляет сообщения BPDU (Bridge Protocol Data Unit) на все порты. BPDU содержит информацию о коммутаторе, его позиции в дереве и стоимости пути до корневого моста. Когда коммутатор получает BPDU от соседнего коммутатора, он проверяет информацию в сообщении и принимает решение о том, какой порт будет корневым портом для данного коммутатора. Корневой порт является портом, на котором путь до корневого моста наименьший.
Остальные порты коммутатора могут быть либо назначены в качестве некорневых портов (designated ports), либо заблокированы. Некорневые порты – это порты, которые имеют наименьший путь до корневого моста среди портов коммутатора. Заблокированные порты не пропускают трафик и используются для предотвращения возникновения петель в сети.
Если в сети происходят изменения, связанные с добавлением или удалением коммутаторов или переподключением портов, STP проводит анализ и пересчитывает пути до корневого моста. Этот процесс называется сходимостью STP (STP convergence).
STP позволяет создавать резервные пути между коммутаторами, что повышает отказоустойчивость и обеспечивает более эффективное использование подключенных сетевых ресурсов.
Преимущества и недостатки использования STP на роутере
Протокол STP (Spanning Tree Protocol) предоставляет механизм для обнаружения и предотвращения циклических петель в сети. Роутеры, поддерживающие STP, могут активно контролировать и управлять связями между собой, что приводит к следующим преимуществам:
1. Предотвращение циклических петель: STP автоматически находит и блокирует порты, которые могут создать петлю в сети. Это позволяет избежать возникновения трафика, зацикленного внутри сети, что может привести к снижению производительности и отказам в работе.
2. Автоматическое восстановление: Если один из роутеров или связей в сети выходит из строя, STP автоматически перестраивает топологию сети, выбирая новый путь для доставки трафика. Это позволяет сети быстро адаптироваться к изменениям с учетом наличия запасных связей.
3. Балансировка нагрузки: STP может распределять трафик между несколькими связанными роутерами, обеспечивая более равномерную нагрузку и предотвращая перегрузку отдельных узлов сети.
Несмотря на эти преимущества, STP имеет и некоторые недостатки:
1. Отказоустойчивость ограничена: STP может восстановить топологию только в случае отказа одного из роутеров или связей. Если сеть страдает от более серьезных проблем, например, отключения питания или повреждения кабеля, STP может быть недостаточен для обеспечения непрерывной работы.
2. Замедление сети: Каждый раз, когда STP перестраивает топологию, возникает задержка в работе сети. В больших сетях или в случае частых изменений в топологии, это может привести к значительному замедлению передачи данных.
3. Сложность конфигурации: Настройка STP может быть сложной задачей, особенно в больших и сложных сетях. Для корректной работы протокола требуется правильно настроить параметры, такие как приоритеты портов, затухание и прочие, что требует специальных знаний и опыта.
Несмотря на некоторые недостатки, преимущества использования STP на роутере далеко перевешивают его ограничения и сложности конфигурации. Протокол STP стал важной составляющей современных сетей, где отказоустойчивость и эффективное управление трафиком имеют первостепенное значение.
Table Of Contents
Spanning Tree Protocol
Understanding Spanning Tree Protocol
STP Overview
Bridge Interoperability
Bridge Protocol Data Units
Election of the Spanning-Tree Root
Spanning-Tree Timers
Creating the Spanning-Tree Topology
Spanning-Tree Interface States
Blocking State
Listening State
Learning State
Forwarding State
Disabled State
Configuring STP Features
Default STP Configuration
Configuring STP Settings
STP Configuration Examples
Root Device Without VLANs
Non-Root Bridge Without VLANs
Root Device with VLANs
Non-Root Bridge with VLANs
Displaying Spanning-Tree Status
Spanning Tree Protocol
This document descibes Spanning Tree Protocol (STP) in a wireless environment.
Understanding Spanning Tree Protocol
This section describes how spanning-tree features work.
STP Overview
STP is a Layer 2 link management protocol that provides path redundancy while preventing loops in the network. For a Layer 2 network to function properly, only one active path can exist between any two stations. Spanning-tree operation is transparent to end stations, which cannot detect whether they are connected to a single LAN segment or to a LAN of multiple segments.
When you create fault-tolerant internetworks, you must have a loop-free path between all nodes in a network. The spanning-tree algorithm calculates the best loop-free path throughout a Layer 2 network. Infrastructure devices such as wireless bridges and switches send and receive spanning-tree frames, called bridge protocol data units (BPDUs), at regular intervals. The devices do not forward these frames but use them to construct a loop-free path.
Multiple active paths among end stations cause loops in the network. If a loop exists in the network, end stations might receive duplicate messages. Infrastructure devices might also learn end-station MAC addresses on multiple Layer 2 interfaces. These conditions result in an insecure network.
STP defines a tree with a root device and a loop-free path from the root to all infrastructure devices in the Layer 2 network.

Note In discussions about STP, the term root is used to describe two concepts: the bridge on the network that serves as a central point in the spanning tree is called the root device, and the port on each device that provides the most efficient path to the device is called the root port. These meanings are separate. A bridge whose role in radio network setting is root device does not necessarily become the root device in the spanning tree. In this chapter, the root device in the spanning tree is called the spanning-tree root.
STP forces redundant data paths into a standby (blocked) state. If a network segment in the spanning tree fails and a redundant path exists, the spanning-tree algorithm recalculates the spanning-tree topology and activates the standby path.
When two interfaces are part of a loop, the spanning-tree port priority and path cost settings determine which interface is put in the forwarding state and which is put in the blocking state. The port priority value represents the location of an interface in the network topology and how well it is located to pass traffic. The path cost value represents media speed.
The bridge supports both per-VLAN spanning tree (PVST) and a single 802.1q spanning tree without VLANs. The bridge cannot run 802.1s multiple spanning tree (MST) or 802.1d Common Spanning Tree, which map multiple VLANs into a one-instance spanning tree.
The bridge maintains a separate spanning-tree instance for each active VLAN configured on it. A bridge ID, consisting of the bridge priority and the MAC address, is associated with each instance. For each VLAN, the bridge with the lowest bridge ID becomes the spanning-tree root for that VLAN.
Bridge Interoperability
Cisco bridges are interoperable when STP is enabled and no VLANs are configured. This configuration is the only one possible, for the following reasons:
•When STP is disabled, the bridge acts as an access point and disallows association of non-root bridge.
•The bridge has a single instance of STP in non-VLAN configurations and multiple instances of STP in VLAN configurations.
•Incompatibilities between single and multiple instances of STP can cause inconsistent blocking of traffic when VLANs are configured. When the native VLAN is blocked, bridge flapping can occur.
Therefore, the best configuration for STP interoperability is to have the bridge STP feature enabled and VLANs not configured.

Note When Cisco bridges are configured as workgroup bridges, they can operate with STP disabled and allow for associations with access points. However, this configuration is not technically a bridge-to-bridge scenario.
Bridge Protocol Data Units
The stable, active spanning-tree topology of a network is determined by the following factors:
•The unique bridge ID (wireless bridge priority and MAC address) associated with each VLAN on each wireless bridge
•The spanning-tree path cost to the spanning-tree root
•The port identifier (port priority and MAC address) associated with each Layer 2 interface
When the bridges in a network are powered up, each bridge functions as the STP root. The bridges send configuration BPDUs through the Ethernet and radio ports. The BPDUs communicate and compute the spanning-tree topology. Each configuration BPDU contains this information:
•The unique bridge ID of the wireless bridge that the sending bridge identifies as the spanning-tree root
•The spanning-tree path cost to the root
•The bridge ID of the sending bridge
•Message age
•The identifier of the sending interface
•Values for the hello, forward delay, and max-age protocol timers
When a bridge receives a configuration BPDU that contains information superior (lower bridge ID, lower path cost, and so forth), it stores the information for that port. If this BPDU is received on the root port of the bridge, the bridge also forwards it with an updated message to all attached LANs for which it is the designated bridge.
If a bridge receives a configuration BPDU that contains inferior information to that currently stored for that port, it discards the BPDU. If the bridge is a designated bridge for the LAN from which the inferior BPDU was received, it sends that LAN a BPDU containing the up-to-date information stored for that port. In this way, inferior information is discarded, and superior information is propagated on the network.
A BPDU exchange results in these actions:
•One bridge is elected as the spanning-tree root.
•A root port is selected for each bridge (except the spanning-tree root). This port provides the best path (lowest cost) when the bridge forwards packets to the spanning-tree root.
•The shortest distance to the spanning-tree root is calculated for each bridge based on the path cost.
•A designated bridge for each LAN segment is selected. The designated bridge incurs the lowest path cost when forwarding packets from that LAN to the spanning-tree root. The port through which the designated bridge is attached to the LAN is called the designated port.
•Interfaces that are included in the spanning-tree instance are selected. Root ports and designated ports are put in the forwarding state.
•All interfaces that are not included in the spanning tree are blocked.
Election of the Spanning-Tree Root
All bridges in the Layer 2 network that are participating in STP gather information about other bridges in the network by exchanging BPDU data messages. This message exchange results in these actions:
•The election of a unique spanning-tree root for each spanning-tree instance
•The election of a designated bridge for every LAN segment
•The removal of loops in the network by blocking Layer 2 interfaces connected to redundant links
For each VLAN, the bridge with the highest bridge priority (the lowest numerical priority value) is elected as the spanning-tree root. If all bridges are configured with the default priority (32768), the bridge with the lowest MAC address in the VLAN becomes the spanning-tree root. The bridge priority value occupies the most significant bits of the bridge ID.
When you change the bridge priority value, you change the probability that the bridge will be elected as the root device. Configuring a higher value decreases the probability; a lower value increases the probability.
The spanning-tree root is the logical center of the spanning-tree topology. Paths that are not needed to reach the spanning-tree root from anywhere in the network are placed in the spanning-tree blocking mode.
BPDUs contain information about the sending bridge and its ports, including bridge and MAC addresses, bridge priority, port priority, and path cost. STP uses this information to elect the spanning-tree root and root port for the network and the root port and designated port for each LAN segment.
Spanning-Tree Timers
Table 1 describes the timers that affect the entire spanning-tree performance.
|
Variable |
Description |
|---|---|
|
Hello timer |
Determines how often the bridge broadcasts hello messages to other bridges. |
|
Forward-delay timer |
Determines how long each of the listening and learning states last before the interface begins forwarding. |
|
Maximum-age timer |
Determines the amount of time the bridge stores protocol information received on an interface. |
Creating the Spanning-Tree Topology
In Figure 1, bridge 4 is elected as the spanning-tree root, under the assumption that the priority of all the bridges is set to the default (32768) and bridge 4 has the lowest MAC address. However, because of traffic patterns, number of forwarding interfaces, or link types, bridge 4 might not be the ideal spanning-tree root. By increasing the priority (lowering the numerical value) of the ideal bridge so that it becomes the spanning-tree root, you force a spanning-tree recalculation to form a new topology with the ideal bridge as the spanning-tree root.
Figure 1 Spanning-Tree Topology

Spanning-Tree Interface States
Propagation delays can occur when protocol information passes through a wireless LAN. As a result, topology changes can take place at different times and at different places in the network. When an interface transitions directly from nonparticipation in the spanning-tree topology to the forwarding state, it can create temporary data loops. Interfaces must wait for new topology information to propagate through the LAN before starting to forward frames. They must allow the frame lifetime to expire for forwarded frames that have used the old topology.
Each interface on a bridge using spanning tree exists in one of these states:
•Blocking—The interface does not participate in frame forwarding.
•Listening—The first transitional state after the blocking state, in which the spanning tree determines that the interface should participate in frame forwarding.
•Learning—The interface prepares to participate in frame forwarding.
•Forwarding—The interface forwards frames.
•Disabled—The interface is not participating in spanning tree because there is a port shutdown, there is no link on the port, or no spanning-tree instance is running on the port.
An interface moves through these states:
•From initialization to blocking
•From blocking to listening or to disabled
•From listening to learning or to disabled
•From learning to forwarding or to disabled
•From forwarding to disabled
Figure 2 illustrates how an interface moves through the states.
Figure 2 Spanning-Tree Interface States

When you enable STP on the bridge, the Ethernet and radio interfaces go through the blocking state and the transitory states of listening and learning. STP stabilizes each interface at the forwarding or blocking state.
When the spanning-tree algorithm places a Layer 2 interface in the forwarding state, this process occurs:
1. The interface is in the listening state while STP waits for protocol information to transition the interface to the blocking state.
2. While STP waits the forward-delay timer to expire, it moves the interface to the learning state and resets the forward-delay timer.
3. In the learning state, the interface continues to block frame forwarding as the bridge learns end-station location information for the forwarding database.
4. When the forward-delay timer expires, STP moves the interface to the forwarding state, where both learning and frame forwarding are enabled.
Blocking State
An interface in the blocking state does not participate in frame forwarding. After initialization, a BPDU is sent to the bridge’s Ethernet and radio ports. A bridge initially functions as the spanning-tree root until it exchanges BPDUs with other bridges. This exchange establishes which bridge in the network is the spanning-tree root. If there is only one bridge in the network, no exchange occurs, the forward-delay timer expires, and the interfaces move to the listening state. An interface always enters the blocking state when you enable STP.
An interface in the blocking state performs as follows:
•Discards frames received on the port
•Does not learn addresses
•Receives BPDUs

Note If a port is blocked, some broadcast or multicast packets can reach a forwarding port on the bridge and cause the bridging logic to switch the blocked port into listening state momentarily before the packets are dropped at the blocked port.
Listening State
The listening state is the first state an interface enters after the blocking state. The interface enters this state when STP determines that the interface should participate in frame forwarding.
An interface in the listening state performs as follows:
•Discards frames received on the port
•Does not learn addresses
•Receives BPDUs
Learning State
An interface in the learning state prepares to participate in frame forwarding. The interface enters the learning state from the listening state.
An interface in the learning state performs as follows:
•Discards frames received on the port
•Learns addresses
•Receives BPDUs
Forwarding State
An interface in the forwarding state forwards frames. The interface enters the forwarding state from the learning state.
An interface in the forwarding state performs as follows:
•Receives and forwards frames received on the port
•Learns addresses
•Receives BPDUs
Disabled State
An interface in the disabled state does not participate in frame forwarding or in the spanning tree. An interface in the disabled state is nonoperational.
A disabled interface performs as follows:
•Discards frames received on the port
•Does not learn addresses
•Does not receive BPDUs
Configuring STP Features
You complete three major steps to configure STP on the WMIC:
1. If necessary, assign interfaces and subinterfaces to bridge groups
2. Enable STP for each bridge group
3. Set the STP priority for each bridge group
These sections provide information on STP configuration:
•Default STP Configuration
•Configuring STP Settings
•STP Configuration Examples
Default STP Configuration
STP is disabled by default. Table 2 lists the default STP settings when you enable STP.
|
Setting |
Default Value |
|---|---|
|
bridge priority |
32768 |
|
bridge max age |
20 |
|
bridge hello time |
2 |
|
bridge forward delay |
15 |
|
Ethernet port path cost |
19 |
|
Ethernet port priority |
128 |
|
radio port path cost |
33 |
|
radio port priority |
128 |
The radio and Ethernet interfaces and the native VLAN on the bridge are assigned to bridge group 1 by default. When you enable STP and assign a priority on bridge group 1, STP is enabled on the radio and Ethernet interfaces and on the primary VLAN, and those interfaces adopt the priority assigned to bridge group 1. You can create bridge groups for subinterfaces and assign different STP settings to those bridge groups.
Configuring STP Settings
To configure STP on the WMIC, follow these steps, beginning in privileged EXEC mode:
|
Command |
Purpose |
|
|---|---|---|
|
Step 1 |
configure terminal |
Enters global configuration mode. |
|
Step 2 |
interface {dot11radio port | fastethernet port } |
Enters interface configuration mode for radio or Ethernet interfaces or subinterfaces. |
|
Step 3 |
bridge-group number |
Assigns the interface to a bridge group. You can number your bridge groups from 1 to 255. |
|
Step 4 |
no bridge-group number spanning-disabled |
Counteracts the command that automatically disables STP for a bridge group. (STP is later enabled on the interface when you enter the bridge n protocol ieee command.) |
|
Step 5 |
exit |
Returns to global configuration mode. |
|
Step 6 |
bridge number protocol ieee |
Enables STP for the bridge group. You must enable STP on each bridge group that you create with bridge-group commands. |
|
Step 7 |
bridge number priority priority |
(Optional) Assigns a priority to a bridge group. The lower the priority, the more likely it is that the bridge becomes the spanning-tree root. |
|
Step 8 |
end |
Returns to privileged EXEC mode. |
|
Step 9 |
show spanning-tree bridge |
Verifies your entries. |
|
Step 10 |
copy running-config startup-config |
(Optional) Saves your entries in the configuration file. |
STP Configuration Examples
These configuration examples show how to enable STP on root and non-root bridges with and without VLANs:
•Root Device Without VLANs
•Non-Root Bridge Without VLANs
•Root Device with VLANs
•Non-Root Bridge with VLANs
Root Device Without VLANs
This example shows the configuration of a root device with no VLANs configured and with STP enabled:
hostname master-bridge-south
speed basic-6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0
ip address 1.4.64.23 255.255.0.0
ip default-gateway 1.4.0.1
Non-Root Bridge Without VLANs
This example shows the configuration of a non-root bridge with STP enabled and no VLANs configured:
hostname client-bridge-north
speed basic-6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0
bridge-group 1 path-cost 40
ip address 1.4.64.24 255.255.0.0
Root Device with VLANs
This example shows the configuration of a root device with VLANs configured with STP enabled:
hostname master-bridge-hq
ip ssh authentication-retries 3
speed basic-6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0
encapsulation dot1Q 1 native
bridge-group 3 path-cost 500
interface FastEthernet0.1
encapsulation dot1Q 1 native
interface FastEthernet0.2
interface FastEthernet0.3
ip address 1.4.64.23 255.255.0.0
ip default-gateway 1.4.0.1
Non-Root Bridge with VLANs
This example shows the configuration of a non-root bridge with VLANs configured with STP enabled:
hostname client-bridge-remote
ip ssh authentication-retries 3
speed basic-6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0
encapsulation dot1Q 1 native
interface FastEthernet0.1
encapsulation dot1Q 1 native
interface FastEthernet0.2
interface FastEthernet0.3
bridge-group 3 path-cost 400
ip address 1.4.64.24 255.255.0.0
Displaying Spanning-Tree Status
To display the spanning-tree status, use one or more of the commands in Table 3 in privileged EXEC mode:
|
Command |
Purpose |
|---|---|
|
show spanning-tree |
Displays information on your network’s spanning tree. |
|
show spanning-tree blocked-ports |
Displays a list of blocked ports on this device. |
|
show spanning-tree bridge |
Displays status and configuration of this bridge. |
|
show spanning-tree active |
Displays spanning-tree information on active interfaces only. |
|
show spanning-tree root |
Displays a detailed summary of information on the spanning-tree root. |
|
show spanning-tree interface interface-id |
Displays spanning-tree information for the specified interface. |
|
show spanning-tree summary [totals] |
Displays a summary of port states or displays the total lines of the STP state section. |
For information about other keywords for the show spanning-tree privileged EXEC command, refer to the Cisco IOS Command Reference for Cisco Access Points and Bridges.
Summary
The purpose of spanning tree protocol is to provide the ability to create loop-free Layer 2 topologies while having redundant links. While connecting multiple bridges or just cross-connecting bridge ports, it’s possible to create network loops that can severely impact the stability of the network. Spanning tree protocol aims to resolve this problem by introducing the concept of the root bridge, all bridges in the same Layer 2 domain will exchange information about the shortest path to the root bridge. Afterward, each bridge will negotiate which ports to use to reach the root bridge. This information exchange is done with the help of Bridge Protocol Data Units (BPDUs). STP will disable certain ports for each bridge in order to avoid loops, while still ensuring that all bridges can communicate with each other. For an in-depth description of protocol please refer to IEEE 802.1D.
As a best practice, it is always recommended to manually set up each bridge’s priority, port priority, and port path cost to ensure proper Layer2 functionality at all times. Leaving STP related values to defaults are acceptable for a network that consists of 1 to 2 bridges running with (R/M)STP enabled, but it is highly recommended to manually set these values for larger networks. Since STP elects a root bridge and root ports by checking STP related values from bridges over the network, then leaving STP settings to automatic may elect an undesired root bridge and root ports and in case of a hardware failure can result in an inaccessible network.
Monitoring
You can check the STP status of a bridge by using the /interface bridge monitor command, for example:
/interface bridge monitor bridge
state: enabled
current-mac-address: 64:D1:54:D9:27:E6
root-bridge: yes
root-bridge-id: 0x3000.64:D1:54:D9:27:E6
root-path-cost: 0
root-port: none
port-count: 5
designated-port-count: 5
Note that the root bridge doesn’t have any root ports, only designated ports.
You can check the STP status of a bridge port by using the /interface bridge port monitor command, for example:
/interface bridge port monitor 2
interface: ether3
status: in-bridge
port-number: 3
role: root-port
edge-port: no
edge-port-discovery: yes
point-to-point-port: yes
external-fdb: no
sending-rstp: yes
learning: yes
forwarding: yes
root-path-cost: 10
designated-bridge: 0x3000.64:D1:54:D9:27:E6
designated-cost: 0
designated-port-number: 4
hw-offload-group: switch1
Note that root-bridge-id consists of the bridge priority and the bridge’s MAC address, for non-root bridges the root bridge will be shown as designated-bridge. One port can have one role in an STP enabled network, below is a list of possible port roles:
- root-port — port that is facing towards the root bridge and will be used to forward traffic from/to the root bridge.
- alternate-port — port that is facing towards root bridge, but is not going to forward traffic (a backup for root port).
- backup-port — port that is facing away from the root bridge, but is not going to forward traffic (a backup for non-root port).
- designated-port — port that is facing away from the root bridge and is going to forward traffic.
- disabled-port — disabled or inactive port.
When using bridges that are set to use 802.1Q as EtherType, they will send out BPDUs to 01:80:C2:00:00:00, which are used by MSTP, RSTP, and STP. When using 802.1ad as bridge VLAN protocol, the BPDUs are not compatible with 802.1Q bridges and they are sent to 01:80:C2:00:00:08. (R/M)STP will not function properly if there are different bridge VLAN protocols across the Layer2 network.
STP and RSTP
STP and Rapid STP are used widely across many networks, but almost all networks have switched over using only RSTP since of its benefits. STP is a very old protocol and has a convergence time (the time needed to fully learn network topology changes and to continue properly forwarding traffic) of up to 50 seconds. RSTP has a lot of smaller convergence time, a few seconds or even a few milliseconds. It is recommended to use RSTP instead of STP since it is a lot faster and is also backward compatible with STP. One of the reasons why RSTP is faster is because of reduced possible port states, below is a list of possible STP port states:
- Forwarding — port participates in traffic forwarding and is learning MAC addresses, is receiving BPDUs.
- Listening — port does not participate in traffic forwarding and is not learning MAC addresses, is receiving BPDUs.
- Learning — port does not participate in traffic forwarding but is learning MAC addresses.
- Blocking — port is blocked since it is causing loops but is receiving BPDUs.
- Disabled — port is disabled or inactive.
In RSTP the disabled, listening and blocking port states are replaced with just one state called the Discarding state:
- Forwarding — port participates in traffic forwarding and is learning MAC addresses, is receiving BPDUs (forwarding=yes).
- Learning — port does not participate in traffic forwarding but is learning MAC addresses (learning=yes).
- Discarding — port does not participate in traffic forwarding and is not learning MAC addresses, is receiving BPDUs (forwarding=no).
In STP connectivity between bridges is determined by sending and receiving BPDUs between neighbor bridges. Designated ports are sending BPDUs to root ports. If a BPDU is not received 3 times the HelloTime in a row, then the connection is considered as unavailable and network topology convergence will commence. It is possible for STP to reduce the convergence time in certain scenarios by reducing the forward-delay timer, which is responsible for how long can the port be in the learning/listening state.
In RouterOS, it is possible to specify which bridge ports are edge ports. Edge ports are ports that are not supposed to receive any BPDUs, this is beneficial since this allows STP to skip the learning and the listening state and directly go to the forwarding state. This feature is sometimes called PortFast· You can leave this parameter to the default value, which is auto, but you can also manually specify it, you can set a port as edge port manually for ports that should not have any more bridges behind it, usually these are access ports.
Additionally, bridge port point-to-point , specifies if a bridge port is connected to a bridge using a point-to-point link for faster convergence in case of failure. By setting this property to yes, you are forcing the link to be a point-to-point link, which will skip the checking mechanism, which detects and waits for BPDUs from other devices from this single link, by setting this property to no, you are implying that a link can receive BPDUs from multiple devices. By setting the property to yes, you are significantly improving (R/M)STP convergence time. In general, you should only set this property to no , if it is possible that another device can be connected between a link, this is mostly relevant to Wireless mediums and Ethernet hubs. If the Ethernet link is full-duplex, auto enables point-to-point functionality. This property has no effect when protocol-mode is set to none.
Default values
When creating a bridge or adding a port to the bridge the following are the default values that are assigned by RouterOS:
- Default bridge priority: 32768 / 0x8000
- Default bridge port path cost: 10
- Default bridge port priority: 0x80
- BPDU message age increment: 1
- HelloTime: 2
- Default max message age: 20
RouterOS does not change port path cost based on the link speed, for 10M, 100M, 1000M, and 10000M link speeds the default path cost value when a port is added to a bridge are always 10. The age of a BPDU is determined by how many bridges have the BPDU passed times the message age since RouterOS uses 1 as the message age increment, then the BPDU packet can pass as many bridges as specified in the max-message-age parameter. By default this value is set to 20, this means that after the 20th bridge the BPDU packet will be discarded and the next bridge will become a root bridge, note that if max-message-age=20on is set, then it is hard to predict which ports will be the designated port on the 21st bridge and may result in traffic not being able to be forwarded properly.
In case bridge filter rules are used, make sure you allow packets with DST-MAC address 01:80:C2:00:00:00 since these packets carry BPDUs that are crucial for STP to work properly.
Election process
To properly configure STP in your network you need to understand the election process and which parameters are involved in which order. In RouterOS the root bridge will be elected based on the smallest priority and the smallest MAC address in this particular order:
- Bridge priority (lowest)
- Bridge MAC address (lowest)
In RouterOS root ports are elected based on lowest Root port path cost, lowest bridge identifier, and lowest bridge port ID in this particular order:
- Root port path cost (lowest)
- Bridge identifier (lowest)
- Bridge port ID (lowest)
First, when the device considers which of its ports to elect as the root port, it will check the root path cost seen by its ports. If root path cost is the same for two or more ports then the Bridge identifier of the upstream device will be checked and port connected to the lowest bridge identifier will become the root port. If the same bridge identifier is seen on two or more ports, then the Bridge port ID of the upstream device will be checked.
Explanation of attributes:
Root path cost, all bridges have a Root Path Cost. Root bridge has a root path cost of 0. For all other Bridges, it is the sum of the Port Path Costs on the least-cost path to the Root Bridge. You can modify local port path cost under «/interface bridge port».
Bridge identifier is a combination of «bridge priority» and «bridge MAC», configurable under «/interface bridge»
Bridge port ID is a combination of «unique ID» and «bridge port priority», the unique ID is automatically assigned to bridge port upon adding it to the bridge, it cannot be edited. It can be seen in WinBox under «Bridge Port» «Port Number» column, or with «/interface bridge port monitor», as «port-number».
Make sure you are using path cost and priority on the right ports. For example, setting path cost on ports that are in a root bridge has no effect, only port priority has an effect on them. Root path cost has an effect on ports that are facing towards the root bridge and port priority has an effect on ports that are facing away from the root bridge. And bridge identifier doesn’t impact the device’s own root port election, instead, it affects the root port election for downstream devices.
In RouterOS it is possible to set any value for bridge priority between 0 and 65535, the IEEE 802.1W standard states that the bridge priority must be in steps of 4096. This can cause incompatibility issues between devices that do not support such values. To avoid incompatibility issues, it is recommended to use only these priorities: 0, 4096, 8192, 12288, 16384, 20480, 24576, 28672, 32768, 36864, 40960, 45056, 49152, 53248, 57344, 61440.
Examples
Root path cost example
This example outlines how the root path cost works. SW1 will be the root bridge, due to it having the lowest priority of 0x1000, as the root bridge. Each bridge will calculate the path cost to the root bridge. When calculating root path cost bridges take into account configured path cost on their ports + root path cost advertised by neighboring bridges.
SW1: due to it being the root bridge, it advertises root path cost of 0 to its neighbors, even though it has a configured path cost of 10.
SW2: ether1. has root path cost of 0 + 25=25. On the ether2 path cost will be 10+10+10+0=30
SW3: ether2, has root path cost of 0 + 10=10. On the ether4 path cost will be 10+5+25+0=40
SW4: ether1, has root path cost of 0+25+5=30. On ether4 path cost will be 10+10+0=20
Port with the lowest path cost will be elected as the root port. Every bridge in STP topology needs a path to root bridge, after the best path has been found, the redundant path will be blocked, in this case, path between SW2 and SW4.
You can configure path cost on the root bridge, but it will only be taken into account when the bridge loses its root status.
STP example
In this example, we want to ensure Layer2 redundancy for connections from ServerA to ServerB. If a port is connected to a device that is not a bridge and not running (R)STP, then this port is considered as an edge port, in this case ServerA and ServerB is connected to an edge port. This is possible by using STP in a network. Below are configuration examples for each switch.
- Configuration for SW1:
/interface bridge add name=bridge priority=0x1000 /interface bridge port add bridge=bridge interface=ether1 priority=0x60 add bridge=bridge interface=ether2 priority=0x50 add bridge=bridge interface=ether3 priority=0x40 add bridge=bridge interface=ether4 priority=0x30 add bridge=bridge interface=ether5
- Configuration for SW2:
/interface bridge add name=bridge priority=0x2000 /interface bridge port add bridge=bridge interface=ether1 add bridge=bridge interface=ether2 add bridge=bridge interface=ether3
- Configuration for SW3:
/interface bridge add name=bridge priority=0x3000 /interface bridge port add bridge=bridge interface=ether1 add bridge=bridge interface=ether2 add bridge=bridge interface=ether3
- Configuration for SW4:
/interface bridge add name=bridge priority=0x4000 /interface bridge port add bridge=bridge interface=ether1 add bridge=bridge interface=ether2 path-cost=20 add bridge=bridge interface=ether3
In this example, SW1 is the root bridge since it has the lowest bridge priority. SW2 and SW3 have ether1,ether2 connected to the root bridge and ether3 is connected to SW4. When all switches are working properly, the traffic will be flowing from ServerA through SW1_ether2, through SW2, through SW4 to ServerB. In the case of SW1 failure, the SW2 becomes the root bridge because of the next lowest priority, indicated by the dotted line in the diagram. Below is a list of ports and their role for each switch:
- root-port — SW2_ether2, SW3_ether2, SW4_ether1
- alternate-port — SW2_ether1, SW3_ether1, SW4_ether2
- designated-port — SW1_ether1, SW1_ether2, SW1_ether3, SW1_ether4, SW1_ether5, SW2_ether3, SW2_ether3, SW4_ether3
Note: By the 802.1Q recommendations, you should use bridge priorities in steps of 4096. To set a recommended priority it is more convenient to use hexadecimal notation, for example, 0 is 0x0000, 4096 is 0x1000, 8192 is 0x2000 and so on (0..F).
Multiple Spanning Tree Protocol
Multiple Spanning Tree Protocol (MSTP) is used on a bridge interface to ensure loop-free topology across multiple VLANs, MSTP can also provide Layer2 redundancy and can be used as a load balancing technique for VLANs since it has the ability to have different paths across different VLANs. MSTP is operating very similarly to (R)STP and many concepts from (R)STP can be applied to MSTP and it is highly recommended to understand the principles behind (R)STP before using MSTP, but there are some differences that must be taken into account when designing an MSTP enabled network.
In case (R)STP is used, the BPDUs are sent across all physical interfaces in a bridge to determine loops and stop ports from being able to forward traffic if it causes a loop. In case there is a loop inside a certain VLAN, (R)STP might not be able to detect it. Some STP variants solve this problem by running an STP instance on every single VLAN (PVST), but this has been proven to be inefficient and some STP variants solve this problem by running a single STP instance across all VLANs (CST), but it lacks the possibility to do load balancing for each VLAN or VLAN group. MSTP tends to solve both problems by using MST instances that can define a group of VLANs (VLAN mapping) that can be used for load balancing and redundancy, this means that each VLAN group can have a different root bridge and a different path. Note that it is beneficial to group multiple VLANs in a single instance to reduce the amount of CPU cycles for each network topology change.
In RouterOS with MSTP enabled the bridge priority is the CIST’s root bridge priority, as stated in the IEEE 802.1Q standard the bridge priority must be in steps of 4096, the 12 lowest bits are ignored. These are valid bridge priorities: 0, 4096, 8192, 12288, 16384, 20480, 24576, 28672, 32768, 36864, 40960, 45056, 49152, 53248, 57344, 61440. When setting an invalid bridge priority, RouterOS will warn you about it and trunk the value to a valid value, but will save the original value in the configuration since invalid bridge priority values can still be used in (R)STP between devices running RouterOS, though it is recommended to use valid a bridge priority instead.
MSTP Regions
MSTP works in groups called regions, for each region there will be a regional root bridge and between regions, there will be a root bridge elected. MSTP will use Internal Spanning Tree (IST) to build the network topology inside a region and Common Spanning Tree (CST) outside a region to build the network topology between multiple regions, MSTP combines these two protocols into Common and Internal Spanning Tree (CIST), which holds information about topology inside a region and between regions. From CST’s perspective, a region will seemingly be as a single virtual bridge, because of this MSTP is considered very scalable for large networks. In order for bridges to be in the same region, their configuration must match, BPDUs will not include VLAN mappings since they can be large, rather a computed hash is being transmitted. If a bridge receives a BPDU through a port and the configuration does not match, then MSTP will consider that port as a boundary port and that it can be used to reach other regions. Below is a list of parameters that need to match in order for MSTP to consider a BPDU from the same region:
- Region name
- Region revision
- VLAN mappings to MST Instance IDs (computed hash)
It is possible to create MSTP enabled network without regions, though to be able to do load balancing per VLAN group it is required for a bridge to receive a BPDU from a bridge that is connected to it with the same parameters mentioned above. In RouterOS the default region name is empty and region revision is 0, which are valid values, but you must make sure that they match in order to get multiple bridges in a single MSTP region. A region cannot exist if their bridges are scattered over the network, these bridges must be connected at least in one way, in which they can send and receive BPDUs without leaving the region, for example, if a bridge with different region related parameters is between two bridges that have the same region related parameters, then there will exist at least 3 different MSTP regions.
The downside of running every single bridge in a single MSTP region is the excess CPU cycles. In comparison, PVST(+) creates a Spanning Tree Instance for each VLAN ID that exists on the network, since there will be very limited paths that can exist in a network, then this approach creates a lot of overhead and unnecessary CPU cycles, this also means that this approach does not scale very well and can overload switches with not very powerful CPUs. MSTP solves this problem by dividing the network into MSTP regions, where each bridge inside this region will exchange and process information about VLANs that exist inside the same region, but will run a single instance of Spanning Tree Protocol in the background to maintain the network topology between regions. This approach has been proven to be much more effective and much more scalable, this means that regions should be used for larger networks to reduce CPU cycles.
In regions, you can define MST Instances, which are used to configure load balancing per VLAN group and to elect the regional root bridge. It is worth mentioning that in each region there exists a pre-defined MST Instance, in most documentations, this is called as MSTI0· This MST Instance is considered as the default MST Instance, there are certain parameters that apply to this special MST Instance. When traffic is passing through an MSTP enabled bridge, MSTP will look for an MST Instance that has a matching VLAN mapping, but if a VLAN mapping does not exist for a certain VLAN ID, then traffic will fall under MSTI0.
Since MSTP requires VLAN filtering on the bridge interface to be enabled, then make sure that you have allowed all required VLAN IDs in /interface bridge vlan, otherwise, the traffic will not be forwarded and it might seem as MSTP misconfigured, although this is a VLAN filtering misconfiguration.
Election process
The election process in MSTP can be divided into two sections, intra-region and inter-region. For MSTP to work properly there will always need to be a regional root, that is the root bridge inside a region, and a CIST root, that is the root bridge between regions. A regional root is the root bridge inside a region, regional root bridge will be needed to properly set up load balancing for VLAN groups inside a region. CIST root will be used to configure which ports will be alternate/backups ports (inactive) and which ports will be root ports (active).
Between regions, there is no load balancing per VLAN group, root port election process and port blocking between MSTP regions is done the same way as in (R)STP. If CIST has blocked a port that is inside an MSTP region to prevent traffic loops between MSTP regions, then this port can still be active for IST to do load balancing per VLAN group inside an MSTP region.
- The following parameters are involved to elect a regional root bridge or root ports inside a MSTP region:
| Property | Description |
|---|---|
| priority (integer: 0..65535 decimal format or 0x0000-0xffff hex format; Default: 32768 / 0x8000) | /interface bridge msti, MST Instance priority, used to elect a regional root inside a MSTP region. |
| internal-path-cost (integer: 1..4294967295; Default: 10) | /interface bridge port, path cost to the regional root for unknown VLAN IDs (MSTI0), used on a root port inside a MSTP region. |
| priority (integer: 0..240; Default: 128) | /interface bridge port mst-override, MST port priority for a defined MST Instance, used on a bridge port on the regional root bridge. |
| internal-path-cost (integer: 1..200000000; Default: 10) | /interface bridge port mst-override, MST port path cost for a defined MST Instance, used on a non-root bridge port inside a MSTP region. |
- The following parameters are involved to elect a CIST root bridge or CIST root ports:
| Property | Description |
|---|---|
| priority (integer: 0..65535 decimal format or 0x0000-0xffff hex format; Default: 32768 / 0x8000) | /interface bridge, CIST bridge priority, used to elect a CIST root bridge. |
| priority (integer: 0..240; Default: 128) | /interface bridge port, CIST port priority, used on a CIST root bridge to elect CIST root ports. |
| path-cost (integer: 1..4294967295; Default: 10) | /interface bridge port, CIST port path cost, used on a CIST non-root bridge port to elect CIST root ports. |
The sequence of parameters in which MSTP checks to elect root bridge/ports are the same as in (R)STP, you can read more about it at the (R)STP Election Process section.
MST Instance
Sub-menu: /interface bridge msti
This section is used to group multiple VLAN IDs to a single instance to create a different root bridge for each VLAN group inside an MSTP region.
| Property | Description |
|---|---|
| bridge (text; Default: ) | Bridge to which assign an MST instance. |
| identifier (integer: 1..31; Default: ) | MST instance identifier. |
| priority (integer: 0..65535 decimal format or 0x0000-0xffff hex format; Default: 32768 / 0x8000) | MST instance priority, used to determine the root bridge for a group of VLANs in an MSTP region. |
| vlan-mapping (integer: 1..4094; Default: ) | The list of VLAN IDs to assign to MST instance. This setting accepts the VLAN ID range, as well as comma, separated values. E.g. vlan-mapping=100-115,120,122,128-130 |
MST Override
Sub-menu: /interface bridge port mst-override
This section is used to select the desired path for each VLAN mapping inside an MSTP region.
| Property | Description |
|---|---|
| disabled (yes | no; Default: no) | Whether entry is disabled. |
| internal-path-cost (integer: 1..200000000; Default: 10) | Path cost for an MST instance’s VLAN mapping, used on VLANs that are facing towards the root bridge to manipulate path selection, lower path cost is preferred. |
| identifier (integer: 1..31; Default: ) | MST instance identifier. |
| priority (integer: 0..240; Default: 128) | The priority an MST instance’s VLAN, used on VLANs that are facing away from the root bridge to manipulate path selection, lower priority is preferred. |
| interface (name; Default: ) | Name of the port on which use configured MST instance’s VLAN mappings and defined path cost and priority. |
Monitoring
Similarly to (R)STP, it is also possible to monitor MSTP status. By monitoring the bridge interface itself it possible to see the current CIST root bridge and the current regional root bridge for MSTI0, it is also possible to see the computed hash of MST Instance identifiers and VLAN mappings, this is useful when making sure that certain bridges are in the same MSTP region. Below you can find an example to monitoring an MSTP bridge:
/interface bridge monitor bridge
state: enabled
current-mac-address: 6C:3B:6B:7B:F0:AA
root-bridge: no
root-bridge-id: 0x1000.64:D1:54:24:23:72
regional-root-bridge-id: 0x4000.6C:3B:6B:7B:F0:AA
root-path-cost: 10
root-port: ether4
port-count: 5
designated-port-count: 3
mst-config-digest: 74edbeefdbf82cf63a70cf60e43a56f3
In MSTP it is possible to monitor the MST Instance, this is useful to determine the current regional root bridge for a certain MST Instance and VLAN group, below you can find an example to monitor an MST Instance:
/interface bridge msti monitor 1
state: enabled
identifier: 2
current-mac-address: 6C:3B:6B:7B:F0:AA
root-bridge: no
root-bridge-id: 0.00:00:00:00:00:00
regional-root-bridge-id: 0x1002.6C:3B:6B:7B:F9:08
root-path-cost: 0
root-port: ether2
port-count: 5
designated-port-count: 1
It is also possible to monitor a certain MST Override entry, this is useful to determine the port role for a certain MST Instance when configuring root ports and alternate/backup ports in an MSTP region, below you can find an example to monitor an MST Override entry:
/interface bridge port mst-override monitor 1
port: ether3
status: active
identifier: 2
role: alternate-port
learning: no
forwarding: no
internal-root-path-cost: 15
designated-bridge: 0x1002.6C:3B:6B:7B:F9:08
designated-internal-cost: 0
designated-port-number: 130
MSTP example
Let’s say that we need to design topology and configure MSTP in a way that VLAN 10,20 will be forwarded in one path, but VLAN 30,40 will be forwarded in a different path, while all other VLAN IDs will be forwarded in one of those paths. This can easily be done by setting up MST Instances and assigning port path costs, below you can find a network topology that needs to do load balancing per VLAN group with 3 separate regions as an example:

Start by adding each interface to a bridge, initially, you should create a (R)STP bridge without VLAN filtering enabled, this is to prevent losing access to the CPU. Each device in this example is named by the region that it is in (Rx) and a device number (_x). For larger networks configuring MSTP can be confusing because of the number of links and devices, we recommend using The Dude to monitor and design a network topology.
- Use the following commands on R1_1, R1_3, R2_1, R2_3, R3_1, R3_3:
/interface bridge add name=bridge protocol-mode=rstp vlan-filtering=no /interface bridge port add bridge=bridge interface=ether1 add bridge=bridge interface=ether2 add bridge=bridge interface=ether3 add bridge=bridge interface=ether4
- Use the following commands on R1_2, R2_2, R3_2:
/interface bridge add name=bridge protocol-mode=rstp vlan-filtering=no /interface bridge port add bridge=bridge interface=ether1 add bridge=bridge interface=ether2
- Make sure you allow the required VLAN IDs on these devices, here we will consider that each device will receive tagged traffic that needs to be load balanced per VLAN group, use these commands on R1_1, R1_3, R2_1, R2_3, R3_1, R3_3:
/interface bridge vlan add bridge=bridge tagged=ether1,ether2,ether3,ether4 vlan-ids=10,20,30,40
- Use the following commands on R1_2, R2_2, R3_2:
/interface bridge vlan add bridge=bridge tagged=ether1,ether2 vlan-ids=10,20,30,40
Make sure you add all the needed VLAN IDs and ports to the bridge VLAN table, otherwise your device will not forward all required VLANs and/or you will lose access to the device.
We need to assign a region name for each bridge that we want to be in a single MSTP region, you can also specify the region revision, but it is optional, though they need to match. In this example, if all bridges will have the same region name, then they will all be in a single MSTP bridge. In this case, we want to separate a group of 3 bridges in a different MSTP region to do load balancing per VLAN group and to create diversity and scalability.
- Set appropriate region name (and region revision) for each bridge, use the following commands on each device (change the region name!):
/interface bridge set bridge region-name=Rx region-revision=1
After we have created 3 different MSTP regions, we need to decide which device is going to be a regional root for each VLAN group. For consistency, we are going to set the first device (_1) in each region as the regional root for VLAN 10,20 and the third device (_3) in each region as the regional root for VLAN 30,40. This can be done by creating an MST Instance for each VLAN group and assigning a bridge priority to it. The MST Instance identifier is only relevant inside an MSTP region, outside an MSTP region these identifiers can be different and mapped to a different VLAN group.
- Use the following commands on R1_1, R2_1, R3_1:
/interface bridge msti add bridge=bridge identifier=1 priority=0x1000 vlan-mapping=10,20 add bridge=bridge identifier=2 priority=0x3000 vlan-mapping=30,40
- Use the following commands on R1_3, R2_3, R3_3:
/interface bridge msti add bridge=bridge identifier=1 priority=0x3000 vlan-mapping=10,20 add bridge=bridge identifier=2 priority=0x1000 vlan-mapping=30,40
- Use the following commands on R1_2, R2_2, R3_2:
/interface bridge msti add bridge=bridge identifier=1 priority=0x2000 vlan-mapping=10,20 add bridge=bridge identifier=2 priority=0x2000 vlan-mapping=30,40
Now we need to override the port path-cost and/or port priority for each MST Instance. This can be done by adding a MST-Override entry for each port and each MST Instance. To achieve that for a certain MST Instance the traffic flow path is different, we simply need to make sure that the port path cost and/or priority is larger. We can either increase the port path cost or either decrease the port path cost to ports that are facing towards the regional root bridge. It doesn’t matter if you increase or decrease all values, it is important that at the end one port’s path cost is larger than the other’s.
- Use the following commands on R1_1, R2_1, R3_1:
/interface bridge port mst-override add identifier=2 interface=ether1 internal-path-cost=5 add identifier=2 interface=ether2 internal-path-cost=15
- Use the following commands on R1_2, R2_2, R3_2:
/interface bridge port mst-override add identifier=1 interface=ether1 internal-path-cost=5 add identifier=2 interface=ether2 internal-path-cost=9
- Use the following commands on R1_3, R2_3, R3_3:
/interface bridge port mst-override add identifier=1 interface=ether2 internal-path-cost=5 add identifier=1 interface=ether3 internal-path-cost=9
In this case for VLAN 10,20 to reach the third device from the first device, it would choose between ether1 and ether2, one port will be blocked and set as an alternate port, ether1 will have path cost as 5+9=14 and ether2 will have path cost as 10, ether2 will be elected as the root port for MSTI1 on the third device. In case for VLAN 30,40 to reach the first device from the third device, ether1 will have path cost as 5+9=14 and ether2 will have path cost as 15, ether1 will be elected as the root port for MSTI2 on the third device.
Now we can configure the root ports for MSTI0, in which will fall under all VLANs that are not assigned to a specific MST Instance, like in our example VLAN 10,20 and VLAN 30,40. To configure this special MST Instance, you will need to specify internal-path-cost to a bridge port. This value is only relevant to MSTP regions, it does not have any effect outside an MSTP region. In this example will choose that all unknown VLANs will be forwarded over the same path as VLAN 30,40, we will simply increase the path cost on one of the ports.
- Use the following commands on R1_3, R2_3, R3_3:
/interface bridge port set [find where interface=ether3] internal-path-cost=25
At this point, a single region MSTP can be considered as configured and in general, MSTP is fully functional. It is highly recommended to configure the CIST part, but for testing purposes, it can be left with the default values. Before doing any tests, you need to enable MSTP on all bridges.
- Use the following commands on all devices:
/interface bridge set bridge protocol-mode=mstp vlan-filtering=yes
When MSTP regions have been configured, you can check if they are properly configured by forwarding traffic, for example, send tagged traffic from the first device to the third device and change the VLAN ID for the tagged traffic to observe different paths based on VLAN ID. When this is working as expected, then you can continue to configure CIST related parameters to elect a CIST root bridge and CIST root ports. For consistency we will choose the first device in the first region to be the CIST root bridge and to ensure the consistency in case of failure we can set a higher priority to all other bridges.
- Use the following commands on R1_1:
/interface bridge set bridge priority=0x1000
- Use the following commands on R1_2:
/interface bridge set bridge priority=0x2000
- …
- Use the following commands on R3_3:
/interface bridge set bridge priority=0x9000
We also need to elect a root port on each bridge, for simplicity we will choose the port that is closest to Ŗ1_1 as the root port and has the least hops. At this point the procedure to elect root ports is the same as the procedure in (R)STP.
- Use the following commands on R3_3:
/interface bridge port set [find where interface=ether2] path-cost=30 set [find where interface=ether3] path-cost=40 set [find where interface=ether4] path-cost=20
-
Use the following commands on R1_3 and R2_3:
/interface bridge port set [find where interface=ether2] path-cost=20 set [find where interface=ether3] path-cost=30
- Use the following commands on R1_2:
/interface bridge port set [find where interface=ether1] path-cost=30
Порядок перечисления состояний не случаен: при включении (а также при втыкании нового провода), все порты на устройстве с STP проходят вышеприведенные состояния именно в таком порядке (за исключением disabled-портов). Возникает закономерный вопрос: а зачем такие сложности? А просто STP осторожничает. Ведь на другом конце провода, который только что воткнули в порт, может быть свич, а это потенциальная петля. Вот поэтому порт сначала 15 секунд (по умолчанию) пребывает в состоянии прослушивания — он смотрит BPDU, попадающие в него, выясняет свое положение в сети — как бы чего ни вышло, потом переходит к обучению еще на 15 секунд — пытается выяснить, какие mac-адреса “в ходу” на линке, и потом, убедившись, что ничего он не поломает, начинает уже свою работу. Итого, мы имеем целых 30 секунд простоя, прежде чем подключенное устройство сможет обмениваться информацией со своими соседями. Современные компы грузятся быстрее, чем за 30 секунд. Вот комп загрузился, уже рвется в сеть, истерит на тему “DHCP-сервер, сволочь, ты будешь айпишник выдавать, или нет?”, и, не получив искомого, обижается и уходит в себя, извлекая из своих недр айпишник
автонастройки.
Естественно, после таких экзерсисов, в сети его слушать никто не будет, ибо “не местный” со своим 169.254.x.x. Понятно, что все это не дело, но как этого избежать?









