Network: BGP (QUAGGA, BIRD, FRRouting); iWAN/PfR in Global Routing

  • CheatSheet
  • Не совсем корректно с точки зрения таймаута (30 мин lsrefreshtime), но в целом проблематика ospf выглядит потенциально реальной на каналах с потерями, важно что lsa сгенерируется один раз, а hello в среднем три до dead, т.е. чтобы потерялся апдейт достаточно потери одного пакета, а для потери соседства должно потеряться 3 hello подряд: при потерях LSA в линии может до 60 минут указывать в живого пира, у которого уже упал канал до цели. И не переключать роутинг через резерв. Поэтому перешел на iBGP, уменьшив ему дистанцию и bgp timers.
  • CheatSheet2 (private ASN по факту ограничены 65534)

41% of ISPs having connections with only one IPv4 provider. In IPv6 connectivity, the situation is even worse – with over 54%.
Year by year, we observe a positive global trend towards increased reliability and overall availability.
  • Тестирование BGP с использованием разных генераторов:
  • BGP full view table – show ip bgp с роутера 203.133.248.2
  • TCP port 179
  • 20 AD eBGP
  • 200 AD iBGP
  • BGP RFC – 74 шт.
# grep ^"RFC" sw | grep -v summary | sort -n -k2,2
RFC 1745 BGP4/IDRP for IP---OSPF Interaction
RFC 1772 Application of the Border Gateway Protocol in the Internet
RFC 1773 Experience with the BGP-4 protocol
RFC 1774 BGP-4 Protocol Analysis
RFC 1930 Guidelines for creation, selection, and registration of an Autonomous System (AS)
RFC 1997 BGP Communities Attribute
RFC 1998 An Application of the BGP Community Attribute in Multi-home Routing
RFC 2270 Using a Dedicated AS for Sites Homed to a Single Provider
RFC 2385 Protection of BGP Sessions via the TCP MD5 Signature Option
RFC 2439 BGP Route Flap Damping
RFC 2519 A Framework for Inter-Domain Route Aggregation
RFC 2545 Use of BGP-4 Multiprotocol Extensions for IPv6 Inter-Domain Routing
RFC 2918 Route Refresh Capability for BGP-4
RFC 3107 Carrying Label Information in BGP-4
RFC 3221 Commentary on Inter-Domain Routing in the Internet
RFC 3345 Border Gateway Protocol (BGP) Persistent Route Oscillation Condition
RFC 3562 Key Management Considerations for the TCP MD5 Signature Option
RFC 3765 NOPEER Community for Border Gateway Protocol (BGP) Route Scope Control
RFC 3779 X.509 Extensions for IP Addresses and AS Identifiers
RFC 3882 Configuring BGP to Block Denial-of-Service Attacks
RFC 3913 Border Gateway Multicast Protocol (BGMP): Protocol Specification
RFC 4098 Terminology for Benchmarking BGP Device Convergence in the Control Plane
RFC 4264 BGP Wedgies
RFC 4271 A Border Gateway Protocol 4 (BGP-4)
RFC 4272 BGP Security Vulnerabilities Analysis
RFC 4273 Definitions of Managed Objects for BGP-4
RFC 4274 BGP-4 Protocol Analysis
RFC 4275 BGP-4 MIB Implementation Survey
RFC 4276 BGP-4 Implementation Report
RFC 4277 Experience with the BGP-4 Protocol
RFC 4278 Standards Maturity Variance Regarding the TCP MD5 Signature Option (RFC 2385) and the BGP-4 Specification
RFC 4360 BGP Extended Communities Attribute
RFC 4364 BGP/MPLS IP Virtual Private Networks (VPNs)
RFC 4365 Applicability Statement for BGP/MPLS IP Virtual Private Networks (VPNs)
RFC 4381 Analysis of the Security of BGP/MPLS IP Virtual Private Networks (VPNs)
RFC 4382 MPLS/BGP Layer 3 Virtual Private Network (VPN) Management Information Base
RFC 4384 BGP Communities for Data Collection
RFC 4451 BGP MULTI_EXIT_DISC (MED) Considerations
RFC 4456 BGP Route Reflection: An Alternative to Full Mesh Internal BGP (IBGP)
RFC 4486 Subcodes for BGP Cease Notification Message
RFC 4632 Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan
RFC 4659 BGP-MPLS IP Virtual Private Network (VPN) Extension for IPv6 VPN
RFC 4684 Constrained Route Distribution for Border Gateway Protocol/MultiProtocol Label Switching (BGP/MPLS) Internet Protcol (IP) Virtual Private Networks (VPNs)
RFC 4698 IRIS: An Address Registry (areg) Type for the Internet Registry Information Service
RFC 4724 Graceful Restart Mechanism for BGP
RFC 4760 Multiprotocol Extensions for BGP-4
RFC 4761 Virtual Private LAN Service (VPLS) Using BGP for Auto-Discovery and Signaling
RFC 4781 Graceful Restart Mechanism for BGP with MPLS
RFC 4797 Use of Provider Edge to Provider Edge (PE-PE) Generic Routing Encapsulation (GRE) or IP in BGP/MPLS IP Virtual Private Networks
RFC 4808 Key Change Strategies for TCP-MD5
RFC 4893 BGP Support for Four-octet AS Number Space
RFC 5004 Avoid BGP Best Path Transitions from One External to Another
RFC 5065 Autonomous System Confederations for BGP
RFC 5123 Considerations in Validating the Path in BGP
RFC 5195 BGP-Based Auto-Discovery for Layer-1 VPNs
RFC 5291 Outbound Route Filtering Capability for BGP-4
RFC 5292 Address-Prefix-Based Outbound Route Filter for BGP-4
RFC 5396 Textual Representation of Autonomous System (AS) Numbers
RFC 5398 Autonomous System (AS) Number Reservation for Documentation Use
RFC 5492 Capabilities Advertisement with BGP-4
RFC 5512 The BGP Encapsulation Subsequent Address Family Identifier (SAFI) and the BGP Tunnel Encapsulation Attribute
RFC 5543 BGP Traffic Engineering Attribute
RFC 5566 BGP IPsec Tunnel Encapsulation Attribute
RFC 5575 Dissemination of Flow Specification Rules
RFC 5668 4-Octet AS Specific BGP Extended Community
RFC 5701 IPv6 Address Specific BGP Extended Community Attribute
RFC 5747 4over6 Transit Solution Using IP Encapsulation and MP-BGP Extensions
RFC 5824 Requirements for Supporting Customer Resource ReSerVation Protocol (RSVP) and RSVP Traffic Engineering (RSVP-TE) over a BGP/MPLS IP-VPN
RFC 6037 Cisco Systems' Solution for Multicast in BGP/MPLS IP VPNs
RFC 6039 Issues with Existing Cryptographic Protection Methods for Routing Protocols
RFC 6115 Recommendation for a Routing Architecture

 

