🌍 Networking

BGP

Border Gateway Protocol

An internet routing protocol. Exchanges routes between ASes.

📖 Detailed Explanation

BGP (Border Gateway Protocol) is a protocol that exchanges routing information among the tens of thousands of autonomous systems (AS) that make up the internet. Called the internet's "post office system," it determines the optimal paths so that networks around the world can communicate with each other. If DNS is the internet's phone book, BGP is responsible for designing the roads along which actual data travels.

BGP is broadly divided into two types. eBGP (External BGP) exchanges routing information between different ASes and is generally used for peering between an ISP and an enterprise, or between ISPs. iBGP (Internal BGP) is used to propagate routes learned from outside within the same AS. AS numbers (ASN) are assigned by IANA and have been expanded from 2 bytes (0-65535) to 4 bytes (up to 4.2 billion).

BGP's path selection algorithm determines the optimal path based on several attributes. Attributes such as LOCAL_PREF (higher is preferred), AS_PATH (shorter is preferred), MED (lower is preferred), ORIGIN (IGP > EGP > incomplete), and WEIGHT (Cisco only) are compared in sequence. Thanks to this complex algorithm, network administrators can finely control traffic flow.

Major outages caused by BGP vulnerabilities occur repeatedly. In October 2021, Facebook (Meta) had its services disrupted worldwide for about 6 hours due to a BGP configuration error, resulting in losses of billions of dollars. BGP Hijacking is an attack in which a malicious AS advertises incorrect routes to intercept traffic; in 2018, an Amazon Route 53 hijacking even led to the theft of about $150,000 in cryptocurrency. To prevent this, security mechanisms such as RPKI (Resource Public Key Infrastructure) and ROA (Route Origin Authorization) are being introduced.

💻 Code Example

# pip install pybgpstream (BGP 데이터 분석)
from pybgpstream import BGPStream

# BGP 업데이트 스트림 분석
stream = BGPStream(
    from_time="2021-10-04 15:00:00",
    until_time="2021-10-04 22:00:00",
    collectors=["route-views2", "rrc00"],
    record_type="updates",
    filter="prefix more 32.0.0.0/8"  # Facebook 관련 프리픽스
)

# BGP 메시지 파싱
for elem in stream:
    if elem.type == "A":  # Announcement
        print(f"Announce: {elem.fields['prefix']}")
        print(f"  AS Path: {elem.fields['as-path']}")
        print(f"  Origin AS: {elem.peer_asn}")
    elif elem.type == "W":  # Withdrawal
        print(f"Withdraw: {elem.fields['prefix']}")

# ExaBGP로 BGP 스피커 구현 (exabgp.conf)
"""
neighbor 192.168.1.1 {
    router-id 10.0.0.1;
    local-address 10.0.0.2;
    local-as 65001;
    peer-as 65002;

    static {
        route 203.0.113.0/24 next-hop self;
        route 198.51.100.0/24 next-hop self community [65001:100];
    }
}
"""

# RPKI 검증 (routinator 사용)
import requests

def check_rpki_validity(prefix, asn):
    """RPKI ROA 검증"""
    url = f"https://rpki-validator.ripe.net/api/v1/validity/{asn}/{prefix}"
    response = requests.get(url)
    data = response.json()
    return data.get("validated_route", {}).get("validity", {}).get("state")

# 예시: AS15169(Google)의 8.8.8.0/24 검증
result = check_rpki_validity("8.8.8.0/24", 15169)
print(f"RPKI Status: {result}")  # valid, invalid, or not-found
# BGP 라우팅 테이블 조회 (Looking Glass)
# 공개 BGP Looking Glass 서비스 사용

# whois로 AS 정보 조회
whois -h whois.radb.net AS15169  # Google AS 정보
whois -h whois.radb.net 8.8.8.0/24  # IP 프리픽스 소유자

# bgpq4로 프리픽스 리스트 생성 (ISP 필터링용)
bgpq4 -4 -l prefix_list AS-GOOGLE  # Google의 IPv4 프리픽스

# RIPE RIS Live BGP 스트림 (WebSocket)
websocat "wss://ris-live.ripe.net/v1/ws/?client=cli-example" | \
  jq 'select(.data.type == "UPDATE")'

# BGP 경로 추적 (traceroute + AS 정보)
mtr --aslookup google.com

# RPKI 검증 상태 확인
curl "https://stat.ripe.net/data/rpki-validation/data.json?resource=8.8.8.0/24&prefix=8.8.8.0/24"

