Блог

  • 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 attacker or ”untrusted party“ can get into a position enabling the performance of the attacks described above.

    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 hijacking from within the Carrier or Cloud Service

    BGP hijacking from within the Carrier or Cloud Service

    Relabeling Attack

    Loki can be used to relabel 802.1Q tagged packets on the fly. Once an attacker is in the traffic path all seen 802.1Q communications are listed in the dot1q module. To rewrite a label in transmission between two hosts, it simply needs to be selected to fill in most of the fields for the rewrite rule. Only the target label and an optional tcpdump filter to match specific data streams need to be added. Once the rule is added a background thread takes care of the relabeling.

    Relabeling attack with Loki on L3VPN MPLS

    Modifying Q-in-Q on MPLS Network

    The dot1q module in Loki can also be used to rewrite the inner 802.1Q label used in Q-in-Q scenarios in the same way as when rewriting the outer 802.1Q label.

    Modifying Q-in-Q with Loki on MPLS Network

    Network Behaviour with Security Impact, Resulting from Unified Layer2 Network

    If several sites form a common Layer2 domain after connecting them (mainly in “full transparency” cases), some interesting settings – with potentially huge security impact – can emerge. For example there might only be one Spanning Tree Root in the whole (then world wide) L2 network (or one per VLAN). Combined with the fact that some sites may even implement redundant links to the carrier network the following scenario might follow:

    MPLS Network sample

    Here the network traffic resulting from Bob’s access to the fileserver with actually be forwarded to New York and back to Amsterdam (as the link between the switches in Amsterdam is in blocking state), effectively passing the MPLS backbone (possibly unencrypted). Moreover Bob (or the site’s or the company’s security officer) might be completely unaware of this situation.

    Another example of (at the first glance) “unexpected” network behaviour is shown in the following diagram:

    L3VPN on MPLS Network

    With a fully transparent Intra-Site Ethernet connection the switch in New York will propagate it’s VLAN table to the switches in Amsterdam effectively melting down the complete network over there.

    Full transparency with regard to VLANs might impose another risk, shown in the following diagram: “VLAN visibility across the cloud”:

    VLAN visibility across the cloud

    Members of VLAN 10 in Paris (“wlan”) might be able to communicate with members of VLAN 10 in Amsterdam (“servers”)8, without notice or awareness of the sysadmins in Amsterdam. This is another example of the effects a fully transparent connection may have.

    Traditional Layer2 Attacks from One Site to Another

    It should be explicitly noted that – in a such a “unified Layer2 network” – the impact of a system compromise in one site may lead to Layer2 attacks against other sites (e.g. attacks against DTP with subsequent sniffing of remote VLANs with yersinia). Previously such attacks mostly probably were not possible.

    Misconfigurations on the Carrier Side, leading to Security Breaches of/within Customer Network

    If, for instance, the carrier is expected to provide “partial transparency” but actually “full transparency” is implemented (due to operational deficiencies and/or human error), security problems (like those depicted above) may arise.

    Another example (which in fact happens) is the accidental connection of sites belonging to different customers or leakage of routing information due to typos in the VRF/VFI identifiers.

    Misconfigurations on the Customer Side, leading to Breaches

    In “full transparency” scenarios diligent configuration of the customer’s network devices might be necessary to avoid security problems as discussed above. Bad operational practice or human errors may easily lead to severe problems here.

    Product or Technology Change on Carrier Side may lead to different Level of Transparency

    If the customer is unaware of the exact behaviour of the carrier’s Ethernet service at one point and “just doesn’t notice any problems”, a technology change (be a change of device firmware to a newer version, be a change of an infrastructure protocol’s configuration) may lead to security exposure. A well known historical example was the (mostly unannounced) introduction of a proprietary OSPF enhancement called Link Local Signaling in Cisco’s IOS which effectively broke OSPF sessions with (customer) Nokia devices after (carrier) IOS upgrades some years ago.

    Inconsistent Transparency Level amongst “Carrier Ethernet” Product(s) from one Vendor

    Carriers offering a nation- or even world wide Ethernet service may technologically implement the product in different ways, depending on the distance between sites (“Metro Ethernet” in case of regional offices, VPLS if far distance between sites). The different technologies may behave differently then as for the level of transparency.

  • Attacking MPLS Provider Edge

    Attacking MPLS Provider Edge

    The another Loki‘s usage case shows how to inject MPLS-VPN routing information (as described in RFC4364) into a MPLS Provider Edge router.

    The peer again is a Cisco 3750ME with a MPLS-VPN virtual routing and forwarding table associated with the customer ‘RED’:

    Cisco 3750 MP-BGP Routing Information

    Loki is then used to inject the MPLS-VPN routing information:

    Injecting MPLS-VPN Routing Information with Loki

    Before setting up the session we need to overwrite the default session parameters with our custom BGP capabilities. This is done by filling in the optional connection parameters.

    Next the AS number and the hold timer needs to be set. At last the target host is missing, which in this example is the host with the IP address 10.10.10.1. After clicking on “Connect” a session setup is performed.

    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 assigns the BGP update message. 

    This message defines, which routing information to publish to the connected host. In the example case we build up a RFC4364 Multi-Protocol-BGP update packet, which says we are announcing the network 192.168.113.111/32 with the route distinguisher 100:0, which should be forwarded to the next hop 10.10.10.10. In the end we send the prepared update message by clicking on “Update”.

    After publishing the routing information, the routers virtual routing and forwarding table for the customer ‘RED’ looks like this:

    Cisco 3750 MP-BGP Routing Information after using Loki

    One can see the new route for the host 192.168.113.111 pointing to our attack host (10.10.10.10). Click here to dowload Loki.

  • Attacking LDP

    Attacking LDP

    The Label Distribution Protocol, initially specified in the RFC 3036, is a signaling protocol for distributing labels for a label switched path in an MPLS network. In 2007 RFC 5036 was released and replaces the old specification. LDP serves a set of procedures and messages by which Label Switched Routers (LSRs) establish Label Switched Paths through a network by mapping network routing information to data-link layer switched paths. The procedures consist of four kind of functions: discovery functions, session management, advertisement and notification.

    Trust Model

    LDP uses TCP to establish sessions between two LSRs. UDP is used for basic operations like discovery mechanisms which are periodically sent over the network to a well-known discovery port for all routers of a specific subnet. As these are sent to the “all routers on this subnet” group multicast address, with regard to the discovery process all routers on the local link are regarded trustworthy.

    Security Controls Inherent to Technology

    To protect the authenticity and integrity of LDP messages, LDP supports the TCP MD5 signature options described in RFC 2385. It has to be activated at the LSRs and may protect the messages by validating the segment by calculating and comparing the MD5 digest. To use the MD5 option a preconfigured password on each LSR is necessary.

    Attacking LDP

    Loki contains a universal LDP module, written in python. It implements the most common used LDP packet and data types and can be used to participate in the LDP discovery process, as well as establish targeted LDP sessions for advanced signaling. If such a targeted session is established, the tool starts a background thread which sends keep-alive packages to hold the connection open and the signaled data valid. To create such signaling data e.g. EoMPLS virtual circuits signaling, the module provides build-in data types which can be merged to the appropriated signaling packet.

    An Example for signaling EoMPLS virtual circuits

    The peer is a Cisco 3750ME was configured, but not activated virtual circuit:

    Cisco 3750ME was configured, but not activated virtual circuit

    Loki is the used to establish an LDP session and to send the necessary signaling information:

    establishing the LDP session with Loki

    First Loki needs to take part in the LDP discovery process; this is done by activating the Hello-Thread via clicking on the “Hello” button. Next the remote host tries to connect the attacks host via TCP, so Loki needs to listen for that incoming connection; this is done by activating the Listen-Thread via clicking on the “Listen” button. Once the Connection is established, the remote Host will show up in the Host-List. The next step is to configure the LDP update message, which defines the signaling message to publish to the remote host. In this case we generate a LDP Label-Mapping-Message. In the end we send the prepared update message by selecting the designated host from the host list and clicking on the “Update” button.

    After sending the LDP Label-Mapping-message the configured virtual circuit is activated on the remote side:

    After sending the LDP Label-Mapping-message the configured virtual circuit is activated on the remote side

    So we activated the virtual circuit and mapped it to a label defined in the update message. A tool like mplstun could be used to set up a valid endpoint on the attacker’s side. Click here to download Loki.

  • О подмене маршрута в зоне bgp в процессинге фиата и крипты

    О подмене маршрута в зоне bgp в процессинге фиата и крипты

    Перво наперво стоит провести анализ транзитного сетевого трафика с помощью любого сетевого анализатора в «неразборчивом» режиме работы сетевой карты (promiscuous mode). В качестве сетевого анализатора для подобных целей замечательно подходит WireShark или CommView. Чтобы выполнить этот этап, хватит и пары часов работы сетевого анализатора. По прошествии этого времени накопится достаточно данных для проведения анализа перехваченного трафика. И в первую очередь при его анализе следует обратить внимание на следующие протоколы:
    • протоколы коммутации (STP, PVST+, CDP, DTP, VTP, и им подобные)
    • протоколы маршрутизации (RIP, BGP, EIGRP, OSPF, IS-IS и другие)
    • протоколы динамической конфигурации узла (DHCP, BOOTP)
    • открытые протоколы (telnet, rlogin и подобные)
    Что касается открытых протоколов, – вероятность того, что они попадутся во время сбора пакетов проходящего мимо трафика в коммутируемой сети, достаточно мала. Однако, если такого трафика много, то в обследуемой сети явно наблюдаются проблемы в настройках сетевого оборудования.
    Во всех остальных случаях присутствует возможность проведения красивых сценариев:
    • классическая MITM (Man in the middle) в случае, когда используется DHCP, RIP
    • получение роли корневого узла STP (Root Bridge), что позволяет перехватывать трафик соседних сегментов
    • перевод порта в магистральный режим с помощью DTP (enable trunking), позволяет перехватывать весь трафик своего сегмента сети
    Для реализации этих сценариев взаимодействия с сетевыми протоколами коммутации доступен замечательный инструмент Yersinia.

    Предположим, что в процессе анализа трафика были выявлены пролетающие мимо DTP-пакеты (смотри скриншот). Тогда отправка пакета DTP ACCESS/DESIRABLE может позволить перевести порт коммутатора в магистральный режим. Дальнейшее развитие этого сценария позволяет прослушивать весь свой сегмент этой сети.

    использование Yersinia для реализации mitm сценария
    После тестирования канального уровня стоит переключить внимание на третий уровень модели OSI. Дошла очередь и до проведения сценария взаимодействия через ARP-poisoning. Тут все просто, выбираем инструмент Ettercap NG. Все дело в том, что в случае успешной реализации сценария ARP-poisoning в отношении всего своего сегмента сети может наступить ситуация, когда MiTM компьютер по середине не справится с потоком поступающих данных и, в конечном счете, это может стать причиной отказа в обслуживании целого сегмента сети, что обязательно заметят. Поэтому наиболее правильным будет выбрать единичные цели, например, рабочие места администраторов и/или разработчиков, какие-либо определенные серверы (возможно контроллер домена, СУБД, терминальный сервер, bgp-маршрутизатор и другие важные элементы сети).
    Успешно проведенная ARP-poisoning позволяет получить в открытом виде пароли к различным информационным ресурсам – СУБД, каталогу домена (при понижении проверки подлинности NTLM), SNMP-community string, bgp пакеты UPDATE, пароли для сетевого оборудования с уровнем доступа level 15 и другие приятные вещи. В менее удачном случае могут быть получены хеш-значения от паролей к различным системам, которые нужно будет постараться восстановить по радужным таблицам (rainbow tables), по словарю или методом «в лоб». Перехваченные пароли могут использоваться где-то еще на других сайтах в сети интернет, но впоследствии это также необходимо подтвердить или опровергнуть.
    Кроме того, стоит проанализировать весь перехваченный трафик на присутствие CAV2/CVC2/CVV2/CID/PIN, передаваемых в открытом виде. Для этого можно пропустить сохраненный cap-файл через NetResident и/или 0x4553-Intercepter. Второй, кстати, замечательно подходит для анализа накопленного трафика в целом.

    Встраивание в уже созданную BGP сессию и реализация bgp hijacking

    Сразу стоит обозначить результат — поменять маршруты движения трафика, но не управлять каким-то bgp-роутером через консоль, то есть не проникая в его систему управления от слов совсем и никак, просто модифицировать данные его таблиц маршрутизации. Для этого используется обычная реализация IP Spoofing + TCP hijacking = BGP Spoofing сценария для того, чтобы перенаправить все общение между двумя роутерами через свой хост, то есть осуществление полного перехвата и фильтрации BGP-сесий этих роутеров. Об инструментах, которые позволяют сделать это внутри транзитной сети поговорим немного позже.

    Реализация BGP spoofing сценария через консоль роутера

    После того, как был получен доступ к bgp-роутеру, крнечный результат реализации сценария bgp-hijacking будет зависеть от настроек его bgp-соседей. Есть вероятность, что этому bgp-роутеру доверяют все его bgp-соседи, а им — их bgp-соседи и так далее, так можно незаметно поменять пути маршрутизации и сделать bgp-обход целых сетевых сегментов, манипулируя при этом огромными объемами сетевого трафика в Интернет. 
    А возможно, что через этот bgp-роутер можно будет изменить пути только в сети, в которой он сам и находиться или в автономной системе этого bgp-роутера, но и это на самом деле не такой уж и плохой результат, даже если сеть или Автономная Система небольшие.

    Для начала надо определить, из каких AS у нас наиболее вероятен перехват трафика, а это, как правило, соседние AS относительно той, в которой находиться BGP-роутер. Принадлежность определенного IP к AS и соседи определенной AS могут быть получены различными сервисами, например, тот же ipinfo.io либо простым выполнением команды show ip bgp neighbors на роутере. 

    Еще есть интересные сервисы, такие как asnmap.com или bgplay от RIPE. Интерфейс BGP роутера — консоль с ограниченными, определенными командами для управления и конфигурирования текущего BGP демона или устройтсва и некоторых прилагающихся сетевых сервисов. То есть попав на этот интерфейс можно в реальном времени без каких-либо перезапусков и перезагрузок менять конфигурацию bgp-демона или устройства, хотя если попасть в файловую систему роутера, то можно и поменять конфигурацию с его перезапуском.

    Так всё таки, какой сценарий выбрать для понимания bgp в крипте?

    Эксплуатация уязвимостей протокола BGP в контексте криптовалют и блокчейнов — это довольно специфическая область, которая требует углубленного изучения. Давайте разберемся, какие сценарии могут быть наиболее востребованы в контексте процессинга крипты. В сети блокчейнов первого уровня маршрутизация между нодами использует протокол BGP для установления соединений между ними через Интернет, например, Bitcoin или Ethereum. Новые блоки, содержащие транзакции, также распространяются по сети Интернет при помощи BGP, и оно играет важную роль в синхронизации состояния всего блокчейна. BGP помогает поддерживать согласованность состояния блокчейна между всеми нодами. 
    Децентрализованные биржи (DEX) также осуществляют обмен ордерами при помощи BGP и стабиьность его работы влияет на эффективность маршрутизации ордеров между различными DEX. Обеспечение ликвидности: BGP может помочь в распределении ликвидности по различным пулам. 
    Так какой же сценарий выбрать?

    Выбор конкретного сценария зависит от ваших целей.  Если вы новичок и только начинаете изучать BGP в контексте криптовалют, то лучше начать с простых сценариев, таких как маршрутизация в сети Bitcoin и управление bgp-роутером через консоль. Но для этого Вам предстоит сначала найти этот роутер и получить к нему доступ ранее озвученными методами, включая пример на видео. 

    Если вы уже разрабатываете блокчейн-приложения, то вам будет полезно изучить, как BGP используется для масштабирования и создания децентрализованных сетей. Тажке если вы занимаетесь администрированием блокчейн-инфраструктуры, то вам необходимо понимать, как BGP используется для обеспечения надежности и доступности сети. BGP — это сложный протокол, и его полное понимание требует времени и усилий. Начните с простых концепций и постепенно углубляйтесь в более сложные темы. Для воздейтвия на таблицу маршрутизации bgp-роутера без доступа в его консоль вам понадобится специализированное программное обеспечение, например ciag-bgp-tools-1.00.tar.gz или Insinuator (ex loki).
    ARP сканирование с помощью loki

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