Ibgp/ebgp route announcements

Question: Взгляните на топологию выше. Маршрутизаторы R1, R2 и R3 являются iBGP-соседями, и R2 является eBGP-соседом для транзитного маршрутизатора. Выберите верные утверждения касательно анонсирования маршрутов для маршрутизатора R2 (от 2 до всех вариантов):
R2 - не будет анонсировать маршруты, полученные от R1 на R3
R2 будет анонсировать маршруты, полученные от R3 на R1

R2 будет анонсировать маршруты, полученные от транзитного маршрутизатора на R1 и R3

R2 не будет анонсировать маршруты, полученные от R1 или R3 на транзитный маршрутизатор

R2 не будет анонсировать маршруты, полученные от транзитного маршрутизатора на R1 и R3
answer: R2 будет анонсировать маршруты от транзитного маршрутизатора iBGP-соседям, и наоборот. Маршруты, полученные от iBGP-соседа не будут распространяться другому iBGP-соседу для предотвращения петель.

 

 

 

Performence Routing, SD-WAN (IWAN, pfR)

У cloudflare роутинг между ДЦ на основе качественных характеристик задержки каналов между ДЦ – каждому префиксу сопоставляется кост задержки, чем ниже тем лучше. Это позволяет улучшить TTFB на 30%. Причем трафик по этим маршрутам роутится как в сторону серверов cloudflare (если DST находится в Cloudflare), так и в сторону исходящих нод cloudflare, которые наиболее близки к серверам назначения (если DST НЕ находится в Cloudflare).

https://blog.cloudflare.com/warp-technical-challenges/
At Cloudflare we have a product called Argo. Argo makes websites' time to first byte more than 30% faster on average by continually monitoring thousands of routes over the Internet between our data centers. That data builds a database which maps every IP address range with the fastest possible route to every destination. When a packet arrives it first reaches the closest data center to the client, then that data center uses data from our tests to discover the route which will get the packet to its destination with the lowest possible latency.

