Algorithm Search⌘K

Algorithmadvanced

Route origin validation

Also called RPKI origin validation, ROV.

Marks each BGP route valid, invalid or not found by matching its prefix and origin AS against signed route origin authorizations.

Time
O(L + c) worst · averageO(1) best
Space
O(1) extra
Where
L = the length of the route prefix in bits; N = the number of VRPs; W = the address width; c = the number of VRPs that cover the route
Properties
deterministiconlinevalidates origin only
Origin
Pradosh Mohapatra, John Scudder, David Ward, Randy Bush, Rob Austein, 2013

Route origin validation (ROV) checks whether the autonomous system (AS) that originates a BGP route is allowed to originate that prefix. The allowed pairs come from route origin authorizations (ROAs): objects signed in the Resource Public Key Infrastructure (RPKI) by the holder of the address space, each naming one AS, some prefixes and a maximum length. A router reduces the validated ROAs to triples called VRPs and gives each route one of three states: Valid, Invalid or NotFound. The check catches announcements from the wrong AS, a common form of BGP prefix hijacking, but it does not check the rest of the AS path.

In plain words

The owner of a block of addresses signs a short statement: "only network 64496 may announce my block, and no piece smaller than this size". Routers collect these statements, check the signatures once, and keep a list.

When a route arrives, the router looks for statements about blocks that contain the announced block. If none exist, it knows nothing, and the route is "not found". If one of them names the network that announced the route and allows that size, the route is "valid". If statements exist but none fits, the route is "invalid", and the router can choose to drop it. The router only checks who started the route, not who passed it along.

The problem

Input. A set of VRPs, each a triple (prefix qq, maximum length ℓmax⁡\ell_{\max}, ASN aa), and a route with prefix PP of length ∣P∣|P| and an AS_PATH. The route origin ASN is the rightmost AS in the final segment of the AS_PATH if that segment is an AS_SEQUENCE; the speaker's own AS if the AS_PATH is empty or the final segment is a confederation segment; and the value NONE otherwise, for example for an AS_SET (RFC 6811, Section 2).

Definitions (RFC 6811, Section 2). A VRP covers PP if ∣q∣≤∣P∣|q| \le |P| and qq and PP agree on the first ∣q∣|q| bits. A VRP matches the route if it covers PP, ∣P∣≤ℓmax⁡|P| \le \ell_{\max}, and the origin ASN equals aa. No route matches a VRP whose ASN is 0, and NONE matches no VRP.

Output. Valid if at least one VRP matches; Invalid if at least one VRP covers PP but none matches; NotFound if no VRP covers PP.

The VRPs are stored in a trie keyed by the bits of their prefixes, one trie per address family. The covering VRPs of PP are exactly the VRPs stored at the nodes on the path from the root to PP.

The algorithm

  1. VALIDATE(T, P, origin) ▷ T: the trie of VRPs for the family of P
  2. 1state ← NotFound
  3. 2node ← the root of T
  4. 3for i ← 0 to |P| do ▷ node holds the prefix of the first i bits of P
  5. 4for each VRP (ℓmax, a) stored at node do
  6. 5state ← Invalid ▷ a VRP covers P
  7. 6if |P| ≤ ℓmax and origin ≠ NONE and a ≠ 0 and a = origin then return Valid
  8. 7if i = |P| or node has no child for bit i of P then stop the loop, else node ← that child
  9. 8return state

Line L5 records that PP is covered; line L6 tests the three conditions of a match and returns at the first one. The loop goes down the trie only along the bits of PP, so it visits the covering VRPs and nothing else. RFC 6811 gives similar pseudocode in Section 2.1 and states that the prose definitions are authoritative.

Example

All prefixes and AS numbers here are documentation values. The VRPs are:

VRP prefix max length ASN
192.0.2.0/24 24 64496
198.51.100.0/24 25 64497
203.0.113.0/24 24 0
2001:db8:1000::/36 48 64498

Routes received by a router in AS 64510:

