One place for hosting & domains

      An Explanation of BGP Networking


      Routing protocols are crucial for proper network engineering and design. They allow traffic to be quickly routed across a network from source to destination. The
      Border Gateway Protocol (BGP) is the universally-accepted routing protocol for the internet backbone. Although BGP is incredibly powerful and has many advantages, it is also complex and has some drawbacks. This guide explains what BGP is and how BGP routing works. It also discusses the advantages and disadvantages of BGP and its role in many recent major network outages.

      What is the BGP Protocol?

      BGP is designed to quickly route traffic from source to destination across the entire internet. It enforces the use of standardized routing messages and practices that are shared between each internet service provider (ISP). For each packet, BGP determines the best route to the final destination. It then transmits the message using the appropriate interface. This process is repeated at every node along the route until the packet arrives at its destination. BGP routing information is exchanged between connected neighbor interfaces, which are called peers. Large ISPs must use BGP to connect to the internet backbone, but smaller networks might also choose to deploy it internally.

      BGP was first roughly sketched out in 1989 and initially deployed in 1994. It quickly became the de facto standard for routing traffic across domains. The current version of BGP is version 4 (BGP4), and its specification is described in
      RFC 4271. The current implementation corrects some errors and ambiguities, and introduces support for Classless Inter-Domain Routing (CIDR) and route aggregation. There is also a BGP implementation for IPv6 as first described in
      RFC 2545, along with several extensions and optimizations.

      BGP is an example of an exterior gateway protocol, as opposed to an interior gateway protocol. Exterior gateway protocols connect large autonomous systems (AS), which might represent an internet service provider (ISP) or an application provider like Netflix. Interior gateway protocols, including Open Shortest Path First (OSPF) and Intermediate System to Intermediate System (ISIS), can only be used inside a single AS. BGP is said to create a “network of networks” out of the different autonomous systems.

      Each AS is allowed to choose its own interior gateway protocol but requires a shared mechanism for sending traffic to another system. BGP provides a successful solution, and virtually all providers now use it to reduce interoperability problems. Consequently, BGP is the only remaining exterior gateway protocol in widespread use.

      BGP constructs routing tables describing the next hop and interface for each external network. The networks are defined based on their IP address and network mask. For instance, the network 192.0.2.0/24 might have its own entry in the BGP routing table. Any traffic to any address in this subnet is routed the same way. BGP is considered a vector protocol. It considers each route to be a sequence of autonomous systems to transit and not a series of hops. BGP also provides a mechanism to add, delete, and change information from the routing table.

      BGP uses the Transmission Control Protocol (TCP) as its transport mechanism. It is officially assigned TCP port 179. TCP provides a reliable connection, packet retransmission, and fragmentation/reassembly services. This eliminates any requirement for BGP to implement these features. Each BGP message contains a header consisting of a marker field of all ones, the message length, and the BGP message type.

      How does a BGP Session Work?

      BGP is responsible for receiving and transmitting network updates and constructing a routing table from these updates. A BGP interface establishes a point-to-point connection with its BGP peer, which is a neighboring interface. Peering information for each BGP interface is configured manually and used when negotiating the connection. The configuration must include the expected AS and IP address of the BGP peer. The following example demonstrates how to configure a BGP session on a Nokia 7750 router.

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      
      group "To_AS_30000"
          connect-retry 20
          hold-time 90
          keepalive 30
          local-preference 100
          remove-private
          peer-as 30000
          neighbor 10.0.3.10
              description "To_Router C - EBGP Peer"
              connect-retry 20
              hold-time 90
              keepalive 30
              peer-as 30000
          exit
      exit

      To establish, monitor, and maintain these connections, BGP implements a finite state machine (FSM). The BGP FSM changes the state of the connection based on a combination of internal and external events. Connections are established and unicast messages are sent using TCP port 179. When the connection is established, BGP sends keep-alive messages at a configurable rate.

      There are two types of BGP connections. The type of connection depends on whether the peers are in the same AS or not.

      • Exterior Border Gateway Protocol (eBGP): eBGP connects interfaces in different autonomous systems. Routes learned from an eBGP peer are advertised to both iBGP and eBGP peers. eBGP can also run between two peers that are not directly connected using a virtual private network (VPN) tunnel.
      • Interior Border Gateway Protocol (iBGP): This runs between two peers within the same AS. Routes learned from an iBGP peer are only advertised outside the AS through eBGP peers. As a result, all routes within iBGP are required to be connected in a full mesh. However, several optimizations and extensions can somewhat relieve this demand.

      Each AS is assigned an autonomous system number (ASN) to identify it on the network. This designates it as an independent network with its own routing policies and helps BGP decide whether to use iBGP or eBGP. An AS controls a set of IP addresses and is allowed to advertise and aggregate these addresses.

      How Does the BGP State Machine Operate?

      BGP uses a finite state machine to establish and maintain connections. The connection state changes in response to incoming messages, errors, lack of responses from the peer, and internal timers. There are four types of BGP messages, and the FSM has six states. Here are the BGP message types.

      • Open: These messages are sent after the TCP session is established. They communicate information about the local BGP configuration and negotiate shared parameters.
      • Keepalive: A keepalive message tells the peer the session is still active. The frequency of the keepalive messages is typically configurable on a per-peer basis.
      • Update: An update communicates new routing information to the peer. When a BGP session is initially established, local routing information is sent to the peer. In an ongoing session, information about new and withdrawn routes is also sent using this message type.
      • Notification: A notification advises the peer about errors or connectivity problems. When a peer receives the message, it terminates the BGP connection.

      The BGP finite state machine includes the following six states.

      • Idle: A BGP connection begins in this state and returns to this state if errors occur or the connection times out. While in this state, BGP initiates a connection and listens for a response or request for connection from the peer. After the connection establishment phase begins, the FSM moves the session to the Connect state. It is not possible to move from Idle to any other state other than Connect.
      • Connect: This is a transitional state that occurs during TCP negotiation after a message is received from the peer. The Connect state attempts to complete a three-way TCP handshake with the peer and establish a TCP session. After a successful handshake, BGP sends an Open message and moves to OpenSent. If the TCP session is not immediately established, the state changes to Active. Any errors cause the state machine to transition back to Idle.
      • Active: This confusingly named state allows for another attempt at establishing a TCP session. If the new attempt is successful, the session sends an Open message and proceeds to the OpenSent state. If it is unsuccessful and the timer expires, it returns to either the Connect or Idle state. In the case of network issues, congestion, or unstable links, a connection can wind up cycling between Idle, Connect, and Active.
      • OpenSent: When the TCP session is established, the BGP FSM enters the OpenSent state and listens for an Open message from the peer. When it receives this message, it validates the message. If the validation is successful, the FSM sets the hold time and moves to the OpenConfirm state. If there are errors, it notifies the peer and resets the connection back to Idle.
      • OpenConfirm: In this short-lived state, BGP listens for a keepalive message from the peer. If it receives one before the keepalive timer expires, the session transitions to Established. If a keepalive is not received or another error occurs, the session moves back to Idle.
      • Established: When a BGP session reaches this final state, it becomes fully operational. When the Established state is reached, the peers send Update messages to advertise information about the routes in their database. If any errors occur, the session moves back to the Idle state.

      Here is a state diagram illustrating all possible states and transitions, courtesy of Wikipedia.

      BGP Finite State Machine

      When BGP detects an error, it sends a Notification message. This message causes the interface to close and moves the BGP session back to the Idle state. Here are some examples of errors that can return the connection to the Idle state.

      • TCP port 179 is closed or fails to open. This can occur if the underlying physical interface is not operational or if the BGP interface is disabled or not fully configured.
      • A dynamic TCP port with an ID greater than 1023 is not available for the second ephemeral TCP port.
      • The BGP peer address and ASN are not configured correctly.
      • Network congestion or high latency.
      • A flapping network interface or connection.
      • A session times out due to a lack of keepalive messages.

      How Does BGP Build its Routing Information Base?

      BGP routing is extremely complex and some aspects are vendor specific. A complete discussion of the full intricacies of BGP routing is beyond the scope of this introductory guide. However, certain basic principles apply in all cases.

      Each BGP interface receives Update messages from its peer indicating reachable destinations for a specific BGP path. The reachable networks are communicated in the form of Network-layer Reachability Information (NLRI) updates. Each NLRI contains a length and prefix for each network on the path. Only one NLRI is advertised in each update message. For instance, an NLRI might contain the entry /24, 192.0.2.

      The Update also contains path attributes, including the inter-AS path to the network. A BGP route contains a list of the autonomous systems a packet must transit to reach the destination. This information helps detect and avoid routing loops. The path attributes must also include the next hop information, and a legacy attribute for the route origin.

      BGP receives a number of NLRI updates from each peer. In return, it also sends out its list of known networks to each of its peers. This strategy allows each peer to effectively calculate the best route to each network.

      For each peer, BGP maintains a conceptual base of routing information. This includes an adjacent routing information base, incoming (Adj-RIB-In) for NLRI updates received from the neighbor. Only one route to a given destination is stored in the Adj-RIB-In. The complementary Adj-RIB-Out is an outgoing information base containing NLRIs to send to the peer. The adj-RIB-Out is also influenced by routing policy and other factors, but only viable routes are allowed.

      BGP collates the information received from all peers into its local routing information base (Loc-RIB). The Loc-RIB is the master BGP routing table. It includes the best BGP route to each advertised network, independent of other routing protocols. The BGP protocol specification lists some factors to consider when selecting routes. However, individual vendors can also incorporate other information.

      Each route in the Loc-RIB must be resolvable and reachable. Additionally, the Loc-RIB chooses routes learned from external peers over any routes learned from iBGP. Other factors might include the cost/throughput of the route, the number of autonomous systems to traverse, community membership, route preferences, and system routing policies. The values of the AS and the IP address can potentially be used as tiebreakers.

      BGP is only one source of routing information for a system. BGP submits the candidate routes from the Loc-RIB to the main routing table, which combines routes from all routing sources. The BGP route is not necessarily selected. For example, in a local network an OSPF route or a static route might be chosen instead. Routing policies also dictate which route is used. For instance, all outgoing packets of a certain type might have to be sent to a traffic management system first. Each router is responsible for its own routing decisions, and the algorithms might vary from vendor to vendor.

      The routing topology is never static. New networks are always being built and removed, and interfaces can fail. New information from a peer forces BGP to recalculate the Adj-RIB-In. In many cases, this might cause a new best route to be installed in the Loc-RIB. This can consequently result in changes to the system routing table. In the event of a failure, traffic can quickly switch over to a less efficient secondary route. If there are no longer any routes to a destination, it is withdrawn from the BGP routing table.

      BGP Extensions and Optimizations

      Over the years, several enhancements and optimizations have been proposed to improve BGP performance and reduce memory requirements. BGP does not require any of these extensions, and system administrators can choose whether to use them or not. Here is a list of some of the most significant BGP options.

      • BGP Communities: Communities allow common policies to be applied to a set of prefixes. A community is indicated through the use of a common attribute tag. There are official well-known communities that should not be advertised or exported. Communities also allow geographic restrictions and help defend against denial-of-service attacks.
      • BGP Confederations: A BGP confederation contains more than one AS. The AS networks within the confederation exchange information as if they were all part of the same iBGP network. Only the ID of the confederation is advertised to the rest of the internet. A confederation makes it easier for an ISP to administer large networks.
      • Multi-exit Discriminators (MED): The MED is sent to peers to advertise the preferred interface for inbound traffic within an AS.
      • Multiprotocol BGP (MBGP/MP-BGP): MBGP can simultaneously carry information for multiple routing protocols and address families, including IPv6 and L3VPN. It supports both unicast and multicast addresses and permits separate routing tables for multicast addresses. MBGP is defined in
        RFC 4760.
      • Route Reflectors (RR): Route reflectors reduce the number of connections inside an AS and eliminates the requirement for a full mesh. An RR acts as the central point for a cluster of routers within the AS. All the route reflectors peer with each other, but the remaining routers only peer with the RR in their cluster. The net effect is to increase scalability and reduce the number of iBGP routes within the network.

      Unfortunately both route reflectors and confederations can increase convergence time and introduce inefficient routes, especially when used together.

      The Advantages and Disadvantages of BGP

      BGP has become the default exterior routing protocol due its many advantages. Here are some of the main benefits of BGP:

      • It provides a comprehensive and unified standard for the entire internet. BGP enables routers in different ISPs to communicate, thus reducing interoperability and compliance issues.
      • BGP is highly scalable and is able to store hundreds of thousands of routes.
      • The protocol does an efficient job of computing the best next hop for a given destination. Its internal algorithms and route selection process are highly optimized.
      • Several optimizations and extensions are available to maximize the performance of BGP and reduce its memory demands.
      • BGP conserves network bandwidth by minimizing the amount of updates and network traffic. The BGP finite state machine is clear and simple and most sessions are negotiated quickly.
      • It is able to quickly handle network failures and reroute traffic.

      Unfortunately, BGP has several drawbacks. Some of these problems are inherent in the original RFC, while others have developed due to the rapid growth of internet networks. Here are some of the most serious disadvantages of BGP:

      • BGP relies on manual configuration, which has the potential to introduce problems. Incorrect BGP configuration has been the root cause of several large-scale internet outages.
      • Sometimes the BGP route and the best route differ. This can be due to factors such as congestion and cost. So BGP is prone to suboptimal routing, particularly when extensions are used.
      • BGP is prone to stability problems in the presence of rapidly flapping interfaces or continually rebooting routers. This can lead to cascading failures that spread out to other networks and cause instability in the rest of the AS or across the internet backbone. BGP instability can be partially alleviated by route flap damping. Damping ignores a problematic interface for a predefined interval of time. Unfortunately, this can also increase convergence times for updates.
      • The global BGP routing tables are very large and continue to grow rapidly. iBGP requires a full mesh of connections, which is memory intensive to store. Efforts have been made to reduce the number of routes through aggregation and routing policies. The CPU demands of a large network can also be very large, especially when the router has many iBGP peers. Smaller and older routers might not be able to keep up with the large volume of updates.
      • BGP cannot detect congestion. This can result in the selection of suboptimal routes.
      • BGP is subject to security issues like BGP Hijacking. This occurs when attackers distribute false routing information to misdirect traffic. BGP hijacking takes advantage of the trust-based system between the autonomous systems. This problem has been reduced through the use of a Resource Public Key Infrastructure (RPKI). RPKI ensures only the official owner of an AS can distribute route updates for the addresses it owns.

      How Can BGP Cause Network Outages?

      BGP problems are commonly the root cause of major network outages, due to the complexity and challenges of the protocol. DNS problems can also cause network outages, but routing issues tend to be more complex and more difficult to debug and resolve. Some extensions and optimizations can interact to produce negative results.

      Problems can occur during configuration or when updating routers. A large number of route flaps can overwhelm a network with updates, leading to router failures. These failures intensify the original problem, and can subsequently spread to the wider internet. Several major outages at Tier 1 ISPs and services have been caused by cascading failures that eventually took down the entire network.

      Certain misconfiguration problems can be particularly severe. One ISP configured its network so all inbound and outbound traffic had to pass through one particular node, which soon failed under the pressure. It is also possible to accidentally drop all traffic destined for another AS. This could, for example, result in all users of the ISP being unable to access Google. In some cases, these failures can spread outside the AS and affect other networks. On more than one occasion, an organization has wiped all traces of its BGP interfaces off the internet with a bad configuration change.

      BGP problems can be very difficult to fix, whether the problem is a routing update from a telecom vendor or an internal configuration change. Only a certain number of highly skilled and trained people typically understand BGP and know how to debug and fix problems. In most cases, the only reasonable response is to roll back the router software or BGP configuration to an earlier version. Engineers can then investigate the problem offline while the network recovers. Unfortunately, it can still take a while for the network to come back online because BGP updates take some time to propagate. Networks that are already unstable or in flux are especially prone to this type of problem.

      BGP errors can also cause DNS failures, so the two major risk factors in a network can combine to amplify problems. A large number of BGP updates can cause DNS requests to fail and overload the DNS servers. This can potentially affect other services and lead to a network storm that decreases performance across the entire internet.

      Conclusion

      The Border Gateway Protocol (BGP) is the main routing system for the internet backbone and is used by every major service provider. BGP provides a map for routers to funnel packets from their original source to their final destination. A BGP session is established with a peer interface through the use of a finite state machine and standard message types. The peer can be in the same autonomous system or part of a different vendor’s network.

      BGP sends information about the reachable networks it knows to all of its peers. Based on the routes it receives in return, it constructs a local routing information base consisting of the best route to each network. In turn, BGP sends its selected routes to the main system routing base, where they can potentially be selected as the best route. BGP is a scalable and efficient standard, but suffers from high memory requirements and security issues, and is prone to serious misconfiguration problems. For full details about BGP, including state machine details and messaging formats, consult the IETF
      RFC 4271.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Cómo monitorear los anuncios y las rutas de BGP utilizando BGPalerter en Ubuntu 18.04


      El autor seleccionó el COVID-19 Relief Fund para que reciba una donación como parte del programa Write for DOnations.

      Introducción

      BGP (Protocolo de puerta de enlace de borde) es uno de los protocolos principales responsable de redirigir paquetes a través de Internet; por lo tanto, si presenta errores, se pueden producir interrupciones importantes. Por ejemplo, en 2019, un pequeño proveedor de servicios de Internet hizo una mala configuración de BGP que, lamentablemente, se propagó de manera ascendente y dejó importantes partes de Cloudflare y AWS sin conexión durante más de una hora.  Además, hace un año, se realizó un ataque a BGP para interceptar el tráfico a un proveedor de monederos de criptomonedas y robar los fondos de clientes desprevenidos.

      BGPalerter es una herramienta de monitoreo de la red de BGP de código abierto que puede proporcionar alertas en tiempo real sobre la actividad de BGP, incluso la visibilidad de rutas y los anuncios de nuevas rutas, así como actividades potencialmente nefastas, como intercepciones o fugas en las rutas. BGPalerter ingiere automáticamente la información de redireccionamiento de la red disponible públicamente, lo que significa que no necesita tener ningún nivel de acceso con privilegios ni integración en las redes que quiere controlar.

      Nota: BGPalerter ingiere automáticamente la información de redireccionamiento de la red disponible públicamente, lo que significa que no necesita tener ningún nivel de acceso con privilegios ni integración en las redes que quiere controlar. Todo el monitoreo cumple plenamente con la Ley de Uso Indebido de Computadoras (Computer Misuse Act), la Ley de Fraude y Abuso de Computadoras (Computer Fraud and Abuse Act), y otras leyes similares.  Sin embargo, se recomienda revelar de forma responsable cualquier hallazgo relevante al operador de la red afectado.

      En este tutorial, instalará y configurará BGPalerter para monitorear sus redes importantes, a fin de detectar actividades potencialmente sospechosas.

      Requisitos previos

      Para completar este tutorial, necesitará lo siguiente:

      Para cada dispositivo o red, necesitará identificar la dirección IP individual, el intervalo de la dirección IP o el número de sistema autónomo del que es parte. Esto se abarca en el paso 1.

      Una vez que tenga todo esto listo, inicie sesión en su servidor como non-root user.

      Paso 1: Identificar las redes que se quieren monitorear

      En este paso, identificará los detalles pertinentes de las redes que quiere monitorear.

      BGPalerter puede monitorear sobre la base de direcciones IP individuales o prefijos de red. También puede monitorear redes enteras sobre la base de su número de sistema autónomo (AS), que es un identificador global único de una red propiedad de una entidad administrativa en particular.

      Para encontrar esta información, puede utilizar el servicio de búsqueda IP-to-ASN de WHOIS, proporcionado por el servicio de inteligencia de amenazas Team Cymru. Se trata de un servidor de WHOIS personalizado diseñado para buscar información de dirección IP y enrutamiento de red.

      Si no tiene whois instalado, puede instalarlo usando el siguiente comando:

      • sudo apt update
      • sudo apt install whois

      Una vez que haya confirmado que whois está instalado, comience por realizar una búsqueda de la dirección IP de su propio servidor, utilizando el argumento -h para especificar un servidor personalizado:

      • whois -h whois.cymru.com your-ip-address

      Esto generará un resultado similar al siguiente, que muestra el nombre y el número de AS del que su servidor es parte. Normalmente, será el AS de su proveedor de alojamiento del servidor, por ejemplo, DigitalOcean.

      Output

      AS | IP | AS Name 14061 | your-ip-address | DIGITALOCEAN-ASN, US

      A continuación, puede realizar una búsqueda para identificar el prefijo de la red o el intervalo del que su servidor es parte. Para hacerlo, agregue el argumento -p a su solicitud:

      • whois -h whois.cymru.com " -p your-ip-address"

      El resultado será muy similar al comando anterior, pero, ahora, mostrará el prefijo de dirección IP al que pertenece la dirección IP de su servidor:

      Output

      AS | IP | BGP Prefix | AS Name 14061 | your-ip-address | 157.230.80.0/20 | DIGITALOCEAN-ASN, US

      Por último, puede buscar más detalles del AS del que forma parte su servidor, incluyendo la región geográfica y la fecha de asignación.

      Sustituya el número de AS que identificó usando los comandos anteriores. Utiliza el argumento -v para habilitar el resultado detallado, lo que garantiza que se muestren todos los detalles relevantes:

      • whois -h whois.cymru.com " -v as14061"

      El resultado mostrará más información sobre el AS:

      Output

      AS | CC | Registry | Allocated | AS Name 14061 | US | arin | 2012-09-25 | DIGITALOCEAN-ASN, US

      identificó detalles clave sobre las redes que quiere monitorear. Tome nota de estos detalles en algún lugar, ya que los necesitará más adelante. A continuación, comenzará a configurar BGPalerter.

      Paso 2: Crear un usuario sin privilegios para BGPalerter

      En este paso, creará una nueva cuenta de usuario sin privilegios para BGPalerter, dado que el programa no necesita ejecutarse con privilegios sudo/root.

      Primero, cree un usuario nuevo con contraseña deshabilitada:

      • sudo adduser --disabled-password bgpalerter

      No necesita configurar una contraseña o una clave de SSH, dado que solo utilizará este usuario como una cuenta de servicio para ejecutar/mantener BGPalerter.

      Inicie sesión con el usuario nuevo utilizando su:

      Ahora, está conectado con su usuario nuevo:

      bgpalerter@droplet:/home/user$
      

      Utilice el comando cd para dirigirse al directorio de inicio de su usuario nuevo:

      bgpalerter@droplet:/home/user$ cd
      bgpalerter@droplet:~$
      

      Creó un usuario sin privilegios nuevo para BGPalerter. A continuación, instalará y configurará BGPalerter en su sistema.

      Paso 3: Instalar y configurar BGPalerter

      En este paso, instalará y configurará BGPalerter. Asegúrese de seguir conectado con su usuario sin privilegios nuevo.

      Primero, debe identificar la última versión de BGPalerter, a fin de asegurarse de descargar la más reciente. Diríjase a la página de Lanzamientos de BGPalerter y copie el enlace de descarga de la versión de Linux x64 más reciente.

      Ahora, puede descargar una copia de BGPalerter usando wget, asegurándose de sustituir el enlace de descarga correcto:

      • wget https://github.com/nttgin/BGPalerter/releases/download/v1.24.0/bgpalerter-linux-x64

      Una vez que el archivo haya terminado de descargarse, márquelo como ejecutable:

      • chmod +x bgpalerter-linux-x64

      A continuación, compruebe que BGPalerter se haya descargado e instalado correctamente comprobando el número de la versión:

      • ./bgpalerter-linux-x64 --version

      Esto dará como resultado el número de la versión actual:

      Output

      1.24.0

      Para poder ejecutar BGPalerter adecuadamente, deberá definir las redes que desea monitorear en un archivo de configuración. Cree y abra el archivo prefixes.yml en su editor de texto favorito:

      En este archivo de configuración, especificará cada una de las direcciones IP individuales, los intervalos de dirección IP y los números de AS que quiere monitorear.

      Añada el siguiente ejemplo y ajuste los valores de configuración según sea necesario usando la información de la red que identificó en el paso 1:

      ~/prefixes.yml

      your-ip-address/32:
        description: My Server
        asn:
          - 14061
        ignoreMorespecifics: false
      
      157.230.80.0/20:
        description: IP range for my Server
        asn:
          - 14061
        ignoreMorespecifics: false
      
      options:
        monitorASns:
          '14061':
            group: default
      

      Puede monitorear todos los intervalos de dirección IP o números de AS que quiera. Para monitorear direcciones IP individuales, represéntelas utilizando /32 para IPv4 y /128 para IPv6.

      El valor ignoreMorespecifics se utiliza para determinar si BGPalerter debe ignorar la actividad de las rutas más específicas (pequeñas) que la que está monitoreando. Por ejemplo, si está monitoreando /20 y se detecta un cambio de enrutamiento para /24 en su interior, se considera que es más específica. En la mayoría de los casos, no es recomendable ignorarlas si está monitoreando una red grande con varios prefijos de cliente delegados, sin embargo, puede ayudar a reducir interferencias de fondo.

      Ahora, puede ejecutar BGPalerter por primera vez para comenzar a monitorear sus redes:

      Si BGPalerter se inicia correctamente, verá un resultado similar al siguiente. Tenga en cuenta que, a veces, el monitoreo puede tardar unos minutos en iniciarse:

      Output

      Impossible to load config.yml. A default configuration file has been generated. BGPalerter, version: 1.24.0 environment: production Loaded config: /home/bgpalerter/config.yml Monitoring 157.230.80.0/20 Monitoring your-ip-address/32 Monitoring AS 14061

      BGPalerter se seguirá ejecutando hasta que lo detenga usando Ctrl+C.

      En el siguiente paso, interpretará algunas de las alertas que BGPalerter puede generar.

      Paso 4: Interpretar alertas de BGPalerter

      En este paso, revisará algunas alertas de BGPalerter de ejemplo. BGPalerter emitirá alertas en la fuente de salida principal, y también, de forma opcional, en cualquier otro extremo de información que pueda configurarse dentro de config.yml, como se describe en la documentación de BGPalerter.

      De manera predeterminada, BGPalerter monitorea y alerta sobre lo siguiente:

      • Intercepciones de ruta: se produce cuando un AS anuncia un prefijo que no está permitido, lo que provoca que el tráfico se enrute de forma errónea. Puede ser un ataque deliberado o un error de configuración accidental.

      • Pérdida de visibilidad de la ruta: una ruta se considera visible cuando la mayoría de los enrutadores de BGP de Internet pueden redirigir de forma fiable hacia ella. La pérdida de visibilidad significa que su red no está disponible, por ejemplo, si su emparejamiento de BGP ha dejado de funcionar.

      • Nuevos anuncios de subprefijos: sucede cuando un AS comienza a anunciar un prefijo que es más pequeño de lo que se espera. Esto puede indicar un cambio de configuración previsto, un error de configuración accidental o, en algunos casos, un ataque.

      • Actividad en su AS: normalmente, se refiere a anuncios de rutas nuevas. Una ruta se considera “nueva” si BGPalerter todavía no la conoce.

      A continuación, se presentan algunas alertas de ejemplo, junto con una descripción breve de su significado:

      Alert #1

      The prefix 203.0.113.0/24 is announced by AS64496 instead of AS65540
      

      Esta alerta muestra pruebas de una intercepción de la ruta, donde AS64496 anunció 203.0.113.0/24 cuando se esperaba que se anuncie AS65540. Esto es un claro indicio de un error de configuración que conduce a una fuga de la ruta o a una intercepción deliberada de un atacante.

      Alert #2

      The prefix 203.0.113.0/24 has been withdrawn. It is no longer visible from 6 peers
      

      Esta alerta indica que la red 203.0.113.0/24 ya no está visible. Esto puede deberse a un problema de enrutamiento previo o a un fallo de energía en un enrutador.

      Alert #3

      A new prefix 203.0.113.0/25 is announced by AS64496. It should be instead 203.0.113.0/24 announced by AS64496
      

      Esta alerta indica que se anunció un prefijo más específico en un caso en el que no estaba previsto, por ejemplo, si se anunció /25 cuando se esperaba /24. Es muy probable que esto sea un error de configuración, sin embargo, en algunos casos, puede indicar la intercepción de la ruta.

      Alert #4

      AS64496 is announcing 192.0.2.0/24 but this prefix is not in the configured list of announced prefixes
      

      Por último, esta alerta indica que AS64496 anunció un prefijo que BGPalerter todavía no conoce. Esto podría deberse a que usted está anunciando legítimamente un nuevo prefijo o podría ser un indicio de un error de configuración que haya provocado que anunciara accidentalmente un prefijo propiedad de otra persona.

      En este paso, revisó algunas alertas de BGPalerter de ejemplo. A continuación, configurará BGPalerter para que se ejecute de forma automática en el arranque.

      Paso 5: Iniciar BGPalerter en el arranque

      En este último paso, configurará BGPalerter para que se ejecute en el arranque.

      Asegúrese de seguir conectado con su usuario sin privilegios nuevo y, luego, abra el editor de crontab:

      Luego, añada la siguiente línea a la parte inferior del archivo de crontab:

      crontab

      @reboot sleep 10; screen -dmS bgpalerter "./bgpalerter-linux-x64"
      

      Cada vez que su sistema se arranque, esto creará una sesión screen separada denominada ‘bgpalerter’ en la que se iniciará BGPalerter.

      Guarde y salga del editor de crontab. Ahora, es conveniente que reinicie su sistema para asegurarse de que BGPalerter se inicie correctamente en el arranque.

      Primero, cierre la sesión de su usuario de BGPalerter:

      Luego, proceda con un reinicio normal del sistema:

      Una vez que su sistema se haya reiniciado, vuelva a iniciar sesión en su servidor y utilice su para volver a acceder a su usuario de BGPalerter:

      Luego, puede unirse a la sesión en cualquier momento para ver el resultado de BGPalerter:

      En este último paso, configuró BGPalerter para que se ejecute en el arranque.

      Conclusión

      En este artículo, configuró BGPalerter y lo utilizó para monitorear cambios de enrutamiento de BGP en las redes.

      Si quiere hacer que BGPalerter sea más fácil de usar, puede configurarlo para que envíe alertas a un canal de slack a través de un webhook:

      Si quiere obtener más información sobre BGP, pero no tiene acceso a un entorno de producción de BGP, puede utilizar DN42 para realizar pruebas con BGP en un entorno seguro y aislado:



      Source link

      Мониторинг объявлений и мероприятий по BGP при помощи BGPalerter в Ubuntu 18.04


      Автор выбрал COVID-19 Relief Fund для получения пожертвования в рамках программы Write for DOnations.

      Введение

      BGP (таблица пограничного межсетевого протокола) — один из ключевых протоколов, отвечающих за маршрутизацию пакетов через Интернет, поэтому когда он работает неправильно, могут возникать серьезные перебои с Интернетом. Например, в 2019 году небольшой интернет-провайдер создал неправильную конфигурацию BGP, которая, к сожалению, распространилась на более высокие уровни и вывела большие сегменты Cloudflare и AWS оффлайн более чем на час. Кроме того, годом ранее был осуществлен захват BGP, чтобы перехватить трафик к известному провайдеру криптовалютных кошельков и похитить средства ничего не подозревающих клиентов.

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

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

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

      Предварительные требования

      Для данного обучающего руководства вам потребуется следующее:

      • Сервер Ubuntu 18.04, настроенный согласно руководству по первоначальной настройке сервера с Ubuntu 18.04, включая пользователя non-root user с привилегиями sudo.

      • Одна или несколько сетей и устройств, которые вы хотите отслеживать, например:

        • Ваш сервер
        • Сеть вашей компании
        • Ваш локальный интернет-провайдер

      Для каждого устройства или сети вам потребуется идентифицировать либо отдельный IP-адрес, диапазон IP-адресов, либо номер автономной системы в этом диапазоне. Эти действия рассматриваются в шаге 1.

      Подготовив все вышеперечисленное, войдите на сервер в качестве non-root user, чтобы начать подготовку.

      Шаг 1 — Определение сетей для мониторинга

      На этом шаге вы узнаете соответствующие данные о сетях, которые вы хотите отслеживать.

      BGPalerter может выполнять мониторинг на основе отдельных IP-адресов или сетевых префиксов. Он также может отслеживать целые сети на основе номера автономной системы — уникального в глобальном масштабе идентификатора сети, принадлежащего конкретному административному объекту.

      Для нахождения этой информации вы можете использовать службу пооиска IP-to-ASN WHOIS, которую предоставляет служба разведки угроз Team Cymru. Это пользовательский сервер WHOIS, предназначенный для просмотра IP-адресов и информации о сетевой маршрутизации.

      Если у вас не установлен whois, вы можете сделать это с помощью следующих команд:

      • sudo apt update
      • sudo apt install whois

      Как только вы убедились, что whois установлен, начните с поиска IP-адресов вашего собственного сервера с помощью аргумента -h для указания настраиваемого сервера:

      • whois -h whois.cymru.com your-ip-address

      Это выведет примерно следующий результат, где указано имя и номер AS, в котором находится ваш сервер. Как правило, это будет AS вашего хостинг-провайдера — например, DigitalOcean.

      Output

      AS | IP | AS Name 14061 | your-ip-address | DIGITALOCEAN-ASN, US

      Далее вы можете выполнить поиск для определения префикса/диапазона сети, в которой находится ваш сервер. Это можно сделать, добавив к запросу аргумент -p:

      • whois -h whois.cymru.com " -p your-ip-address"

      Вывод будет очень похож на предыдущую команду, но теперь он будет показывать префикс IP-адреса, к которому относится IP-адрес вашего сервера:

      Output

      AS | IP | BGP Prefix | AS Name 14061 | your-ip-address | 157.230.80.0/20 | DIGITALOCEAN-ASN, US

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

      Подставьте номер AS, который вы определили с помощью предыдущих команд. Вы используете аргумент -v для активации вывода подробной информации с отображением всех соответствующих данных:

      • whois -h whois.cymru.com " -v as14061"

      При этом будет показана дополнительная информация об AS:

      Output

      AS | CC | Registry | Allocated | AS Name 14061 | US | arin | 2012-09-25 | DIGITALOCEAN-ASN, US

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

      Шаг 2 — Создание непривилегированного пользователя для BGPalerter

      На этом шаге вы создадите новую учетную запись непривилегированного пользователя для BGPalerter, т.к. для работы этой программы не требуются права sudo/root.

      Сначала создайте нового пользователя с отключенным паролем:

      • sudo adduser --disabled-password bgpalerter

      Вам не нужно настраивать пароль или ключи SSH, поскольку вы будете использовать этого пользователя только в качестве служебной учетной записи для работы/обслуживания BGPalerter.

      Войдите под именем нового пользователя с помощью команды su:

      Вы вошли как новый пользователь:

      bgpalerter@droplet:/home/user$
      

      Используйте команду cd для перехода в домашнюю директорию нового пользователя:

      bgpalerter@droplet:/home/user$ cd
      bgpalerter@droplet:~$
      

      Вы создали нового непривилегированного пользователя для BGPalerter. Далее вы установите и настроите BGPalerter в своей системе.

      Шаг 3 — Установка и настройка BGPalerter

      На этом шаге вы установите и настроите BGPalerter. Убедитесь, что вы все еще в системе под именем своего нового непривилегированного пользователя.

      Сначала вам нужно определить последний выпуск BGPalerter, чтобы убедиться, что вы загружаете актуальную версию. Перейдите на страницу Выпуски BGPalerter и скопируйте ссылки на загрузку самой последней версии Linux x64.

      Теперь вы можете загрузить копию BGPalerter с помощью wget, если подставите правильную ссылку на загрузку:

      • wget https://github.com/nttgin/BGPalerter/releases/download/v1.24.0/bgpalerter-linux-x64

      Когда файл загрузится, отметьте его как исполняемый:

      • chmod +x bgpalerter-linux-x64

      Затем убедитесь, что BGPalerter загружен и успешно установлен, сверив номер версии:

      • ./bgpalerter-linux-x64 --version

      В результате будет выведен текущий номер версии:

      Output

      1.24.0

      Чтобы корректно запустить BGPalerter, необходимо сначала определить сети, которые вы хотите отслеживать в файле конфигурации. Создайте и откройте файл prefixes.yml в предпочитаемом текстовом редакторе:

      В этом файле конфигурации вы укажете каждый пользовательский IP-адрес, диапазоны IP-адресов и номера AS, которые вы хотите отслеживать.

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

      ~/prefixes.yml

      your-ip-address/32:
        description: My Server
        asn:
          - 14061
        ignoreMorespecifics: false
      
      157.230.80.0/20:
        description: IP range for my Server
        asn:
          - 14061
        ignoreMorespecifics: false
      
      options:
        monitorASns:
          '14061':
            group: default
      

      Вы можете отслеживать столько диапазонов IP-адресов или номеров AS, сколько захотите. Чтобы отслеживать отдельные IP-адреса, указывайте /32 для IPv4 и /128 для IPvv6.

      Значение ignoreMorespecifics используется, чтобы контролировать, должен ли BGPalerter игнорировать деятельность на маршрутах, более специфичных (меньших) по сравнению с тем, который вы отслеживаете. Например, если вы отслеживаете /20, и изменение маршрутизации обнаружено в нем для /24, то это считается более специфичным маршрутом. В большинстве случаев их не нужно игнорировать, но если вы отслеживаете большую сеть с несколькими префиксами делегированных пользователей, то это может снизить фоновый шум.

      Теперь вы можете запустить BGPalerter в первый раз, чтобы начать отслеживать свои сети:

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

      Output

      Impossible to load config.yml. A default configuration file has been generated. BGPalerter, version: 1.24.0 environment: production Loaded config: /home/bgpalerter/config.yml Monitoring 157.230.80.0/20 Monitoring your-ip-address/32 Monitoring AS 14061

      BGPalerter будет продолжать работать, пока вы не остановите его нажатием Ctrl+C.

      На следующем шаге вы перейдете к интерпретации некоторых предупреждений, которые может создавать BGPalerter.

      Шаг 4 — Интерпретация интерфейсов BGPalerter

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

      По умолчанию BGPalerter отслеживает и предупреждает о следующем:

      • Route hijacks: выдается в случае, когда AS объявляет запрещенный префикс, вызывая ошибочную маршрутизацию трафика. Это может быть либо преднамеренным нападением, либо случайной ошибки в конфигурации.

      • Потеря видимости маршрута: маршрут считается видимым, когда большинство маршрутизаторов BGP в Интернете может надежно создавать маршруты к нему. Потеря видимости указывает на потенциальную недоступность вашей сети — например, если ваш BGP peering прекращает работать.

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

      • Деятельность в рамках вашего AS: обычно используется для новых сообщений о маршрутах. Трафик считается «новым», если BGPalerter еще не знает о нем.

      Ниже представлены некоторые примеры предупреждений, а также краткое описание их значения:

      Alert #1

      The prefix 203.0.113.0/24 is announced by AS64496 instead of AS65540
      

      Это предупреждение свидетельствует о захвате маршрута, т.к. AS64496 объявил 203.013.0/24, хотя ожидается, что этот маршрут будет объявлен AS65540. Это надежный показатель ошибочной конфигурации, приводящей к утечке маршрута, либо преднамеренного захвата злоумышленником.

      Alert #2

      The prefix 203.0.113.0/24 has been withdrawn. It is no longer visible from 6 peers
      

      Это предупреждение говорит о том, что сеть 203.013.0/24 стала невидимой. Это может быть связано с проблемой исходящей маршрутизации, либо произошел сбой питания маршрутизатора.

      Alert #3

      A new prefix 203.0.113.0/25 is announced by AS64496. It should be instead 203.0.113.0/24 announced by AS64496
      

      Это предупреждение показывает, что был объявлен более специфичный префикс там, где это не ожидалось — например, /25, когда ожидалось только /24. Скорее всего, это ошибочная конфигурация, но в некоторых случаях это может свидетельствовать о захвате маршрута.

      Alert #4

      AS64496 is announcing 192.0.2.0/24 but this prefix is not in the configured list of announced prefixes
      

      Помимо этого, данное предупреждение показывает, что AS64496 объявил префикс, который BGPalerter еще не знает. Это может быть связано с тем, что вы обоснованно объявляете новый префикс, или может говорить об ошибочной конфигурации, из-за которой вы случайно объявили чужой префикс.

      На этом шаге вы рассмотрели несколько примеров предупреждений BGPalerter. Далее вы настроите BGPalerter для автоматического запуска во время начальной загрузки.

      Шаг 5 — Запуск BGPalerter во время начальной загрузки

      На этом последнем шаге вы настроите BGPalerter для запуска во время начальной загрузки.

      Убедитесь, что вы все еще в системе под именем нового непривилегированного пользователя, затем откройте crontab:

      Добавьте следующую строку внизу файла crontab:

      crontab

      @reboot sleep 10; screen -dmS bgpalerter "./bgpalerter-linux-x64"
      

      При каждой загрузке системы будет создаваться отдельная экранная сессия с именем bgpalerter, в которой будет запускаться BGPalerter.

      Сохраните изменения и закройте редактор crontab. Теперь можно перезагрузить систему, чтобы убедиться, что BGPalerter корректно запускается во время начальной загрузки.

      Сначала нужно выйти из вашего пользователя BGPalerter:

      Затем перезагрузите систему, как обычно:

      После перезагрузки системы снова войдите на сервер и при помощи su еще раз получите доступ к вашему пользователю BGPalerter:

      Затем можно в любой момент присоединиться к сессии для просмотра вывода BGPalerter:

      На этом последнем шаге вы настроили BGPalerter для запуска во время начальной загрузки.

      Заключение

      В этой статье вы настроили BGPalerter и использовали его для отслеживания сетей с целью внесения изменений в маршрутизацию BGP.

      Если хотите сделать BGPalerter более удобным для пользователя, то можно настроить его для отправки предупреждений через канал Slack посредством веб-хука:

      Если хотите узнать больше о самой системе BGP, но у нас нет доступа к производственной среде BGP, то вам может пригодиться DN42 для экспериментов с BGP в безопасной изолированной среде:



      Source link