This proxy is responsible for loading the fastest path from our Argo database and beginning an HTTP session with a machine in the data center this traffic should be forwarded to.

 

Схемы использования
  • Single Homed: вы подключены к одному провайдеру с помощью одного канала.

  • Dual Homed: вы подключены к одному провайдеру с помощью двух каналов.

  • Single Multi-homed: вы подключены к двум провайдерам с помощью одинарных каналов.

  • Dual Multi-homed: вы подключены к двум провайдерам с помощью двух каналов.

Пример:

Название по каждой картинке

1) Single Homed 
2) Dual Homed
3) Single Multi-homed
4) Dual Homed

 

MP BGP

Multiprotocol BGP – расширение классического BGP IPv4. Н его базе осуществляется обмен маршрутной информацией разных address family, например: MPLS L3VPN, VPLS в версии Compella, EVPN.

 

bgp messages
  • Open – отправка «hello” после установки tcp 3whs
  • Update – отправка префиксов
  • Keepalive – независимая от tcp проверка «живости» соседа, по умолчанию каждые 60 сек с holdtime 180
  • Notification – отправляется в случае ошибок (напр. по holdtime, согласования, сбросу сессии), после отправки сессия с соседом разрывается.

BGP community

Есть well-known коды community, которые интерпретируются всеми устройствами с однозначной/одинаковой логикой (напр. no export, no advertise), но можно указывать и кастомизированные вещи в community.

зYou know what a BGP community is, right? It’s like a tag you can put onto a BGP advertisement, so that you can tell other routers to take a certain action if that community exists.

There’s two kinds of communities: “regular” communities, and extended communities. Focusing just on the regular ones for now, communities are made up of two 16-bit numbers, with a colon between them, for example 123:456, or 59876:33333.

The first number is pretty much always your autonomous system number. The second number can be anything of your choosing.

For example, if your AS was 64512 then you might use 64512:100 to set the local preference to 500, while 64512:666 might mean “set the next-hop to discard the traffic”. Communities can be used to change pretty much anything you like, and they’re used extensively in the service provider world to make sure that the many hundreds of thousands of prefixes on the public internet get routed correctly.

In addition to the ones you can define yourself, there are also some “well-known” communities. I always thought this was a goofy name for them. Try going out in the street and asking the average Jeff or Samantha whether they’ve heard of these communities. You’ll soon see how “well-known” they are.

In any case, these communities are reserved, and should be understood by all BGP-speaking routers. The below screenshot is from RFC 1997, which defines three of them.



 

BGP neighbor STATES
  • idle – нет соединения с соседом даже на уровне TCP или начало инициации процесса установки связи
  • connect – попытка установки TCP соединения
  • active –  TCP connect поднят, но BGP сообщения не передаются (напр. у соседа не настроен BGP) или происходит процесс инициации
  • opensent – наш роутер отправляет BGP сообщения соседу по поднятому TCP connect
  • openconfirm – наш роутер получает BGP сообщения соседу по поднятому TCP connect
  • established – TCP и BGP связь поднята с двух сторон, соседи могут обмениваться BGP сообщениями
BEST PATH selection ALGORITHM
  • iBGP – в качестве “метрики” используются атрибуты пути.

0 – only valid path

1 – weight

2 – local pref

3 – source (network source > redistributed source)

4 – as path – пример использования prepend в решении защиты от DDoS от Imperva на основе BGP пиринга поверх GRE (о самой защите подробнее в статье)

8 – lowest rid neighbor

show
  • Можно посмотреть на работающем Cisco ASR1004 http://routeviews.org/. На этом роутере есть full view от Level3 (AS 3356), Hurricane Electric (AS 6939), ATT (AS 7018). Активно используется – когда я заходил было 10 пользователей в show users 😉
Cisco CLI access is available on
route-views.routeviews.org

cisco ASR1004 (RP2) processor (revision RP2) with 9876483K/6147K bytes of memory.

route-views>show user | count vty
Number of lines which match regexp = 10

# offtop - интересная схема адресации - серый IP повторяет белый полностью кроме первого октета.
route-views>show ip interface brief | i \.
Te0/0/0 128.223.51.103 YES NVRAM up up
GigabitEthernet0 10.223.51.103 YES NVRAM up up
show run | sec bgp