route prefix AS_PATH origin covering VRPs state reason
192.0.2.0/24 64500 64496 64496 192.0.2.0/24 Valid covered, length 24 ≤ 24, ASN equal
192.0.2.0/25 64500 64496 64496 192.0.2.0/24 Invalid length 25 > 24
192.0.2.0/24 64500 64511 64511 192.0.2.0/24 Invalid ASN differs
198.51.100.128/25 64497 64497 198.51.100.0/24 Valid length 25 ≤ 25
203.0.113.0/24 64501 64501 203.0.113.0/24 Invalid a VRP with ASN 0 matches nothing
2001:db8:1000::/48 64500 64498 64498 2001:db8:1000::/36 Valid length 48 ≤ 48
2001:db8:1000::/48 64500 {64498 64499} NONE 2001:db8:1000::/36 Invalid the final segment is an AS_SET
2001:db8::/32 64499 64499 none NotFound the /36 VRP is longer, so it does not cover

The second and third rows are the two shapes of a hijack that ROV stops: a more specific prefix, and the wrong origin. The ASN 0 row shows how a holder says "this space must not be routed".

Correctness

Theorem. VALIDATE returns the state defined in RFC 6811, Section 2, for every set of VRPs and every route. This is a statement about the computation; the security guarantee is the next paragraph.

The proof shows that the nodes visited by lines L3 and L7 hold exactly the VRPs that cover PP: a VRP with prefix qq is stored at the node reached by the bits of qq, and that node lies on the path of PP if and only if ∣q∣≤∣P∣|q| \le |P| and qq is a prefix of the bits of PP. Line L6 then applies the definition of a match to each covering VRP. The full proof is in proofs/correctness.md.

Guarantee and its adversary. Assume that the RPKI data is correct and fresh, that the router validated the signatures, and that the attacker controls a BGP speaker but no RPKI key of the address holder. Then a route that the attacker originates from its own AS for a prefix covered by VRPs that do not name that AS is Invalid. The guarantee does not hold against an attacker who puts the authorized AS at the right end of a forged AS_PATH: RFC 6811, Section 6, states that such a forged origin defeats the check, since it validates the origin, not the path.

Proof: Correctness of route origin validation with a triefull

Setting. Addresses of one family have WW bits. For a prefix qq, write ∣q∣|q| for its length and q[0..∣q∣)q[0..|q|) for its first ∣q∣|q| bits; the remaining bits are 0. The trie TT has a root for the empty string, and the node for a bit string ss has a child for bit bb if some VRP prefix starts with sbs b. A VRP (q,ℓmax⁡,a)(q, \ell_{\max}, a) is stored at the node for q[0..∣q∣)q[0..|q|). The route has prefix PP and origin oo, which is an ASN or NONE.

Lemma 1 (the loop visits the path of PP). At the start of iteration ii of line L3, node is the node for P[0..i)P[0..i). The loop stops after iteration ii exactly when i=∣P∣i = |P| or no node exists for P[0..i+1)P[0..i+1).

Proof. At i=0i = 0, node is the root, the node for the empty string (line L2). If the loop continues after iteration ii, line L7 moves node to the child for bit P[i]P[i], which is the node for P[0..i+1)P[0..i+1). Line L7 stops the loop when i=∣P∣i = |P| or that child does not exist. □\square

Lemma 2 (the visited VRPs are the covering VRPs). The VRPs read at line L4, over the whole run, are exactly the VRPs that cover PP, unless the loop returns Valid earlier.

Proof. A VRP with prefix qq covers PP if and only if ∣q∣≤∣P∣|q| \le |P| and q[0..∣q∣)=P[0..∣q∣)q[0..|q|) = P[0..|q|) (RFC 6811, Section 2). If it covers PP, then the node for q[0..∣q∣)=P[0..∣q∣)q[0..|q|) = P[0..|q|) exists, since the VRP is stored there, and so do all nodes for the shorter strings P[0..i)P[0..i) with i≤∣q∣i \le |q|, since the trie contains every prefix of a stored string. By Lemma 1 the loop does not stop before iteration ∣q∣≤∣P∣|q| \le |P|, and at that iteration node is the node for q[0..∣q∣)q[0..|q|), so line L4 reads the VRP. Conversely, a VRP read at iteration ii is stored at the node for P[0..i)P[0..i) with i≤∣P∣i \le |P|, so its prefix qq has ∣q∣=i≤∣P∣|q| = i \le |P| and q[0..∣q∣)=P[0..∣q∣)q[0..|q|) = P[0..|q|), and it covers PP. Each node is visited at most once, so each VRP is read at most once. □\square

