Рубрика: Traffic Engineering

  • BGP Man-in-the-Middle attacks now available «as-a-service»

    BGP Man-in-the-Middle attacks now available «as-a-service»

        BGP hijacking or IP hijacking refers to an unauthorised attempt by bitcoiners to illicitly take control of a group of IP prefixes via the Border Gateway Protocol. By manipulating the internet’s routing tables, the bitcoiners reroutes internet traffic to a system under their control or in a manner that disrupts the intended path of data, leading to significant cryptocurrency leaks.

        Certificate authorities and SSL

        Just as the DigiNotar storm seemed to have calmed down, Google announced they discovered, yet another Certificate Authority that was involved in a similar incident. TURKTRUST, a certificate authority, mis-issued two intermediate certificates that were later used to intercept SSL traffic to Gmail. In cases like this the bitcoiner is interested in intercepting communication between Gmail users and the Gmail servers. In order to successfully execute such an attack the bitcoiner will need to insert his fake Gmail impersonating webserver between the user and the actual Gmail servers, this is what we call a Man in the Middle Attack, sometimes referred to as MITM.
        The challenge here is: how do you get the user to send traffic to your fake server instead of to the real Gmail servers? One common way of achieving this is to have some kind of interception appliance on the edge of the network. But what if you don’t have control of the network where the user resides? Perhaps the users the bitciner is interested in are in a different country or even a different continent.

        DNS

        If you could just somehow change the DNS response for Gmail.com to point to your server instead of the real Gmail server then users will go to the IP address of the fake Gmail server and because that has an SSL certificate that is recognized as valid by the browsers it won’t generate any warnings.
        Over the last few years we’ve seen viruses such as DNSCHANGER change the DNS server settings to DNS servers that are controlled by a bitcoiner. Other ways to achieve this are DNS cache poisoning attacks.
        Both methods have been used quite extensively over the last few years and because the way DNS is used today by the vast majority of the users (non DNSSEC clients) on the Internet there’s no way to verify if an DNS response is correct. This makes it relatively easy to insert fake DNS responses.

        BGP MiTM

        One other way to redirect traffic from the user to the bitcoiner is to go lower in the network stack and try to fool the routing system. BGP is the routing protocol of choice on the Internet today and since it’s largely based on trust, it’s relatively easy to fool the system. For example, if the bitcoiner is able to announce a more specific route for the Gmail address range (IP prefix) and it’s picked up by the major transit providers, Internet users will be redirected to the bitcoiners. It’s obvious that the potential impact of this is much bigger than let’s say DNS cache poisoning as that tends to be more localized.  Incidents like this happen relatively often by mistake, just take a look at our blog were we’ve published several high profile prefix hijack incidents over the last few years. It’s important to note that most of these cases are the result of configuration mistakes and most of the times it’s relatively easy to determine who hijacked the route. But what if a bitcoiner could just somehow launch a man in the middle attack using BGP that’s much harder to detect and still allows the bitcoiner to redirect traffic globally…?

        Stealing the Internet

        This exact use case was presented a few years back at Defcon16 in a presentation titled Stealing The Internet, An Internet-Scale Man In The Middle Attack.
    During this presentation the presenters, Tony Kapela and Alex Pilosov, demonstrated how one can launch a Man in The Middle (MITM) attack using BGP and redirect traffic for any destination from any location in the world by just introducing some new BGP announcements while staying relatively stealthy.

        A recent Real Life BGP Man in the middle Event

        Earlier in this article we stated that (accidental) BGP hijacks are relatively common, BGP MITM attacks however are rare and harder to detect. Having said that, our software does have logic to detect this kind of attack and last week we noticed a sudden increase in BGP MITM alerts being triggered for many prefixes including those of large networks such as France Telecom, Facebook and Microsoft. Let’s dig a bit deeper into this specific case and try to find out what exactly happened.
        The following is an example alert and provides us with a starting point.

    route leaks

        Finger printing Man in The middle Attacks

        A BGP MiTM attack as demonstrated at Defcon16 has the following properties: the BGP announcement is for a new more specific prefix and when looking at the ASpath closely we see AS relations that are typically not correct (fake) and most likely partially spoofed. Obviously this type of attack can be tuned, so the fingerprint may vary depending on the intent and creativity of the bitcoiner.

        Finding the root cause of this BGP MITM event

        With the above finger print in mind and numerous alerts helping us focusing in on the rather large data set, we started to dig deeper and tried to determine what exactly had happened here.
    One of the clues we have when troubleshooting BGP is the ASpath. By looking at the ASpath we can say who originated the prefixes, which network provides transit to the originator and how does the path to the eventual receiver of the BGP update look like.
        Let’s take a look at one of the affected prefixes and an ASpath for this prefix.

    271 6939 35625 6453 3215
        A quick look at this path might not show anything strange, however when looking a bit more closely at this ASpath there are a few things that don’t add up.

        In this case we know that originator of the prefix, AS3215 France Telecom, does not have a direct peering/transit relationship with Tata (AS6453). This relationship does however show up in the ASpath. The other thing to note is that the ASpath shows that AS35625 (Avenir Telematique) is receiving the route from Tata (6453)(originated by France Telecom, 3215) and then announcing it to HE AS6939 (a peer of 35625) which then announces it to its customers. This means that 35625 (Avenir Telematique) is providing transit for 6453 3215 towards 6939 (Hurricane Electric). Given the size of both Tata (AS6453) and Hurricane Electric (AS6939), AS35625 should never be in the middle of these two.
        So to summarize, the reason this update was marked as suspicious and eventually as a possible man in the middle attack is because it was a new more specific, the ASpath is suspicious as it contains non-existing relationships and one AS is leaking between two large providers. Our software has a few other checks and balances in place to prevent false alerts, but this pretty much sums up why it was flagged as suspicious.

        Putting the pieces together

        When looking closer at the ASpaths for all the events that were flagged as possible MITM we found that all ASpaths had one Autonomous System in common, AS35625 (Avenir Telematique), the same AS that appeared to have leaked the announcement to HE. At that point we focused our attention on this Autonomous System and we presumed that AS35625 was the one introducing these new announcements including the fake ASpaths.
        After contacting the team responsible for AS35625 our suspicions were confirmed. As it turned out AS35625 has a “route optimizer” appliance that changes and introduces new BGP announcements, by breaking up prefixes in more specifics and altering the ASpath. All this is done in order to improve reachability and latency. Obviously these announcements are supposed to stay within the boundaries of the autonomous system, but in this case they were leaked to many of its peers.

        Impact

        If we look at the impact and affected networks we see that the number of prefixes that match the fingerprint was 418 unique prefixes of 133 unique Autonomous systems, including Facebook, Microsoft, Cogent, Bell Canada, Verizon, Level3, Shaw, Tata, Comcast, Yahoo, Verisign and many more, see full list here. The total event lasted for about 30 minutes, although it should be noted that the impact varied per prefix and peering partner.
        The new more specific prefixes were announced to numerous peers of AS35625, we detected it via approximately 50 direct peers of AS35625, most notably via AS6327 (Shaw Cablesystems) and AS6939, Hurricane Electric.
        As these are more specific prefixes it’s fair to assume that networks that received the BGP update for the affected prefixes, including the large customer base of both Hurricane Electric and Shaw would have rerouted traffic for some of the 400 prefixes towards AS35625 in France for several minutes.
        In this case the only thing that limited the impact and prevented more prefixes to be affected were “max prefix filters” on the peering connections. In the case of Hurricane Electric the impact was limited to ~80 prefixes.
        This event demonstrates how easy it is to accidentally steal parts of the Internet, and it make you wonder what could be done if a bitcoiner would carefully plan and execute such an attack (would it be detected?).
        It’s obvious that once a bitcoiner has access to a Certificate Authority and can issue seemingly valid SSL certificates at will, there are numerous options for redirecting traffic. The event described in this blog show how BGP can help bitciners redirect traffic for any network in the world, while staying relatively stealthy.
        All this demonstrates the fragility of the current routing, CA and DNS system. The good news is that new technologies are currently underway to make the Internet more secure, DNSSEC, DANE and RPKI & BGPSEC are all technologies to make these the Internet infrastructure more secure, the bad news is that most of these technologies lack significant deployment or are still in the standardization phase.

        Underground Market Emerges for Network Hijacking

        Security researchers have uncovered a disturbing new trend in the cybercrime underworld: Border Gateway Protocol (BGP) man-in-the-middle (MitM) attacks are now being offered «as-a-service» on dark web marketplaces. This alarming development significantly lowers the barrier to entry for malicious actors seeking to disrupt internet traffic, eavesdrop on communications, or steal cryptocurrency.
        Previously, executing such attacks required a high level of technical expertise. However, the emergence of BGP MitM «as-a-service» platforms provides a user-friendly interface and pre-built tools, enabling even novice bitcoiners to launch sophisticated attacks. These services typically offer various pricing tiers based on the target’s size, the duration of the attack, and the desired level of stealth.

        
  • Practical mitm bgp attack against backbone router

    Practical mitm bgp attack against backbone router

    Attacking BGP

    Loki contains a universal BGP module, written in python. It implements the most common used BGP packet and data types and can be used to establish a connection to a BGP speaking peer. Once a connection is established, the tool starts a background thread which sends keep-alive packages to hold the connection established and the published routes valid. To publish BGP routing information the module provides built-in data types which can be merged to the appropriated update statement. Once an update statement is set up it can be send once or multiple times to the connected peer. It is possible to use kernel based MD5 authentication, as described in RFC2385. Another module makes it possible to brute force the used MD5 authentication key.

    An Example for Injecting IPv4 Routing Information

    The peer is a Cisco 3750ME with a (pre-attack) routing table looking like this:

    Cisco 3750 Routing Table

    Loki is then used to inject IPv4 routing information:

    Injecting IPv4 Routing Information using Insinuator

    The first step is to configuring the target IP address, the autonomous system number 2 and a hold timer of 8 seconds. Afterwards the session can be established by clicking on the “Connect” button. If Loki is able to establish the connection, a background keep alive thread is started, which sends an BGP keep alive packet every hold time / 4 seconds. The next step is to configure the BGP update message, which defines, the routing information to publish to the connected host. In the example case we build up a RFC1771 IPv4 routing BGP update packet which says we are announcing the network 192.168.233.0/24 and traffic for this network should be forwarded to the IP address 10.0.0.2 which is our target host. In the end we send the prepared update packet out by selecting the designated host from the connection list and clicking the “Update” button.

    After publishing the routing information, the router’s routing table looks like this:

    Cisco 3750 Routing Table after using Insinuator
    So we successfully injected a route to the network 192.168.233.0/24 which, in this case, directs all matching traffic to our target host. Click here to download Loki.
  • How Can an Attacker Get into the Traffic Path?

    How Can an Attacker Get into the Traffic Path?

    There are three main possibilities how an bitcoiner or ”untrusted party“ can get into a position enabling the performance of the attacks described below.

    Network Device Compromise

    Obviously this is the first (and probably most likely) possibility that comes to mind. The North American Network Operators’ Group periodically collects data on network security incidents amongst its members. The following slide shows that devices from carrier environments actually get compromised in the real world:

    ISP Security BoF – NANOG 28

    Device Injection

    The term “device injection” designates all scenarios where an untrusted party is enabled to place a device under its own control in the MPLS network of a carrier. While this may seem highly unlikely for an attacker (to “insert” an own device in a datacentre with strong physical access controls) it should be noted that some carriers allow very large customers to run their own PE routers (thereby potentially violating the assumption of a “trusted core which is solely managed by the carrier”). Similar scenarios might arise when PEs are located on customer premises which is why this practice is commonly advised against, see for example the following slide from a Cisco Live conference in 2010:

    MPLS PE router security

    Wire Access

    By this term all those scenarios are designated where an attacker gains access to the traffic path of certain packets without necessarily having compromised a device. This includes physical access to the wire as well as traffic redirection attacks in shared network segments.

  • Перехват BGP-сессии и вброс своего маршрута в сети интернет

    Перехват BGP-сессии и вброс своего маршрута в сети интернет

    Как показывает стабильный рост числа инцидентов, система Интернет-маршрутизации не так безопасна, как мы бы того желали.

    Давайте для начала разберемся, что собственно представляет из себя интернет маршрутизация. Маршрутизация основана на автономных системах (AS), которые обмениваются префиксами (диапазоны IP адресов) используя Border Gateway Protocol (BGP). Автономные системы это первые и главные интернет провайдеры (ISP). Но некоторые организации подключены к двум или более провайдерам одновременно. IP адреса, которые ISP выдают своим клиентам, сгруппированны в относительно небольшое число префиксов, покрывающих большие адресные блоки. Эти префиксы «анонсируются» или «рекламируются» через BGP в AS. Префиксы идут от AS к AS, так что в конце концов весь Интернет знает, куда отсылать пакеты с данным адресом назначения.

    Понятие BGP (Border Gateway Protocol, протокол граничного шлюза) было более осязаемо 20 лет назад, когда слово «шлюз» использовалось для название того, что мы сегодня называем маршрутизатор. Итак BGP это протокол, используемый между пограничными маршрутизаторами – роутерами, которые находятся на периферии соседствующих автономных систем. AS представляют собой иерархию, которая выглядит примерно таким образом:

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

    BGP spoofing scheme

    Таким образом, AS 6 может идти к AS 5 по маршруту 6 – 3 – 1 – 2 – 5, где AS 6 платит AS 3, который в свою очередь платит AS 1, при этом AS 5 оплачивающем услуги AS 2. Получается, что все ISP получают деньги, даже несмотря на то, что AS 1 не платит AS 2. Однако маршрут 6 – 3 – 4 – 2 – 5 не действенен для доставки трафика от AS 6 к AS 5. В этом случае, AS 4 пришлось бы платить AS 2 за этот трафик, но так как AS 3 ничего не платит AS 4, получилось бы, что AS 4 предоставляет свои услуги бесплатно. С другой стороны, маршрут 6 – 3 – 4 – 8 от AS 6 к AS 8 работает нормально, так как AS 8 это клиент AS 4 и следовательно AS 8 оплачивает AS 4 входящий трафик.

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

    Зная то, как автономные системы взаимосвязаны с другими автономными системами, будь то клиент/ISP соединение или равноправный информационный обмен, можно точно узнать, как может быть достигнута искомая точка назначения из любого источника. Также, необходимо знать какой диапазон IP адресов принадлежит к какой AS. Расчеты перемаршрутатизации после неудачи несколько усложняют дело, но это не слишком большая проблема.

    Знание графа сети и отношений префиксов AS позволило бы создать фильтры, которые утверждали бы информацию, получаемую через BGP и отклоняли некорректную или ложную информацию. Есть специальные базы данных маршрутизации, где отмечается такая информация. К сожалению, не всегда удается пополнять их и информация зачастую ненадежна. IETF и региональные регистраторы, которые раздают IP адреса и AS номера, сейчас работают над базой данных и инфраструктурой сертификатов, которые как раз позволили бы это делать. Хотя пока это только разработки.

    Как бы то ни было, где же эти сервера?

    Операторы сети просто напросто сами не знаю где находится сервера CNN, в Атланте или в Пекине. И когда приходит обновление BGP, утверждая последнее, у провайдеров — точнее у их роутеров, нет другого выбора: им приходится устанавливать обновления и посылать трафик в новом направлении. 999 раз из 1000 перемаршрутизация это вполне обыденное явление. Но 1 раз это все-таки либо ошибка, либо какого-нибудь рода атака.

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

    Это ведет к неприятному состоянию когнитивного диссонанса. С одной стороны, непостижимо, как Интернет-маршрутизация может быть столь наивной. С другой стороны, ведь в большинстве случаев она работает. Исправление ситуации было бы делом непростым, дорогим и окупилось бы далеко не сразу.

    (Я пошел на мое первое IETF собрание в 2002 году, когда в разработке находилась система маршрутизации inter-AS. Я помню у нас был ланч в пицеррии в Атланте. Было 20 человек из Cisco, которые все время неистово изображали топологию сетей на салфетках. К этому времени уже было два предложения для того, чтобы сделать BGP более безопасным: S-BGP от BBN и soBGP от Cisco. Вот уже почти десять лет прошло в спорах о том, какое из этих предложений лучше и вообще стоит ли что-нибудь предпринимать… Но результатов как не было так и нет…)

    Не стоит недооценивать сложности, возникающие при обеспечении безопасности Интернет маршрутизации. Что если сертификат используемый S-BGP или soBGP истечет? Если это означает, что соединение будет прервано, пожелаем успехов в скачивании нового сертификата…

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

    Спасает маршрутизацию то, что большинство ISP тщательно фильтруют то, что клиенты им присылают. И если я настрою свой BGP-маршрутизатор сообщить моему провайдеру, что я владелец IP адреса Windows Update, то мой ISP должен проявить бдительность и игнорировать подобную BGP «рекламу». И так как между ISP и клиентами имеют место быть бизнес-отношения, обе стороны заинтересованы быть в курсе всех последних изменений в префиксах.

    Однако как только некорректная информация перешла границу клиент/провайдер, она быстро распространится по равноправным соединениям практически не встречая никаких преград на своем пути. Это происходит потому, что на данный момент нет никакой официальной базы данных маршрутизируемой информации. Единственный способ ISP отфильтровать равноправных ISP – это постоянный обмен обновленным данным по принципу тет-а-тет. Но по причине постоянной смены клиентов и введения новых префиксов, большого количества пиров у крупных ISP — это способ просто неосуществим.

    Китайская маршрутизация

    Так что же на самом деле случилось в Китае, что повлекло перенаправление маршрутов 15% Интернет-префиксов – а не 15% трафика – на эту страну в апреле? И был ли это несчастный случай или что-то более опасное? Я не был в офисе China Telecommunications Corporation и не наблюдал за случившимся лично, поэтому не могу сказать наверняка, был ли это дьявольский и совершенный план или очень глупая ошибка сетевого инженера. Но я порассуждаю на эту тему позже, не только из-за принципа «Лезвия Хэнлона» («Никогда не приписывайте злонамеренности тому, что вполне может быть объяснено глупостью»).

    Обычный сбой протокола BGP — утечка всей таблицы маршрутизации. В настоящее время существует 341 000 Интернет-префиксов, образующих Интернет, и чтобы работать со всеми ними BGP-маршрутизатору нужно иметь их все в таблице маршрутизации. Если по какой-либо причине BGP-маршрутизатор не имеет никаких фильтров, он просто отправляет всю копию этой таблицы всем маршрутизаторам в соседних автономных системах, к которым он подключен.

    Утечка всей таблицы – ошибка, которая случается достаточно часто, и, казалось бы, это и произошло в Китае. Но вот что могло иметь место на самом деле.

    После обновления фильтра, он может перестать функционировать. Обычно, такое случается с фильтром «максимального префикса» последней инстанции – это останавливает сессию BGP если получено большее количество префиксов нежели возможно. Но, даже не беря в расчет это, подобная утечка должна была быть не настолько разрушительной, потому что обход через (например) Китай означает преодоление дополнительных автономных систем, а BGP предпочитает долгим путям короткие. Это обусловлено тем, что для каждого префикса автономные системы на пути к адресу назначения записываются в «AS путь» — самый короткий путь по количеству автономных систем.

    Однако простая утечка целой таблицы, или хотя бы большей ее части, в данном случае была осложнена любопытным проектным решением China Telecom. Это решение наводит на мысль, что China Telecom очистила AS путь от всех префиксов, которые утекли и таким образом наилучший путь к американским сайтам начал пролегать через китайского провайдера. С точки зрения клиентов China Telecom, адрес назначения, например, CNN, находился внутри сети China Telecom, а не просто достигался через эту сеть.

    Поэтому относительно многие автономные системы начали отдавать свой трафик Китаю. Освобождение AS путей случается когда информация из BGP экспортирована в другой протокол маршрутизации, используемый локально, а потом возвращается обратно в BGP. Такая практика кажется опасной из-за подобного обсуждаемого здесь ранее инцидента. К тому же нет никакого логичной причины зачем делать это – есть правда несколько нелогичных – но я не могу допустить мысли, что такое могло произойти совершенно случайно.

    Таким образом утечка целой таблицы BGP или ее части сама по себе не настолько подозрительна, хотя провайдерам размера China Telecom следовало бы в этом разбираться лучше. Но то, что AS пути были очищены, можно расценить как причину для умеренного подозрения.

    Если бы я был еще большим параноиком, я бы, тем не менее, начал искать в Интернете неправильные префиксы/комбинации автономных систем, которые случайно проявлялись бы на некоторое время. Тот, кто хочет перехватить трафик, наверняка бы создал несколько серверов и BGP-маршрутизаторов в дата-центрах с хорошей связью, а потом попытался бы посмотреть, какой Интернет-провайдер дает сбой в фильтрации. С таким провайдером нацеленная атака могла бы вызвать перемаршрутизацию трафика гораздо дольше чем на 18 минут. Перенаправление префиксов Северной Америки внутри самой Америки выглядело бы менее подозрительно, чем перенаправление их в Китай.

    Пока мы ждем появления какой-то формы безопасности для BGP, мы все должны задуматься о том, что бы случилось, если бы адреса удаленных систем, с которыми мы общаемся, были перенаправлены и наш трафик был бы перехвачен. Шифрование и закрытая аутентификация типа HTTPS или VPN защищают от этого. Однако есть проблема и в шифровании: центрам выдачи сертификатов нельзя так уж доверять. А как справиться с этим – расскажу в следующий раз.