route-views>show ip bgp sum
BGP router identifier 128.223.51.103, local AS number 6447 # router ID и номер локальной AS
BGP table version is 463214939, main routing table version 463214939 # версия обновляется с каждым апдейтом (в среднем за минуту 100 изменений для full view)
Path RPKI states: 4379825 valid, 19259166 not found, 105992 invalid
834698 network entries using 207005104 bytes of memory # сколько памяти используется под network entries (200MB)
23744983 path entries using 2849397960 bytes of memory # сколько памяти используется под path entries (2,8GB)
3848916/140577 BGP path/bestpath attribute entries using 954531168 bytes of memory
3529986 BGP AS-PATH entries using 180940404 bytes of memory
5 BGP ATTR_SET entries using 200 bytes of memory
150489 BGP community entries using 18543970 bytes of memory
1458 BGP extended community entries using 101952 bytes of memory
0 BGP route-map cache entries using 0 bytes of memory
0 BGP filter-list cache entries using 0 bytes of memory
BGP using 4210520558 total bytes of memory # сколько в сумме BGP потребляет памяти (4210 MB)
BGP activity 11009586/10091487 prefixes, 1306445625/1277514450 paths, scan interval 60 secs

Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd
4.68.4.46 4 3356 3412636 45233 463215526 0 0 2w0d 780254
#

Neighbor - Router ID соседа,
V - версия протокола BGP (4 - текущая),
AS - номер автономной системы соседа,
Msg - количество сообщений получено/отправлено,
Up/Down - сколько активно соседство,
State/PfxRcd - сколько префиксов изучено от этого соседа, в случае если состоение отличное от Established (Idle, Active, etc) - отображается и оно

5.101.110.2 4 14061 0 0 1 0 0 never Idle
12.0.1.63 4 7018 3769519 10019 463215526 0 0 6d07h 777142
37.139.139.17 4 57866 4539630 19837 463215526 0 0 6d07h 778424
64.71.137.241 4 6939 3136680 8263 463215526 0 0 5d05h 805594
66.59.190.221 4 6539 0 0 1 0 0 never Idle
66.110.0.86 4 6453 0 0 1 0 0 never Active
66.185.128.48 4 1668 0 0 1 0 0 never Active
69.31.111.244 4 4436 0 0 1 0 0 never Active
80.241.176.31 4 20771 0 0 1 0 0 never Active
route-views>show ip bgp neighbors
BGP neighbor is 4.68.4.46, remote AS 3356, external link # external = eBGP, internal = iBGP
Description: Level3
BGP version 4, remote router ID 4.69.184.201
BGP state = Established, up for 2w0d # состояние
Last read 00:00:02, last write 00:00:02, hold time is 90, keepalive interval is 30 seconds
Configured hold time is 600, keepalive interval is 100 seconds
Minimum holdtime from neighbor is 0 seconds
Neighbor sessions:
1 active, is not multisession capable (disabled)
Neighbor capabilities:
Route refresh: advertised and received(new)
Four-octets ASN Capability: advertised and received
Address family IPv4 Unicast: advertised and received
Address family IPv4 Multicast: advertised and received
Enhanced Refresh Capability: advertised
Multisession Capability:
Stateful switchover support enabled: NO for session 1
Message statistics:
InQ depth is 0
OutQ depth is 0

Sent Rcvd
Opens: 1 1
Notifications: 0 0
Updates: 2 3406689
Keepalives: 45751 41985
Route Refresh: 0 0
Total: 45754 3448675
Do log neighbor state changes (via global configuration)
Default minimum time between advertisement runs is 30 seconds


show tcp brief # смотрим с кем установлены TCP сессии
route-views>show ip bgp
BGP table version is 463365309, local router ID is 128.223.51.103
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S Stale, m multipath, b backup-path, f RT-Filter, x best-external, a additional-path, c RIB-compressed,
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found

Network Next Hop Metric LocPrf Weight Path
V* 1.0.0.0/24 162.251.163.2 0 53767 13335 i
# V - маршрут проверен через RPKI
# r - RIB failure - обычно маршрут не инсталлирован BGP т.к есть маршрут от других источников маршрутной информации (с меньшим AD - connected, static, IGP protocols)
# * - валидный маршрут, next hop доступен в соответствии с RIB
# Network - сеть в BGP