Theorem. VALIDATE(T,P,o)(T, P, o) returns Valid if at least one VRP matches the route, Invalid if at least one VRP covers PP and none matches, and NotFound if no VRP covers PP.

Proof. By RFC 6811, Section 2, a VRP (q,ℓmax⁡,a)(q, \ell_{\max}, a) matches the route if it covers PP, ∣P∣≤ℓmax⁡|P| \le \ell_{\max} and o=ao = a, with the extra rules that NONE matches no VRP and no route matches a VRP with a=0a = 0. Line L6 tests exactly these conditions for a covering VRP.

If some VRP matches, it covers PP, so by Lemma 2 line L4 reads it unless the loop has already returned Valid. When line L6 tests it, the test succeeds and the result is Valid. If the loop returns Valid, line L6 succeeded for a covering VRP, so that VRP matches.

If no VRP matches, line L6 never succeeds, and the loop ends at line L8 with state. The variable state is NotFound at line L1 and becomes Invalid at line L5 the first time a VRP is read. By Lemma 2, a VRP is read if and only if some VRP covers PP. So the result is Invalid if some VRP covers PP and NotFound otherwise. □\square

Cost. By Lemma 1 the loop runs at most ∣P∣+1|P| + 1 iterations, each with O(1)O(1) work outside line L4, and by Lemma 2 line L4 reads each of the cc covering VRPs at most once. The time is O(∣P∣+c)O(|P| + c). ■\blacksquare

Complexity

In the word RAM model with addresses of WW bits:

  • Time. VALIDATE visits at most ∣P∣+1≤W+1|P| + 1 \le W + 1 nodes and looks at each of the cc covering VRPs once, so it takes O(L+c)O(L + c) time with L=∣P∣L = |P|. The best case is O(1)O(1): the root has no child for the first bit, or a VRP at the root matches.
  • Space. The trie has O(NW)O(N W) nodes for NN VRPs; a path-compressed radix tree cuts this to O(N)O(N). VALIDATE itself needs O(1)O(1) extra space.
  • The oracle. A linear scan over all VRPs takes O(N)O(N) per route. The tests use it to check the trie.

Properties

  • Three states. NotFound keeps routes for space without ROAs usable during partial deployment.
  • Origin only. The AS path beyond the origin is not checked.
  • Monotone in VRPs. Adding a VRP can turn NotFound into Invalid or Valid, and Invalid into Valid, but never Valid into anything else.
  • Policy is local. RFC 6811 gives a state; each operator decides whether to drop Invalid routes or only prefer Valid ones.

Variants and improvements

  • Minimal ROAs. RFC 9319 (BCP 185) recommends ROAs that list only the prefixes actually announced and avoid a maxLength longer than needed. A loose maxLength lets an attacker announce an unused more specific prefix with a forged origin and win by longest prefix match while the route still validates (Section 3).
  • Path validation. BGPsec (RFC 8205) has each AS sign the path as it forwards the route, which closes the forged-origin gap at the cost of a digital signature per hop.
  • Data structures. Routers store VRPs in compressed tries or radix trees, the same structures used for forwarding tables.

When to use it

Use ROV on every BGP router that accepts routes from neighbors, together with ROAs for your own space, to reject wrong-origin and too-specific announcements. Use it with prefix filters for customers, which work without the RPKI, and consider BGPsec or other path checks where forged paths are a concern.