# BGP 업데이트 모니터링 (bgpstream)
bgpreader -w 1633356000,1633377600 \
  -c route-views2 \
  -p 32.0.0.0/8 \
  | head -100

# AS 경로 분석
traceroute -A google.com  # AS 번호 표시

# BGP 세션 상태 확인 (Linux FRRouting)
sudo vtysh -c "show bgp summary"
sudo vtysh -c "show ip bgp neighbors"
sudo vtysh -c "show ip bgp"
# Cisco IOS BGP 기본 설정

# BGP 라우터 설정
router bgp 65001                        # 자신의 AS 번호
  bgp router-id 10.0.0.1               # 라우터 ID
  bgp log-neighbor-changes             # 네이버 상태 변화 로깅

  # eBGP 네이버 설정 (외부 AS)
  neighbor 192.168.1.1 remote-as 65002
  neighbor 192.168.1.1 description ISP_A
  neighbor 192.168.1.1 password MySecretPassword
  neighbor 192.168.1.1 ebgp-multihop 2

  # iBGP 네이버 설정 (같은 AS)
  neighbor 10.0.0.2 remote-as 65001
  neighbor 10.0.0.2 update-source Loopback0
  neighbor 10.0.0.2 next-hop-self

  # 네트워크 광고
  network 203.0.113.0 mask 255.255.255.0

  # 경로 필터링 (Prefix-list)
  neighbor 192.168.1.1 prefix-list ALLOWED-IN in
  neighbor 192.168.1.1 prefix-list ALLOWED-OUT out

# Prefix-list 정의
ip prefix-list ALLOWED-IN seq 10 permit 0.0.0.0/0 le 24
ip prefix-list ALLOWED-IN seq 20 deny 0.0.0.0/0 le 32
ip prefix-list ALLOWED-OUT seq 10 permit 203.0.113.0/24

# Route-map으로 LOCAL_PREF 설정
route-map SET-LOCAL-PREF permit 10
  set local-preference 200
!
neighbor 192.168.1.1 route-map SET-LOCAL-PREF in

# BGP 상태 확인 명령어
show ip bgp summary                    # BGP 세션 요약
show ip bgp neighbors                  # 네이버 상세 정보
show ip bgp                           # BGP 라우팅 테이블
show ip bgp 8.8.8.0/24                # 특정 프리픽스 경로
clear ip bgp * soft                   # BGP 세션 소프트 리셋

🗣️ Say It Like This in Practice

💬 In a Network Incident Analysis Meeting
"I checked with the BGP Looking Glass, and it looks like our prefix has been withdrawn from the upstream ISP. Our ASN has disappeared from the AS Path. We should check the peering session status and, if necessary, try a hard reset of the BGP session."
💬 In a Security Team Meeting
"A BGP Hijacking attempt was recently detected. We need to set up an RPKI ROA to authenticate the origin AS of our prefix, and ask the upstream ISP to enable ROV (Route Origin Validation). Please also consider joining the MANRS initiative."
💬 In an Infrastructure Design Discussion
"For a multihoming setup, we plan to establish BGP peering with two ISPs and adjust traffic distribution with AS-prepending. We'll set LOCAL_PREF 200 on the primary ISP and 100 on the backup ISP to determine outbound traffic priority, and control inbound traffic by AS Path length."

⚠️ Common Mistakes & Cautions

❌
Deploying BGP configuration changes without testing

The 2021 Facebook outage was caused by a bug in a configuration change script that took down all BGP sessions. Always test in a lab environment before making changes, and establish a rollback plan. Use automatic rollback features such as 'commit confirm'.

❌
Peering without prefix filtering

Opening a BGP session without filters makes you vulnerable to route leaks and hijacking. Be sure to apply prefix-list and as-path filters, and block bogon prefixes (0.0.0.0/8, 10.0.0.0/8, 224.0.0.0/4, etc.).

❌
Not configuring an iBGP full mesh

iBGP does not re-advertise learned routes to other iBGP peers (split horizon). With N routers, N*(N-1)/2 sessions are required, or you must configure a Route Reflector or Confederation.

✅
BGP security best practices

Authenticate prefix origins with RPKI/ROA, apply MD5 authentication or TCP-AO to BGP sessions, prevent remote session spoofing with GTSM (TTL security), and counter route leaks by setting maximum-prefix. Follow the MANRS (Mutually Agreed Norms for Routing Security) guidelines.

🔗 Related Terms

📚 Learn More