# Next hop - кто сеть анонсирует, если там 0.0.0.0 - это локальный роутер
# Path - путь в виде последовательности AS и информация, как сеть попала в BGP (i - network command, ? - redistribution)

V* 212.66.96.126 0 20912 13335 i
V* 114.31.199.1 0 4826 13335 i
V* 64.71.137.241 0 6939 13335 i
V* 91.218.184.60 0 49788 13335 i
route-views>show ip route summary
IP routing table name is default (0x0)
IP routing table maximum-paths is 32
Route Source Networks Subnets Replicates Overhead Memory (bytes)
connected 0 2 0 192 576
static 1 87 0 8448 25344
application 0 0 0 0 0
bgp 6447 207425 627188 0 80122848 240368544
External: 834613 Internal: 0 Local: 0 # сколько BGP маршрутов
internal 9453 64826904
Total 216879 627277 0 80131488 305221368 # сколько всего маршрутов в RIB (844156)
config
router bgp <local_asn>

neighbor <remote_rid> remote-as <remote_asn> # remote_asn может совпадать с local_asn, тогда это будет iBGP соседство.
- в качестве RID для eBGP обычно не используется Loopback т.к. связь устанавливается на конкретном линке и избыточность не предусмотрена, но возможно и использования Loopback со static routes.
- в качестве RID для iBGP обычно используется loopback, чтобы падение конкретного интерфейса не влияло на BGP при наличии дополнительных путей между роутерами.

neighbor <remote_rid> update-source <rid_interface> # указываем с какого IP мы устанавливаем связь с соседом, иначе определяется роутингом и в случае указания rid как loopback связи не будет (.к. пакеты будут формироваться не с loopback адреса)

neighbor <remote_rid> weight <weight> # указываем weight для маршрутов соседа. Чем больше тем лучше. По умолчанию 0. После указания нужен рестарт (clear ip bgp <remote_rid>).

redistribute ... # импортируем маршруты в BGP через редистрибьюцию

network <network> mask <mask> # импортируем маршруты в BGP через network, маска должна быть корректная (и не wildcard), иначе маршрут не будет импортирован

 

QUAGGA

 

BIRD

 

FRRouting

FRRouting используется в Cumulus Linux, VyOS. В код контрибьютят сотрудники nvidia (Cumulus). Поддерживаются ключевие фичи и специфичные, например, BGP peer-group. Используется в яндекс (nexthop 2022 FBOSS).

https://docs.nvidia.com/networking-ethernet-software/cumulus-linux-50/Layer-3/FRRouting/
Cumulus Linux uses FRR to provide the routing protocols for dynamic routing and supports the following routing protocols:
- Open Shortest Path First (v2 and v3)
- Border Gateway Protocol

https://blog.vyos.io/using-dmvpn-and-bgp-to-interconnect-multiple-sites
- VyOS makes use of FRRouting as its routing control plane which is abstracted by our CLI commands.
- We will use a BGP peer-group for the DMPN spokes at the hub so in case we change something on our configuration we do it for all our DMVPN remote sites at once.

 

Анонс своих подсетей

Возможен через редистрибьюцию static. Так делают и на сетевых девайсах и на Security (CheckPoint).

Коллеги, приветствую. Столкнулся с ситуацией, что чек поинт не даёт создать больше 16 loopback интерфейсов. Но, никак не могу найти об этом упоминаний в базе знаний и админ гайдах. Кто-нибудь знает про это ограничение, и может его можно обойти?

Для приземления белых ip на чек и редистрибуции маршрутов в BGP. Заказчику отдают большое количество белых ip из разных подсетей.

Белые ip для nat? Тогда им не нужны интерфейсы. А маршруты /32 в бгп можно и из статиков в null отдаватьa.

Подробнее - А как альтернатива лупбэкам - можно написать статик маршрут в null, его редистрибьютить в bgp и уже префикс этот отдавать. Правда как поведёт себя маэстро, я не уверен, но на классике работало)

Да, отлично работает. Мы сначала в сторону алиасов смотрели, но в маестро надо как-то отдельно включать поддержку алиасов, и мы решили не заморачиваться

Да, с null маршрутом сработало. А есть какой-то best practice, как лучше реализовать подобный кейс

В сетевом мире обычно так и делают)

 

 

Дамп

BGP-capture.pcapng

Leave a Reply