Pitfalls

  • Matching ASN 0. If line L6 omits a≠0a \ne 0, a route originated from AS 0, or a careless implementation that treats a missing origin as 0, can become Valid for space whose holder said it must not be routed. Keep the test a≠0a \ne 0 in line L6.
  • Checking only the longest covering VRP. If line L4 looks only at the VRP with the longest prefix, as in a forwarding lookup, a route covered by a /23 VRP for its origin and a /24 VRP for another AS becomes Invalid. Loop over every node from the root in line L3 and every VRP in line L4.
  • Forgetting the maximum length. If line L6 omits ∣P∣≤ℓmax⁡|P| \le \ell_{\max}, every more specific announcement by the authorized AS, and every forged-origin sub-prefix, validates. Keep the length test.
  • Taking the origin from an AS_SET. If the origin is read from an AS_SET as its last member, an attacker can list any AS in the set. Use NONE for an AS_SET, as RFC 6811 requires, so that line L6 never matches.
  • A loose maxLength in the ROA. The algorithm is correct, but a ROA with maxLength /32 for a /24 allows a forged-origin hijack of any unused /25 to /32. Publish minimal ROAs.

Implementations

The code is a synthetic model: it uses documentation prefixes and AS numbers, reads no RPKI data and speaks no BGP. It stores VRPs in a binary trie per family and checks it against a linear scan of the RFC 6811 definitions on 1500 random routes, together with the rules for the origin ASN.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

route_origin_validation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/route-origin-validation/. The authors are listed in prov/BC5B6R.jsonl.

"""Route origin validation of RFC 6811, Section 2, with a binary trie of VRPs.

A VRP (validated ROA payload) is (prefix, max_length, asn). A route is a
prefix and an AS_PATH given as a list of (segment_type, [asn, ...]). The
examples use documentation prefixes and documentation AS numbers only.
"""

from ipaddress import IPv4Network, IPv6Network, ip_network
from typing import Iterable

Network = IPv4Network | IPv6Network
Vrp = tuple[str, int, int]

NOT_FOUND, VALID, INVALID = "NotFound", "Valid", "Invalid"
NONE = None  # the distinguished origin "NONE" of RFC 6811


def origin_asn(as_path: list[tuple[str, list[int]]], own_as: int) -> int | None:
    """The route origin ASN of RFC 6811, Section 2.

    The rightmost AS of the final segment if it is an AS_SEQUENCE; the
    speaker's own AS if the path is empty or the final segment is a
    confederation segment; NONE otherwise (for example an AS_SET). Cost: O(1).
    """
    if not as_path:
        return own_as
    kind, asns = as_path[-1]
    if kind == "AS_SEQUENCE" and asns:
        return asns[-1]
    if kind in ("AS_CONFED_SEQUENCE", "AS_CONFED_SET"):
        return own_as
    return NONE


def bits(net: Network) -> int:
    """The prefix address as an integer of 32 or 128 bits."""
    return int(net.network_address)


class _Node:
    __slots__ = ("child", "vrps")

    def __init__(self) -> None:
        self.child: list["_Node | None"] = [None, None]
        self.vrps: list[tuple[int, int]] = []  # (max_length, asn)


class VrpTrie:
    """A binary trie per address family; each VRP is stored at the node of its prefix."""

    def __init__(self, vrps: Iterable[Vrp] = ()) -> None:
        """Cost: O(total prefix length of the VRPs)."""
        self.roots = {4: _Node(), 6: _Node()}
        for v in vrps:
            self.add(v)

    def add(self, vrp: Vrp) -> None:
        """Precondition: prefix is a valid network and len <= max_length <= width."""
        prefix, max_length, asn = vrp
        net = ip_network(prefix)
        width = net.max_prefixlen
        node = self.roots[net.version]
        a = bits(net)
        for i in range(net.prefixlen):
            b = (a >> (width - 1 - i)) & 1
            if node.child[b] is None:
                node.child[b] = _Node()
            node = node.child[b]
        node.vrps.append((max_length, asn))

    def validate(self, prefix: str, origin: int | None) -> str:
        """The validation state of a route with this prefix and origin ASN.

        Visits only the nodes on the path of the prefix, so the cost is
        O(len + c) for a prefix of length len and c covering VRPs.
        """
        net = ip_network(prefix)
        width, length, a = net.max_prefixlen, net.prefixlen, bits(net)
        state = NOT_FOUND  # @line L1
        node = self.roots[net.version]  # @line L2
        for i in range(length + 1):  # @line L3
            for max_length, asn in node.vrps:  # @line L4
                state = INVALID  # @line L5
                if length <= max_length and origin is not NONE and asn != 0 and asn == origin:  # @line L6
                    return VALID
            if i == length:  # @line L7
                break
            node = node.child[(a >> (width - 1 - i)) & 1]
            if node is None:
                break
        return state  # @line L8


