Метка: BGP MiTM

  • Принципы защиты сетевого оборудования регионального уровня

    Принципы защиты сетевого оборудования регионального уровня

     Оборудование регионального уровня непосредственно связано с оборудованием сетей клиентов сети IP/MPLS ПАО «Ростелеком» и, следовательно, подвергается максимальному риску атак из сетей клиентов ПАО «Ростелеком».

    Принципы защиты оборудования регионального уровня

          В первую очередь необходима защита маршрутизаторов уровня доступа от несанкционированного доступа с использованием различных сетевых протоколов, а также от некорректной маршрутной информации, как в глобальной таблице маршрутизации, так и в отдельных VRF клиентов.

          В основном защита от несанкционированного доступа производится аналогично защите для маршрутизаторов ядра.

          Поскольку пиринг с сетями клиентов и с сетями других операторов происходит с использованием протокола BGP, то необходима, прежде всего, фильтрация префиксов, приходящих от BGP маршрутизаторов сторонних сетей с целью недопущения попадания некорректной маршрутной информации, анонсируемой маршрутизаторами сторонних сетей в результате ошибки или умышленно. Фильтрация префиксов IPv4 осуществляется на базе списка, приведённого в [RFC6890]. Данный список содержит адреса следующих зарезервированных IETF и не подлежащих выделению сетей:

    • 0.0.0.0/8;
    • 0.0.0.0/1 – 0.0.0.0/32;
    • 10.0.0.0/8;
    • 172.16.0.0/12;
    • 192.168.0.0/16;
    • 127.0.0.0/8;
    • 192.0.0.0/24;
    • 192.0.2.0/24;
    • 169.254.0.0/16;
    • 100.64.0.0/10;
    • 192.88.99.0/24;
    • 198.18.0.0/15;
    • 198.51.100.0/24;
    • 203.0.113.0/24;
    • 224.0.0.0/4;
    • 240.0.0.0/4;

          Фильтрация префиксов IPv6 осуществляется на базе списка, указанного в [RFC6890] следующие префиксы:

    • ::/128;
    • ::1/128;
    • FE80::/10;
    • FC00::/7;
    • 2001::/23;
    • 2002::/16;
    • 64:ff9b::/96;
    • ::ffff:0:0/96;
    • 100::/64;

          С целью уменьшения общего числа префиксов фильтруются все префиксы с маской, длина которой превышает 24 бита для IPv4 и 48 бит для IPv6.
          Такая же фильтрация применяется и при передаче префиксов за пределы автономной системы Ростелеком.

          Пример политики для фильтрации неиспользуемых в сети Internet префиксов на маршрутизаторах Juniper:

    protocols {

        bgp {

            group INET_Customers {

                type external;

                neighbor 1.1.1.2 {

                    description «### Test Client ###»;

                    import sanity-check;

                    export sanity-check;

                    peer-as 65432;

                }

            }

            group INET_v6_Customers {

                type external;

                family inet6 {

                    unicast;

                }

                neighbor 1::2 {

                    description «### Test IPv6 Client ###»;

                    import v6-sanity-check;

                    export v6-sanity-check;

                    peer-as 65432;

                }

            }

        }

    }

    policy-options {

        policy-statement sanity-check {

            term reject-bogons {

                from policy bogons;

                then reject;

            }

            term accept-blackhole {

                from community type_blackhole_route;

                then next policy;

            }

            term reject-long-prefixes {

                from {

                    route-filter 0.0.0.0/0 prefix-length-range /25-/32 reject;

                }

            }

        }

        policy-statement bogons {

            term match-rfc6890-networks {

                from {

                    route-filter 10.0.0.0/8 orlonger accept;

                    route-filter 172.16.0.0/12 orlonger accept;

                    route-filter 192.168.0.0/16 orlonger accept;

                    route-filter 0.0.0.0/1 through 0.0.0.0/32 accept;

                    route-filter 0.0.0.0/8 orlonger accept;

                    route-filter 127.0.0.0/8 orlonger accept;

                    route-filter 192.0.0.0/24 orlonger accept;

                    route-filter 192.0.2.0/24 orlonger accept;

                    route-filter 169.254.0.0/16 orlonger accept;

                    route-filter 192.88.99.0/24 orlonger accept;

                    route-filter 224.0.0.0/4 orlonger accept;

                    route-filter 240.0.0.0/4 orlonger accept;

                    route-filter 198.18.0.0/15 orlonger accept;

                    route-filter 198.51.100.0/24 orlonger accept;

                    route-filter 203.0.113.0/24 orlonger accept;

                    route-filter 100.64.0.0/10 orlonger accept;           

                }

            }

            term reject-others {

                then reject;

            }

        }

        policy-statement v6-sanity-check {

            term reject-bogons {

                from policy v6-bogons;

                then reject;

            }

            term reject-long-prefixes {

                from {

                    route-filter ::/0 prefix-length-range /48-/128 reject;

                }

            }

        }

        policy-statement v6-bogons {

            term match-rfc6890-networks {

                from {

                    route-filter ::/128 exact accept;

                    route-filter ::1/128 exact accept;

                    route-filter ::/1 through ::/128 accept;

                    route-filter FE80::/10 orlonger accept;

                    route-filter FC00::/7 orlonger accept;

                    route-filter 2001::/23 orlonger accept;

                    route-filter 2002::/16 orlonger accept;

                    route-filter 64:ff9b::/96 orlonger accept;

                    route-filter ::ffff:0:0/96 orlonger accept;

                    route-filter 100::/64 orlonger accept;

                }

            }

            term reject-others {

                then reject;

            }

        }

    }

          Для снижения вероятности программных сбоев, которые могут произойти в случае большого количества транзитных автономных систем в пути для какого-то префикса, принимаются только анонсы, количество автономных систем в AS_PATH которых не превышает 50. Такое значение не позволяет принимать слишком длинные AS_PATH и в то же время достаточно для корректно сформированных анонсов.

          Пример контроля количества AS в принимаемых анонсах на маршрутизаторах Juniper Networks:

    protocols {

        bgp {

            group INET_Customers {

                type external;

                neighbor 1.1.1.2 {

                    description «### Test Client ###»;

                    import restrict-long-as;

                    peer-as 65432;

                }

            }

            group INET_v6_Customers {

                type external;

                family inet6 {

                    unicast;

                }

                neighbor 1::2 {

                    description «### Test IPv6 Client ###»;

                    import restrict-long-as;

                    peer-as 65432;

                }

            }

        }

    }

    policy-options {

        policy-statement restrict-long-as {

            term reject-long-as_path {

                from as-path too_long_as_path;

                then reject;

            }

        }

        as-path too_long_as_path «.{50,}»;

    }

          Пример контроля количества AS в принимаемых анонсах на маршрутизаторах Cisco Systems:

    router bgp 12389

     bgp maxas-limit 50

    !


          Также необходимо запретить приём от клиентов префиксов Ростелеком и маршрута по умолчанию. Значения BGP Community, не предназначенные для использования клиентами (раздел «3.2.1 Маркировка маршрутов»), должны быть удалены.

          Пример запрета приёма префиксов Ростелеком и маршрута по умолчанию:

    protocols {

        bgp {

            group INET_Customers {

                type external;

                neighbor 1.1.1.2 {

                    description «### Test Client ###»;

                    local-address 1.1.1.1;

                    import INET_CUSTOMER_in;

                    peer-as 65432;

                }

            }

            group INET_v6_Customers {

                type external;

                family inet6 {

                    unicast;

                }

                neighbor 1::2 {

                    description «### Test IPv6 Client ###»;

                    local-address 1::1;

                    import INET__v6_CUSTOMER_in;

                    peer-as 65432;

                }

            }

        }

    }

    policy-options {

        policy-statement INET_CUSTOMER_in {

            term reject-RT-aggregate {

                from policy RT-aggregate;

                then reject;

            }

            term reject-RT-longer-prefixes {

                from policy RT-longer-prefixes;

                then reject;

            }

            term reject-default-route {

                from {

                    route-filter 0.0.0.0/0 exact;

                }

                then reject;

            }

            term remove-12389-communities {

                then {

                    community delete 12389:1-3X;

                    community delete 12389:1UZZ;

                }

            }

        }

        policy-statement RT-aggregate {

            term match-RT-aggregate-networks {

                from {

                    route-filter 87.226.128.0/17 exact accept;

                    route-filter 79.133.64.0/19 exact accept;

                    route-filter 92.50.192.0/18 exact accept;

                    route-filter 94.25.0.0/17 exact accept;

                }

            }

            term reject-others {

                then reject;

            }

        }

        policy-statement RT-longer-prefixes {

            term match-RT-longer-prefixes {

                from {

                    route-filter 87.226.128.0/17 longer accept;

                    route-filter 79.133.64.0/19 longer accept;

                    route-filter 92.50.192.0/18 longer accept;

                    route-filter 94.25.0.0/17 longer accept;

                }

            }

            term reject-others {

                then reject;

            }

        }

        policy-statement INET_v6_CUSTOMER_in {

            term reject-RT-v6-aggregate {

                from policy RT-v6-aggregate;

                then reject;

            }

            term reject-RT-v6-longer-prefixes {

                from policy RT-v6-longer-prefixes;

                then reject;

            }

            term reject-default-route {

                from {

                    route-filter ::/0 exact;

                }

                then reject;

            }

            term remove-12389-communities {

                then {

                    community delete 12389:1-3X;

                    community delete 12389:1UZZ;

                }

            }

        }

        policy-statement RT-v6-aggregate {

            term match-RT-v6-aggregate-networks {

                from {

                    route-filter 2A01:620::/32 exact accept;

                }

            }

            term reject-others {

                then reject;

            }

        }

        policy-statement RT-v6-longer-prefixes {

            term match-RT-v6-longer-prefixes {

                from {

                    route-filter 2A01:620::/32 longer accept;

                }

            }

            term reject-others {

                then reject;

            }

        }

        community 12389 members 12389:*;

        community 12389:1-3X members «^12389:.{1,3}$»;

        community 12389:1UZZ members «^12389:1…$»;

    }

          В целях уменьшения влияния анонсов отдельных клиентов на ресурсы маршрутизаторов Сети ограничивается количество префиксов, получаемых от клиентов, значением 1000 для префиксов IPv4 и 100 для IPv6 (это значение может быть изменено для отдельного клиента или пересмотрено для всей Сети при изменении общей ситуации в сети Internet). При превышении 80% от этого значения генерируется сообщение в журнале событий (syslog), а при превышении 100% сессия BGP разрывается и может быть установлена вновь через 30 минут.

          Пример ограничения количества принимаемых префиксов на маршрутизаторах доступа:

    protocols {

        bgp {

            group INET_Customers {

                type external;

                family inet {

                    unicast {

                        prefix-limit {

                            maximum 1000;

                            teardown 80 idle-timeout 30;

                        }

                    }

                }

            }

            group INET_v6_Customers {

                type external;

                family inet6 {

                    unicast {

                        prefix-limit {

                            maximum 100;

                            teardown 80 idle-timeout 30;

                        }

                    }

                }

            }

        }

    }

          В существующей сети ПАО «Ростелеком» для защиты от некорректных маршрутов применяется фильтрация на основе информации Routing Arbiter Database, являющейся одной из наиболее полных на сегодняшний день баз информации о зарегистрированных в региональных центрах регистрации (Regional Internet Registry, RIR) объектах (автономные системы, префиксы, принципы взаимодействия с соседями). Такая фильтрация является очень мощным средством обеспечения безопасности и стабильности.    Кроме того, процесс получения информации и настройки маршрутизаторов автоматизируется с помощью специализированных программных средств. Если номер автономной системы клиента двухбайтный, для формирования имени фильтра на сети IP/MPLS ПАО «Ростелеком» используется форма CUSTOMER:<ASN>, где <ASN> – номер автономной системы клиента или название AS-SET, AS-NUM или AUT-NUM, зарегистрированные в RIR.

          Пример фильтра при приёме маршрутов от клиента:

    protocols {

        bgp {

            group INET_Customers {

                neighbor 1.1.1.2 {

                    description «### Test Client ###»;

                    import CUSTOMER:65432;

                    peer-as 65432;

                }

            }

        }

    }

    policy-options {

        policy-statement CUSTOMER:65432 {

            term rtbh {

                from {

                    community type_blackhole_route;

                    route-filter 2.1.0.0/16 orlonger;

                    route-filter 1.2.3.0/24 orlonger;

                }

                then {

                    community add NO_EXPORT;

                    next-hop discard;

                    accept;        

                }

            }

            term prefixes {

                from {

                    route-filter 2.1.0.0/16 upto /24;

                    route-filter 1.2.3.0/24 exact;

                }

                then next policy;

            }

            then reject;

        }

        community NO_EXPORT members no-export;

        community type_blackhole_route members 12389:55555;

    }

          Необходимо отметить, что фильтрация префиксов, получаемых от BGP-маршрутизаторов сторонних сетей, не гарантирует отсутствие входящих пакетов с адресами источников из запрещённых сетей. Как и в случае маршрутизаторов магистрального уровня, необходима настройка списков доступа на внутреннем интерфейсе маршрутизатора, связывающем подсистему управления маршрутизатором с подсистемой коммутации пакетов. Также необходимо запретить возможность записывания данных по протоколу SNMP для всех устройств уровня доступа, кроме маршрутизаторов с функциональностью IP SLA, оставив лишь возможность чтения некоторых параметров необходимых для систем мониторинга и управления, а также для систем биллинга. Для маршрутизаторов с функциональностью IP SLA остается возможность записи по протоколу SNMP в CISCO-RTTMON MIB.
          Таким образом, политика безопасности маршрутизаторов доступа в основном совпадает с политикой безопасности маршрутизаторов ядра. Для организации второго рубежа защиты, ориентированного на защиту не отдельного устройства, а сети от несанкционированного доступа и возможности проведения атак типа отказ в обслуживании необходима настройка фильтрации пакетов на клиентских интерфейсах. Универсальный фильтр, запрещающий прохождение пакетов, в адресах назначения которых указаны адреса интерфейсов внутренних устройств сети IP/MPLS ПАО «Ростелеком», кроме тех, которые обеспечивают функционирование публичных сервисов. Для клиентов, использующих только услуги передачи голосового трафика через устройства голосовых сегментов сети IP/MPLS ПАО «Ростелеком», настраиваются списки доступа, разрешающие доступ только к пограничным контроллерам сессий (SBC) на интерфейсах, посредством которых эти клиенты подключаются к сети.

          Пример настройки фильтрации на клиентских интерфейсах маршрутизаторов доступа:

    interfaces {

        ge-2/0/0 {

            unit 2 {

                family inet {

                    filter {

                        input Prohibited_Destinations;

                    }

                }

            }

        }

    }

    firewall {

        filter Prohibited_Destinations {

            term RTK_IPMPLS_internal {

                from {

                    address {

                        87.226.133.0/24;

                        87.226.134.0/24;

                        87.226.135.0/24;

                        87.226.136.0/24;

                        87.226.137.0/24;

                        87.226.138.0/24;

                        87.226.139.0/24;

                    }

                }

                then { 

                    discard;

                }

            }

            term RTK_IPMPLS_MGMT {

                from {

                    address {

                        87.226.129.0/24;

                        87.226.131.128/27;

                        10.0.0.0/8;

                    }

                }

                then {

                    discard;

                }

            }

            term default-action {

                then accept;

            }

        }

    }

          С целью защиты коммутирующих устройств узла:

    • протокол VTP (VLAN Trunking Protocol) на коммутаторах переводится в режим transparent;
    • приём и передача пакетов Spanning Tree Protocol (STP) запрещается на портах, к которым подключены клиенты;
    • защита от перегрузки интерфейса между маршрутизатором и коммутатором излишним трафиком осуществляется путём ограничения скорости входящего трафика на порту подключения клиента;
    • для предотвращения перегрузки таблицы MAC адресов коммутатора на интерфейсах подключения клиентов настраивается механизм Port Security, позволяющий коммутатору заучить не более определённого количества MAC адресов на этом порту;
    • производится ограничение трафика broadcast/multicast/unknown unicast на интерфейсах подключения клиентов (storm control);
    • не применяются протоколы автоматического обнаружения на уровне 2 (CDP, LLDP, LLDP-MED).

          Соответствующие настройки коммутаторов описаны в разделе «8 Принципы настройки агрегирующих коммутаторов».

  • Скачать CiscoWorks • Скачать Cisco Prime LAN Management Solution 4.1 для Windows

    Скачать CiscoWorks • Скачать Cisco Prime LAN Management Solution 4.1 для Windows

    Пакет CiscoWorks LAN Management Solution (LMS) содержит набор средств управления, необходимых для упрощения развертывания, администрирования, мониторинга и диагностики различных кампусных инфраструктур от Cisco.

    CiscoWorks LAN Management Solution

    Используя общие централизованные системы и сведения о сети, CiscoWorks LAN Management Solution предоставляет уникальный набор функций, позволяющих снизить время развертывания сети и расходы на администрирование.

    Основные свойства Cisco LMS:

    • Надежный набор средств уровня 2 для обнаружения устройств и подключений, детализированной визуализации топологии, настройки услуг уровня 2 и отслеживание оконечных станций, облегчающее настройку, управление и понимание физической и логической сетевой инфраструктуры.
    • Представление сетевых устройств на основе графического пользовательского интерфейса с отображением в реальном времени динамических данных о состоянии позволяет упростить диагностику и устранение неисправностей устройств.
    • Обнаружение неисправностей в реальном времени, функции анализа и отчета, использующие подробные сведения об устройствах и правила поиска неисправностей, основанных на лучших методах компании Cisco.
    • Упрощенные задачи администрирования, требующие меньших затрат времени, и централизованное управление сетью с помощью управления заменой устройств, сетевой конфигурацией и образами программного обеспечения, доступность сети и анализ неисправностей.
    Cisco prime

    CiscoWorks LMS состоит из следующих программных компонентов:

    • CiscoWorks Common Services — базовая платформа, осуществляющая общее управление интеграцией со сторонними системами сетевого управления, контроль административного доступа и сервисами для всего семейства решений CiscoWorks.
    • CiscoWorks LMS Portal — собственно, CMS сайта.
    • CiscoWorks Assistant — появился с версии 3.0, представляет собой набор визардов для первичной настройки компонентов.
    • Resource Manager Essentials (RME) — для управления критичными сетевыми ресурсами через Интернет с использованием web-интерфейса. Предоставляет набор инструментов для поиска и устранения неисправностей в сети, сбора детализированных отчетов, централизованного обновления программного обеспечения и конфигураций устройств, управления и конфигурации VPN, CallManager и др.
    • Internet Performance Monitor (IPM) — для анализа, оптимизации производительности и отладки неисправностей сетевых соединений на основе Cisco IP SLA.
    • CiscoView — графическое средство управления устройствами.
    • MiniRMON — инструмент для работы с RMON и RMON2.
    • Campus Manager (CM) — для обнаружения и управления L2/L3 устройствми, конфигурирования и управления VLAN и ATM LANE, а также определения подключения пользователей и IP телефонов.
    • Device Fault Manager (DFM) — обеспечивает обнаружение и определение причин сбоев сетевого оборудования в режиме реального времени.
    • Virtual Network Management (VNM) — появился с версии 3.2, занимается визуализацией топологии виртуальных сетей и их диагностикой, VRF.
    • Health and Utilization Monitor (HUM) — появился с версии 3.0.1, идёт как Add-On, требует отдельной лицензии. занимается сбором, отображением и мониторингом параметров производительности, уведомлением о превышении пороговых значений. Поддерживает только cisco-устройства, может мониторить до 1000 устройств.

    Все эти компоненты имеют свою нумерацию в рамках конкретной версии LMS, скачать Cisco Prime LAN Management Solution 4.1 для Windows

  • Celer Bridge incident analysis or why the BGP hijacks still having success

    Celer Bridge incident analysis or why the BGP hijacks still having success

     On 17 August 2022, a BGP spoofer was able to steal approximately USD 235,000 in cryptocurrency by employing a BGP hijack against the Celer Bridge, a service that allows users to convert between cryptocurrencies.

    In this blog post, I discuss this and previous infrastructure attacks against cryptocurrency services. While these episodes revolve around the theft of cryptocurrency, the underlying attacks hold lessons for securing the BGP routing of any organization that conducts business on the Internet.

    The BGP hijack of Celer Bridge

    In a detailed blog post earlier this month, the threat intelligence team from Coinbase explained how the attack went down (Note: Coinbase was not the target of the attack). In short, the attacker used a BGP hijack to gain control of a portion of Amazon’s IP address space.

    Doing so allowed it to impersonate a part of the Celer Bridge infrastructure, which was hosted by Amazon, and issue malicious smart contracts. These ‘phishing contracts’ stole the victim’s assets by redirecting them to the attacker’s wallet.

    To ensure the BGP hijack would be successful, the attacker needed to make certain its malicious BGP announcements wouldn’t get filtered by an upstream network by taking two steps. First, it managed to insert bogus route objects (shown below) for QuickhostUK in AltDB, a free alternative to the IRR databases managed by RADB and the five RIRs. At this time, it is unclear whether QuickhostUK was also a victim of this attack.

    irrd.log-20220817.gz:31106270-ADD 96126

    irrd.log-20220817.gz:31106280-

    irrd.log-20220817.gz:31106281-as-set:     AS-SET209243

    irrd.log-20220817.gz:31106306-descr:      quickhost set

    irrd.log-20220817.gz:31106332-members:    AS209243, AS16509

    irrd.log-20220817.gz:31106362:mnt-by:     MAINT-QUICKHOSTUK

    irrd.log-20220817.gz:31106392-changed:    crussell()quickhostuk net 20220816

    irrd.log-20220817.gz:31106438-source:     ALTDB

    irrd.log-20220817.gz:31147549-ADD 96127

    irrd.log-20220817.gz:31147559-

    irrd.log-20220817.gz:31147560-route:      44.235.216.0/24

    irrd.log-20220817.gz:31147588-descr:      route

    irrd.log-20220817.gz:31147606-origin:     AS16509

    irrd.log-20220817.gz:31147626:mnt-by:     MAINT-QUICKHOSTUK

    irrd.log-20220817.gz:31147656-changed:    crussell()quickhostuk net 20220816

    irrd.log-20220817.gz:31147702-source:     ALTDB

    Credit: Siyuan Miao of Misaka on NANOG list

    Since network service providers build their route filters using these IRR databases, this step was necessary to ensure upstream networks wouldn’t filter the bogus announcements coming from QuickhostUK.

    Secondly, the attacker altered the AS-PATH of the route so that it appears to be originated by an Amazon ASN (specifically AS14618). This also caused the route to be evaluated as RPKI-valid; more on that later.

    After the hijack in August, I tweeted the following Kentik BGP visualization showing the propagation of this malicious route. The upper portion shows 44.235.216.0/24 appearing with an origin of AS14618 (in green) at 19:39 UTC and quickly becoming globally routed. It was withdrawn at 20:22 UTC but returned again at 20:38, 20:54, and 21:30 before being withdrawn for good at 22:07 UTC.

    Kentik BFP Monitor’s view of the Amazon BGP hijack

    Amazon didn’t begin announcing this identical /24 until 23:07 UTC (in purple), an hour after the last hijack was finished and more than three hours after the hijacks began. According to Coinbase’s timeline, victims had cryptocurrency stolen in separate events between 19:51 and 21:49 UTC.

    Previous BGP hijacks against cryptocurrencies

    The Celer Bridge attack wasn’t the first time that a cryptocurrency service was targeted using a BGP hijack. In April 2018, Amazon’s authoritative DNS service, the former Route 53, was hijacked in order to redirect certain DNS queries to an imposter DNS service, as illustrated below.

    Amazon’s authoritative DNS service was hijacked to redirect certain DNS queries to an imposter DNS service, in April 2018

    The imposter authoritative DNS server returned bogus responses for myetherwallet.com, misdirecting users to an imposter version of MyEtherWallet’s website. When users logged into their accounts (after clicking past the certificate error, ∗sigh∗), the cryptocurrency was drained from their accounts.

    Within a couple of months of this incident, Amazon had published ROAs for their routes including those of its authoritative DNS service. This move enabled RPKI ROV to help offer some protection against such an attack in the future.

    Since public DNS services like Google DNS peer directly with Amazon and reject RPKI-invalids, it would be difficult, if not impossible, to fool Google DNS like this again. If an attacker surreptitiously appended an Amazon ASN to the AS-PATH of its hijack route in order to render it RPKI-valid, it would be unlikely to be selected over the legitimate route from Amazon because of its longer AS-PATH length.

    The BGP hijack against Amazon was not to be the last to target cryptocurrency.

    Earlier this year there was another incident that involved the manipulation of BGP to target a cryptocurrency service. Attackers were able to make off with over USD 2 million in cryptocurrency by employing a BGP hijack against KLAYswap, an online cryptocurrency exchange based in South Korea.

    Henry Birge-Lee and his colleagues at Princeton authored an excellent post on this incident. In this incident, the attackers went after the users of the KLAYswap cryptocurrency exchange by performing a BGP hijack of the IP space of a South Korean hosting provider (Kakao), as illustrated below.

    BGP hijack of Kakao’s IP space. Image credit Henry Birge-Lee

    This is because Kakao was hosting a javascript library that was loaded when users were on the KLAYswap platform. The BGP hijack enabled the attackers to impersonate Kakao and return a malicious version of this library redirecting user transactions to destinations controlled by the attackers.

    So what can be done to protect against BGP hijacks?

    While the incidents discussed above all involved the targeting of cryptocurrency services, the underlying issues are universal and can affect any organization that uses Internet-based services. In order to safeguard against attacks like these, BGP and DNS monitoring need to play a central role in your monitoring strategy. Additionally, strict RPKI configuration can also increase the difficulty for someone to hijack your routes, as I will explain.

    BGP and DNS monitoring

    DNS monitoring exists for the scenario that unfolded with MyEtherWallet in 2018. It uses agents around the world to check that queries for a specified domain return expected results. If a response contains something other than what was expected, it will fire off an alert.

    In the case of last month’s Celer Bridge attack, BGP monitoring could have alerted that a new /24 of Amazon address space was being announced, although the forged Amazon origin may have caused it to appear legitimate.

    However, when this new /24 appeared with an unexpected upstream of AS209243 (Quickhost), that should have triggered an alert drawing attention to this anomaly. The key detail here that would have distinguished this alert from the appearance of just another peer of Amazon would have been that the new upstream was seen by 100% of BGP vantage points. In other words, this new Amazon prefix was getting exclusively transited by this relatively unknown hosting provider. That should have raised some eyebrows among the Amazon NetOps team.

    RPKI ROV

    Amazon had a ROA for the prefix that was hijacked, so why didn’t RPKI ROV help here? It is important to first emphasize that RPKI ROV is intended to limit the impact of inadvertent or accidental hijacks due to routing leaks or misconfigurations. This is because ROV alone cannot prevent a ‘determined adversary’ from forging the origin in the AS-PATH, rendering a malicious hijack RPKI-valid.

    Having said that, it could have still helped if the ROA were set up differently. As it stands, the ROA for the address space in question is quite liberal. Basically, three different Amazon ASNs (16509, 8987, and 14618) can all announce parts of this address space with prefixes ranging in size from a /10 all the way down to a /24. See the output of the Routinator web UI, as shown in figure 4.

    Validation results for 44.235.216.0/24 - AS16509 via the Routinator web UI

    An alternative approach to ROA creation would be to do what other networks such as Cloudflare and Comcast have done — set the origin and maximum prefix length to be identical to how the prefix is routed. While this approach incurs an overhead cost of needing to update a ROA every time a route is modified, it also leaves little room for alternate versions of the route to come into circulation. Another consideration is the propagation time of the RPKI system itself — changes to ROAs take time to propagate around the world and networks only periodically update their RPKI data.

    In its blog post following the June 2019 routing leak by Allegheny Technologies, Cloudflare made the argument that had Verizon deployed RPKI ROV and had been rejecting RPKI-invalid routes, the leak would not have circulated and the impact would have been minimal. As I discussed in my talk at NANOG 78 in February 2020, this statement is only true because the maximum prefix lengths in Cloudflare’s ROAs matched the prefix lengths of their routes. This is not true of many ROAs, including Amazon’s.

    At NANOG 84 earlier this year, Comcast presented the story of how they deployed RPKI ROV on their network. In the Q&A, they confirmed that they adopted a strategy of using automation to maintain exact matches of maximum prefix lengths in their ROAs to avoid this route optimizer leak scenario.

    Had Amazon created a ROA specifically for 44.224.0.0/11 with an origin of AS16509 and a max-prefin-len of 11, then the attacker would have to do one of two things to pull off this attack. One option would be to announce the same route (44.224.0.0/11 with a forged origin of AS16509). This route would have been RPKI-valid but would have had to contend with the real AS16509 for route propagation. Alternatively, if the attacker announced a more-specific route, it would have been evaluated as RPKI-invalid and had its propagation dramatically reduced if not completely blocked given the upstream in this case was Arelion and they reject RPKI-invalid routes.

    Conclusions

    The attacks against cryptocurrency services in recent years highlight universal problems that aren’t restricted to cryptocurrencies. Companies looking to secure their Internet-facing infrastructures need to deploy robust BGP and DNS monitoring of their infrastructure as well as that of any Internet-based dependencies they may have.
    Additionally, companies should reject RPKI-invalid routes while also creating strict ROAs for their IP address space by including maximum prefix lengths that exactly match the prefix lengths used in their routes. In fact, RFC 9319 ‘The Use of maxLength in the Resource Public Key Infrastructure (RPKI)’ states that it is a ‘best current practice’ that networks entirely avoid using the maxLength attribute in ROAs, except in certain circumstances. Leaving the maxLength field blank in a ROA has the same effect as setting the maxLength field to match the prefix. These steps can greatly reduce the window of opportunity for an attacker to subvert your Internet infrastructure.
  • Криптовалюта изнутри или как работают майнеры в интернете

    Криптовалюта изнутри или как работают майнеры в интернете

        Bitcoin напоминает швейцарские механические часы: снаружи четко выполняет задачу, в понимании которой нет ничего сложного. Но если открыть заднюю крышку, то можно увидеть нетривиальный механизм, состоящий из множества шестеренок и прочих деталей. Однако полностью разобраться в том, как все это работает, технически подкованному человеку вполне реально.

        Одно из первых подробных технических описаний Bitcoin на русском было опубликовано в начале десятых годов на Хабре в статье «Bitcoin. Как это работает». Как правильно написано: «У Bitcoin есть такая особенность — чем больше начинаешь в нем разбираться, тем больше возникает новых вопросов. Есть только два выхода —либо разобраться до конца, либо просто научиться пользоваться интерфейсом программы. Иначе не будет покидать чувство, что где-то обязательно должен быть подвох».

    процессинг крипты приносит ощутимый доход операторам bgp mitm площадок

        Что такое криптовалюта? Если кратко, то это децентрализованная валюта с защитой от повторного использования, основанной на достижениях современной криптографии. Идея состоит в том, что каждая транзакция необратима и подтверждается вновь генерируемыми блоками, отвечающими определенным требованиям. Эти блоки вычисляются всем сообществом, объединяются в цепочку и доступны всем для просмотра в виде единой базы данных. Процедура вычисления блоков называется майнинг.

        Сеть построена таким образом, что один блок находится с определенной периодичностью, независимо от вычислительных мощностей, — то есть сложность вычислений саморегулируется. При этом, пока сеть растет, каждый вновь сгенерированный блок содержит еще и новые монеты. В случае с Bitcoin и еще некоторыми видами криптовалют количество монет, которые могут находиться в обращении, ограничено на уровнеротокола, и количество вновь добываемых монет постепенно уменьшается в геометрической прогрессии так, что оно никогда не превысит заданного лимита. Каждый пользователь, который сгенерировал блок, получает фиксированную награду, а также комиссию транзакций, которые он подтвердил, включив их в блок.

        Технология Bitcoin является одним из первых успешных практических решений так называемой задачи о византийских генералах. Кратко она формулируется так: как установить доверие между сторонами, связанными только по каналу связи, которому нельзя доверять? Одним из ключевых моментов в решении служит криптографический метод proof-of-work — те самые «бесполезные» вычисления, которые заведомо должны проводиться долго, но доказательство того, что они были, должно проверяться моментально.

        Bitcoin-клиенты делятся на два вида: толстые/тяжелые (Bitcoin-Qt, Armory) и тонкие/легкие (Electrum, Multibit). Отличие заключается в том, что толстые клиенты для своей работы требуют локальную копию всей базы данных с логом всех транзакций за все время существования сети, а тонкие клиенты выкачивают информацию из децентрализованной сети только по мере необходимости. Для существования сети необходимо наличие в ней толстых клиентов, однако и тонкие клиенты дают возможность полноценно использовать Bitcoin — например, это особенно логично на смартфонах.

        Со временем размер базы данных будет только расти, так же как и емкость носителей информации. Из чего же состоит БД? БД — это блокчейн, цепочка блоков данных в формате JSON. Каждый блок содержит всю необходимую для функционирования сети информацию, свой порядковый номер и хеш-сумму предыдущего блока. Естественно, в самом первом блоке такой хеш-суммы нет. Причем к хешу (шестнадцатеричному числу) выдвигаются строгие требования: он должен начинаться с определенного количества нулей, а если точнее, должен быть меньше специального параметра под названием «bits». Обратно пропорциональный ему параметр называется «сложность». Этот механизм позволяет надежно хранить все прочие необходимые данные в распределенной сети, ведь если изменить хотя бы один символ в блоке, то его хеш изменится целиком и все нули моментально пропадут.

        Что же за вычисления происходят при майнинге и как добиться таких красивых хешей, которые, по сути, являются абсолютно случайными числами? Майнинг — это не что иное, как брутфорс. Брутфорс, который осуществляется не с целью атаки, а с целью защиты. Система такова, что брутфорсить в ней с целью защиты намного выгоднее, чем с целью атаки. Просто потому, что с целью защиты брутфорсит большинство (а на практике все).

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

  • BGP Incidents in July — September 2022

    BGP Incidents in July — September 2022

    Looking at the number of unique BGP route leakers and unique BGP hijackers, it seems that nothing is happening — what is far from the truth. 

    Although the number of unique leakers is almost the same as in the previous quarter — with the difference of only 116 leaking ASes, and the number of unique BGP hijackers grew ⅓ QoQ, we’re getting back to the reality of BGP incidents.

    Remember, here, we are counting the total number and not the unique routing incidents — if one AS originates a route leak, that is distinguished as a separate one by our model — we put it in.

    During July — September 2021 we have recorded 12103554 individual BGP route leaks — the number as high as it was in Jan — March 2022. And the reality is that the number of route leaks jumped back to where it was before the previous, somewhat anomalous quarter. 

    The total BGP hijacks in July — September 2022 were 2545562 — less than 5% of Q2’s astonishing 61M+ hijacks, but as we mentioned, in the previous quarter, the total hijack count was heavily affected by exclusively individual autonomous systems.

    Now, let us look at the global incidents that are part of these statistics through each quarter month.

    Reminder note: our team has a set of certain thresholds that separate global incidents from the rest. They include affected prefixes, affected autonomous systems, and the incident’s distribution among routing tables.

    Global BGP Route Leaks / BGP Hijacks in Q3 2022:

    July: 0 / 1

    August: 3 / 2

    September: 3 / 0

    We analyzes BGP paths data collected from more than 800 sessions, providing analytics and real-time incident monitoring to the registered and authenticated owners of Autonomous Systems. Our team  provides a user with historical data on AS connectivity (links), BGP routing anomalies, and network-related security issues.