def validate_linear(vrps: Iterable[Vrp], prefix: str, origin: int | None) -> str:
    """The oracle: the definitions of RFC 6811, Section 2, checked VRP by VRP. Cost: O(|vrps|)."""
    route = ip_network(prefix)
    covered = matched = False
    for p, max_length, asn in vrps:
        q = ip_network(p)
        if q.version != route.version or q.prefixlen > route.prefixlen:
            continue
        if route.supernet(new_prefix=q.prefixlen) != q:
            continue
        covered = True
        if route.prefixlen <= max_length and origin is not NONE and asn != 0 and origin == asn:
            matched = True
    if matched:
        return VALID
    return INVALID if covered else NOT_FOUND
test_route_origin_validation.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/route-origin-validation/. The authors are listed in prov/BC5B6R.jsonl.

import random
from ipaddress import ip_address, ip_network

from route_origin_validation import (
    INVALID,
    NONE,
    NOT_FOUND,
    VALID,
    VrpTrie,
    origin_asn,
    validate_linear,
)

EXAMPLE_VRPS = [
    ("192.0.2.0/24", 24, 64496),
    ("198.51.100.0/24", 25, 64497),
    ("203.0.113.0/24", 24, 0),
    ("2001:db8:1000::/36", 48, 64498),
]

EXAMPLE_ROUTES = [
    ("192.0.2.0/24", [("AS_SEQUENCE", [64500, 64496])], VALID),
    ("192.0.2.0/25", [("AS_SEQUENCE", [64500, 64496])], INVALID),
    ("192.0.2.0/24", [("AS_SEQUENCE", [64500, 64511])], INVALID),
    ("198.51.100.128/25", [("AS_SEQUENCE", [64497])], VALID),
    ("203.0.113.0/24", [("AS_SEQUENCE", [64501])], INVALID),
    ("2001:db8:1000::/48", [("AS_SEQUENCE", [64500, 64498])], VALID),
    ("2001:db8:1000::/48", [("AS_SEQUENCE", [64500]), ("AS_SET", [64498, 64499])], INVALID),
    ("2001:db8::/32", [("AS_SEQUENCE", [64499])], NOT_FOUND),
]

OWN_AS = 64510


def test_example() -> None:
    trie = VrpTrie(EXAMPLE_VRPS)
    for prefix, path, want in EXAMPLE_ROUTES:
        origin = origin_asn(path, OWN_AS)
        assert trie.validate(prefix, origin) == want, prefix
        assert validate_linear(EXAMPLE_VRPS, prefix, origin) == want


def test_origin_asn() -> None:
    assert origin_asn([], OWN_AS) == OWN_AS
    assert origin_asn([("AS_SEQUENCE", [64496, 64497])], OWN_AS) == 64497
    assert origin_asn([("AS_SEQUENCE", [64496]), ("AS_SET", [64497])], OWN_AS) is NONE
    assert origin_asn([("AS_CONFED_SEQUENCE", [64505])], OWN_AS) == OWN_AS
    assert origin_asn([("AS_CONFED_SET", [64505])], OWN_AS) == OWN_AS


def test_edges() -> None:
    empty = VrpTrie()
    assert empty.validate("192.0.2.0/24", 64496) == NOT_FOUND
    # NONE never matches, even a VRP that would cover and fit.
    assert VrpTrie(EXAMPLE_VRPS).validate("192.0.2.0/24", NONE) == INVALID
    # A VRP for ASN 0 never matches, even a route with origin 0.
    assert VrpTrie([("203.0.113.0/24", 24, 0)]).validate("203.0.113.0/24", 0) == INVALID
    # One matching VRP is enough, even when others cover with other ASNs.
    both = VrpTrie([("192.0.2.0/24", 24, 64511), ("192.0.2.0/23", 24, 64496)])
    assert both.validate("192.0.2.0/24", 64496) == VALID
    # Host routes, and families kept apart.
    assert VrpTrie([("192.0.2.0/24", 32, 64496)]).validate("192.0.2.1/32", 64496) == VALID
    t = VrpTrie([("192.0.2.0/24", 24, 64496)])
    assert t.validate("192.0.2.1/32", 64496) == INVALID
    assert t.validate("2001:db8::/32", 64496) == NOT_FOUND
    # A more specific VRP does not cover a less specific route.
    assert VrpTrie([("192.0.2.128/25", 25, 64496)]).validate("192.0.2.0/24", 64511) == NOT_FOUND


BASES = [ip_network("192.0.2.0/24"), ip_network("198.51.100.0/24"), ip_network("2001:db8::/32")]


def random_prefix(rng: random.Random, base, extra: int) -> str:
    length = base.prefixlen + rng.randrange(0, extra + 1)
    width = base.max_prefixlen
    host = rng.getrandbits(extra) << (width - base.prefixlen - extra) if extra else 0
    addr = int(base.network_address) | host
    net = ip_network((ip_address(addr), length), strict=False)
    return str(net)


def test_random_against_oracle() -> None:
    """The trie agrees with the linear scan of the definitions on random VRP sets and routes."""
    rng = random.Random(6811)
    asns = list(range(64496, 64500)) + [0]
    counts = {VALID: 0, INVALID: 0, NOT_FOUND: 0}
    for _ in range(300):
        extra = rng.randrange(0, 5)
        vrps = []
        for _ in range(rng.randrange(0, 8)):
            base = rng.choice(BASES)
            p = random_prefix(rng, base, extra)
            plen = ip_network(p).prefixlen
            max_length = rng.randrange(plen, min(plen + 4, ip_network(p).max_prefixlen) + 1)
            vrps.append((p, max_length, rng.choice(asns)))
        trie = VrpTrie(vrps)
        for _ in range(5):
            route = random_prefix(rng, rng.choice(BASES), extra + 1)
            origin = rng.choice(asns + [NONE])
            got = trie.validate(route, origin)
            assert got == validate_linear(vrps, route, origin)
            counts[got] += 1
    assert min(counts.values()) > 50

History

The RPKI architecture appeared as RFC 6480 in February 2012, with ROAs binding an AS to prefixes. Mohapatra, Scudder, Ward, Bush and Austein specified the validation procedure in RFC 6811 in January 2013. BGPsec followed in RFC 8205 in 2017 to protect the whole path, and RFC 9319 in 2022 gave advice on maxLength, because loose ROAs leave space open to forged-origin sub-prefix hijacks.

References

  1. P. Mohapatra, J. Scudder, D. Ward, R. Bush and R. Austein, BGP Prefix Origin Validation, RFC 6811, January 2013, Section 2 (Covered, Matched, the three states, the route origin ASN and AS 0), Section 2.1 (pseudocode, with the prose authoritative) and Section 6 (forged origins are not prevented)
  2. M. Lepinski and S. Kent, An Infrastructure to Support Secure Internet Routing, RFC 6480, February 2012, Section 3 (route origin authorizations)
  3. Y. Gilad, S. Goldberg, K. Sriram, J. Snijders and B. Maddison, The Use of maxLength in the Resource Public Key Infrastructure (RPKI), RFC 9319, BCP 185, October 2022, Section 3 (forged-origin sub-prefix hijacks) and Section 5 (minimal ROAs)
  4. M. Lepinski and K. Sriram (editors), BGPsec Protocol Specification, RFC 8205, September 2017, the abstract and the introduction (signatures over the AS path)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example