Algorithm Search⌘K

Algorithmadvanced

Firewall policy anomaly detection

Also called Al-Shaer firewall analysis, rule shadowing detection.

Finds shadowed, redundant, generalized and correlated rules in an ordered firewall rule list by comparing the packet sets of rule pairs.

Time
Θ(m^2 d) worst · average · best
Space
O(1) extra
Where
d = the number of header fields; m = the number of rules
Properties
deterministic
Origin
Ehab Al Shaer, Hazem Hamed, 2004

Firewall policy anomaly detection checks an ordered list of firewall rules for pairs of rules that conflict or repeat each other. Each rule matches a set of packets, given by one interval for each header field, such as the protocol, the source and destination addresses and the ports, and the first rule that matches a packet decides it. For an earlier rule RxR_x and a later rule RyR_y, Al-Shaer and Hamed (2004) named four classes: shadowing, where RyR_y never acts because RxR_x catches all its packets with another action; redundancy, where a rule can be removed without a change; generalization, where RyR_y covers RxR_x with another action; and correlation, where the two overlap partly with different actions. The check compares each pair of rules in Θ(m2d)\Theta(m^2 d) time for mm rules of dd fields. It is exact for each pair, but it is not a full check of the policy: a rule can be covered by several earlier rules together, and no single pair shows that. The analysis only reads the rule list and needs no access to a network.

In plain words

A firewall reads its rules from the top and uses the first rule that fits a packet. Rules are easy to add and hard to keep in order, so a long list often has mistakes.

The check looks at each pair of rules, an earlier one and a later one, and asks how the packets they match relate. If the earlier rule already catches every packet of the later rule with another answer, the later rule can never act, which is shadowing. If a rule could be deleted and every packet would get the same answer, it is redundant. If a later rule is wider and gives the other answer, it is a generalization, which is often on purpose but worth a look. If the two rules overlap only in part and give different answers, the order decides the overlap, which is a correlation.

The problem

A rule RiR_i has a box Bi=Ii,1×⋯×Ii,dB_i = I_{i,1} \times \cdots \times I_{i,d}, a product of dd non-empty integer intervals, and an action such as allow or deny. An address prefix such as 192.0.2.0/24 is the interval of its addresses, and "any" is the full range. The decision on a packet pp is the action of the first RiR_i with p∈Bip \in B_i, or a default action. The input is the list R1,…,RmR_1, \ldots, R_m. The output is the list of pairs x<yx < y in each class:

  • shadowing: By⊆BxB_y \subseteq B_x and the actions differ;
  • redundancy (later): By⊆BxB_y \subseteq B_x and the actions are the same, so RyR_y can be removed;
  • generalization: Bx⊊ByB_x \subsetneq B_y and the actions differ;
  • redundancy (earlier): Bx⊊ByB_x \subsetneq B_y, the actions are the same, and no rule between them meets BxB_x with another action, so RxR_x can be removed;
  • correlation: BxB_x and ByB_y meet, neither contains the other, and the actions differ.

The algorithm

  1. ANOMALIES(R[1..m])
  2. 1A ← empty list
  3. 2for x ← 1 to m - 1 do
  4. 3blocked ← false ▷ a rule after x meets R[x] with another action
  5. 4for y ← x + 1 to m do
  6. 5rel ← RELATION(B[x], B[y]) ; same ← (action[x] = action[y])
  7. 6if rel ≠ DISJOINT then
  8. 7if rel ∈ {EQUAL, SUPERSET} then add (same ? REDUNDANT-LATER : SHADOWING, x, y)
  9. 8else if rel = SUBSET and not same then add (GENERALIZATION, x, y)
  10. 9else if rel = SUBSET and not blocked then add (REDUNDANT-EARLIER, x, y)
  11. 10else if rel = CORRELATED and not same then add (CORRELATION, x, y)
  12. 11if not same then blocked ← true
  13. 12return A

RELATION compares the boxes field by field. Two boxes are disjoint if some pair of intervals is disjoint. Box BxB_x is inside ByB_y if each interval of BxB_x is inside the interval of ByB_y in the same field. SUBSET means that BxB_x is strictly inside ByB_y, and SUPERSET means the reverse. The flag of line L3 records, for the fixed xx, whether some rule after xx and before the current yy meets BxB_x with another action. Line L11 updates it after the tests of the current pair, so line L9 sees only the rules strictly between xx and yy.

The code also has IS-DEAD, which decides whether a rule is covered by the union of all earlier rules. It subtracts each earlier box from the pieces of the rule that remain; the difference of two boxes is at most 2d2d disjoint boxes.

Example

The policy uses documentation addresses only. The fields are protocol, source, source port, destination and destination port, and the default action is deny.

rule protocol source source port destination destination port action
R1R_1 tcp 198.51.100.0/25 any 203.0.113.10 80 allow
R2R_2 tcp 198.51.100.0/24 any 203.0.113.10 80 deny
R3R_3 tcp 198.51.100.200 any 203.0.113.10 80 allow
R4R_4 tcp 198.51.100.128/26 any 203.0.113.0/24 any allow
R5R_5 udp 192.0.2.53 53 203.0.113.0/24 any allow
R6R_6 udp 192.0.2.0/24 53 203.0.113.0/24 any allow
R7R_7 udp 192.0.2.10 53 203.0.113.5 53 allow

ANOMALIES reports one pair of each class. All other pairs are disjoint, because the protocols, the source blocks or the destinations do not meet.

pair relation line class meaning
R1,R2R_1, R_2 B1⊊B2B_1 \subsetneq B_2 L8 generalization R2R_2 denies the rest of 198.51.100.0/24 after R1R_1 allows the first half
R2,R3R_2, R_3 B3⊆B2B_3 \subseteq B_2 L7 shadowing R3R_3 never acts: R2R_2 denies all its packets
R2,R4R_2, R_4 correlated L10 correlation from 198.51.100.128/26 to 203.0.113.10 port 80, R2R_2 denies what R4R_4 allows
R5,R6R_5, R_6 B5⊊B6B_5 \subsetneq B_6 L9 redundancy (earlier) R5R_5 can be removed
R6,R7R_6, R_7 B7⊆B6B_7 \subseteq B_6 L7 redundancy (later) R7R_7 can be removed

For x=5x = 5, no rule between R5R_5 and R6R_6 exists, so blocked is false at line L9. A packet from 198.51.100.150 to 203.0.113.10 port 80 is denied by R2R_2, and the same packet to 203.0.113.11 is allowed by R4R_4. The correlation is a question for the administrator: maybe R4R_4 was meant to come first.

Correctness

RELATION is exact because a box is a product of intervals: two boxes meet if and only if every pair of intervals meets, and one box is inside another if and only if each of its intervals is. Lines L7 to L10 then test the five definitions directly, and the flag of line L3 is true at line L9 exactly when some rule strictly between xx and yy meets BxB_x with another action. A shadowed or later-redundant rule never decides a packet, because each of its packets is caught by RxR_x first. Removing an earlier-redundant RxR_x changes no decision: a packet that RxR_x decided now reaches either a rule between the two, which has the same action, or RyR_y, which has the same action. The full proofs are in proofs/correctness.md.

Proof: The pairwise anomaly classes of a firewall policy are computed exactly, and the redundant rules can be removedfull

We use the pseudocode ANOMALIES of the page. A policy is a list of rules R1,…,RmR_1, \ldots, R_m. Each rule has a box Bi=Ii,1×⋯×Ii,dB_i = I_{i,1} \times \cdots \times I_{i,d}, a product of dd non-empty closed integer intervals, and an action. A packet pp is a point of the header space. The decision of the policy on pp is the action of the first rule whose box contains pp, or a default action when there is none. For x<yx < y we write ax,aya_x, a_y for the actions.

Lemma 1 (relations of boxes). RELATION(Bx,By)(B_x, B_y) returns DISJOINT if Bx∩By=∅B_x \cap B_y = \emptyset, EQUAL if Bx=ByB_x = B_y, SUBSET if Bx⊊ByB_x \subsetneq B_y, SUPERSET if Bx⊋ByB_x \supsetneq B_y, and CORRELATED otherwise.

Proof. A point is in Bx∩ByB_x \cap B_y if and only if each coordinate is in both intervals, so the boxes meet if and only if each pair of intervals meets. Since all intervals are non-empty, Bx⊆ByB_x \subseteq B_y if and only if Ix,j⊆Iy,jI_{x,j} \subseteq I_{y,j} for each jj: if one interval of BxB_x has a point vv outside the matching interval of ByB_y, then a point of BxB_x with coordinate vv and any other coordinates in BxB_x is not in ByB_y. The code tests these interval conditions, and the five cases follow. □\square

Claim 1 (exact classes). For each pair x<yx < y, ANOMALIES reports

  • shadowing if By⊆BxB_y \subseteq B_x and ax≠aya_x \ne a_y;
  • redundancy-later, with RyR_y removable, if By⊆BxB_y \subseteq B_x and ax=aya_x = a_y;
  • generalization if Bx⊊ByB_x \subsetneq B_y and ax≠aya_x \ne a_y;
  • redundancy-earlier, with RxR_x removable, if Bx⊊ByB_x \subsetneq B_y, ax=aya_x = a_y, and no zz with x<z<yx < z < y has Bz∩Bx≠∅B_z \cap B_x \ne \emptyset and az≠axa_z \ne a_x;
  • correlation if the boxes meet, neither contains the other, and ax≠aya_x \ne a_y;

and nothing else.

Proof. Fix xx. The inner loop of line L4 runs y=x+1,…,my = x + 1, \ldots, m in order. We show the invariant: when the iteration for yy starts, blocked is true if and only if some zz with x<z<yx < z < y has Bz∩Bx≠∅B_z \cap B_x \ne \emptyset and az≠axa_z \ne a_x. Line L3 makes it true for y=x+1y = x + 1. Line L11 sets blocked exactly when the current yy meets BxB_x (line L6) and has another action, so the invariant holds for y+1y + 1.

By Lemma 1 the test of line L6 skips exactly the disjoint pairs. Line L7 handles EQUAL and SUPERSET, which together mean By⊆BxB_y \subseteq B_x. Line L8 handles SUBSET with different actions. Line L9 is reached with SUBSET only when the actions are the same, and by the invariant it reports exactly when no such zz exists. Line L10 handles CORRELATED with different actions. The remaining cases, SUBSET with the same action and blocked, and CORRELATED with the same action, report nothing. □\square

Claim 2 (meaning of the classes).

  1. If RyR_y is shadowed or later-redundant, RyR_y decides no packet.
  2. If RyR_y is later-redundant, removing it changes no decision.
  3. If RxR_x is earlier-redundant with RyR_y, removing RxR_x changes no decision.

Proof. (1) Each p∈Byp \in B_y is in BxB_x with x<yx < y, so the first match of pp is at most xx. (2) By (1) no packet has RyR_y as its first match, and the first match of each packet is the same rule with or without RyR_y.

(3) Let pp be a packet. If p∉Bxp \notin B_x, then RxR_x is not a match of pp, and the first match is the same rule with or without RxR_x. If the first match of pp is a rule before xx, it stays the first match. Otherwise the first match of pp is RxR_x and the decision is axa_x. After removing RxR_x, the first match of pp is the first z>xz > x with p∈Bzp \in B_z. If x<z<yx < z < y, then BzB_z meets BxB_x at pp, and by the condition az=axa_z = a_x. If there is no such zz, then p∈Bx⊆Byp \in B_x \subseteq B_y, so RyR_y is the first match, and ay=axa_y = a_x. In each case the decision stays axa_x. □\square

Remark (the condition of line L9). The condition must cover every rule between xx and yy that meets BxB_x with another action, including one inside BxB_x. With B1⊊B3B_1 \subsetneq B_3, a1=a3a_1 = a_3 and B2⊊B1B_2 \subsetneq B_1 with a2≠a1a_2 \ne a_1, the pair (R1,R2)(R_1, R_2) is a shadowing anomaly, not a generalization or a correlation, but removing R1R_1 changes the decision on B2B_2 from a1a_1 to a2a_2. A condition that only looks for generalization and correlation anomalies of RxR_x would call R1R_1 removable here. The test checks this case.

Limits. The classes are pairwise. A rule can be covered by the union of earlier rules without being inside any one of them, and then it decides no packet but no pair reports shadowing. The function IS-DEAD of the code finds this by subtracting each earlier box from the boxes that remain. Subtracting one box from another gives at most 2d2d disjoint boxes, so it is exact, but the number of pieces can grow exponentially with the number of rules.

Cost. Line L5 costs O(d)O(d) by Lemma 1, and lines L6 to L11 cost O(1)O(1) more, for each of the m(m−1)/2m(m-1)/2 pairs. So ANOMALIES takes Θ(m2d)\Theta(m^2 d) time on the word-RAM, and O(1)O(1) extra space besides the output, which has at most m(m−1)/2m(m-1)/2 entries. ■\blacksquare

Complexity

  • Time. Line L5 compares dd pairs of intervals, and lines L6 to L11 add constant work, for each of the m(m−1)/2m(m-1)/2 pairs. So the time is Θ(m2d)\Theta(m^2 d) on the word-RAM in every case.
  • Space. O(1)O(1) extra besides the output list, which can hold up to m(m−1)/2m(m-1)/2 pairs.
  • Union coverage. IS-DEAD is exact but can produce a number of pieces that grows exponentially with the number of rules. It is for small policies or for one suspect rule.

Properties

  • Pairwise. Each class is about one pair. The output lists conflicts to review; it does not say which rule is wrong.
  • Exact for each pair. Integer intervals make the relations exact, with no sampling of packets.
  • Not complete for the policy. A rule covered by a union of earlier rules is dead but can show only generalization or correlation pairs.
  • Read only. The check works on the text of the rules and never sends a packet.

Variants and improvements

  • Policy tree. Al-Shaer and Hamed store the rules in a tree with one level for each field, so that rules that share field values share a path. This finds the same anomalies and avoids comparing rules that differ in an early field.
  • Distributed firewalls. Their INFOCOM 2004 paper also checks rules on different firewalls of a path, for example a packet that one firewall allows and a later one blocks.
  • Decision diagrams. A binary decision diagram or a firewall decision diagram represents the whole decision function, so it can find dead rules that are covered by a union and compare two policies exactly.
  • Faster pair search. For large rule sets, interval trees or range trees on one or two fields find the pairs that meet without comparing all pairs. The same structures appear in packet classification.

When to use it

Use the pairwise check before loading a changed rule list, or as part of a review of an access control list on a router or a host firewall. It is quick, its classes are easy to explain, and each finding names two rules. Generalization is often intended, for example a final rule that denies all traffic after specific allow rules, so a tool should report it with a lower weight. When the question is whether a rule can ever act, or whether two policies decide every packet the same way, use the union check or a decision diagram, since pairs alone can miss it.

Pitfalls

  • Only equal boxes in line L7. If line L7 tests only rel = EQUAL, a later rule strictly inside a wider earlier rule is not reported as shadowed, which is the most common case. Line L7 must test EQUAL and SUPERSET, which together mean By⊆BxB_y \subseteq B_x.
  • A weak test in line L9. If line L9 reports redundancy without the blocked flag, or with a flag that only counts rules in a generalization or correlation with RxR_x, then a rule between them that lies inside BxB_x with another action is missed. Removing RxR_x would then change the decision on that rule's packets. Line L11 must set the flag for every rule that meets BxB_x with another action.
  • Updating the flag too early. If line L11 runs before line L9 for the same yy, a rule RyR_y with another action blocks itself. That is harmless only because line L9 needs the same action; if the classes change, keep the update after the tests.
  • Trusting the pairs. A rule covered by two earlier rules together never acts, but each pair shows only a correlation or a generalization. Use IS-DEAD or a decision diagram for that question.
  • Mixed address families. An IPv4 prefix and an IPv6 prefix such as 2001:db8::/32 must not be compared as integers in one field. Use a separate field or a separate policy for each family.

Implementations

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.

firewall_policy_anomaly_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/firewall-policy-anomaly-detection/. The authors are listed in prov/MRZ666.jsonl.

"""Anomalies between pairs of rules in an ordered firewall policy.

A rule matches a box: one closed integer interval for each header field, for
example protocol, source address, source port, destination address and
destination port. The first rule that matches a packet decides it. For an
earlier rule Rx and a later rule Ry, the classes follow Al-Shaer and Hamed
(2004):

* shadowing: Ry is inside Rx and the actions differ, so Ry never acts;
* redundancy-later: Ry is inside Rx with the same action, so Ry can go;
* generalization: Rx is strictly inside Ry and the actions differ;
* redundancy-earlier: Rx is strictly inside Ry with the same action, and no
  rule between them meets Rx with another action, so Rx can go;
* correlation: the boxes overlap, neither contains the other, and the actions
  differ.

The code only reads rule lists. It does not touch any network.
"""

import ipaddress
from typing import NamedTuple, Optional

Box = tuple  # ((lo, hi), ...) with lo <= hi in each field

DISJOINT, EQUAL, SUBSET, SUPERSET, CORRELATED = "disjoint", "equal", "subset", "superset", "correlated"


class Rule(NamedTuple):
    box: Box
    action: str


class Anomaly(NamedTuple):
    kind: str
    x: int  # 1-based index of the earlier rule
    y: int  # 1-based index of the later rule
    removable: Optional[int]  # the rule that can be removed, if any


def relation(a: Box, b: Box) -> str:
    """How box a relates to box b. SUBSET means a is strictly inside b.

    Cost: O(d) for d fields. A box is a product of intervals, so a is inside b
    exactly when each interval of a is inside the one of b.
    """
    a_in_b = b_in_a = True
    for (alo, ahi), (blo, bhi) in zip(a, b, strict=True):
        if ahi < blo or bhi < alo:
            return DISJOINT
        a_in_b = a_in_b and blo <= alo and ahi <= bhi
        b_in_a = b_in_a and alo <= blo and bhi <= ahi
    if a_in_b and b_in_a:
        return EQUAL
    if a_in_b:
        return SUBSET
    if b_in_a:
        return SUPERSET
    return CORRELATED


def anomalies(rules: list[Rule]) -> list[Anomaly]:
    """ANOMALIES of the page. Cost: O(m^2 d) for m rules of d fields."""
    out: list[Anomaly] = []  # @line L1
    for x in range(len(rules)):  # @line L2
        blocked = False  # @line L3
        for y in range(x + 1, len(rules)):  # @line L4
            rel = relation(rules[x].box, rules[y].box)  # @line L5
            same = rules[x].action == rules[y].action
            if rel != DISJOINT:  # @line L6
                if rel in (EQUAL, SUPERSET):  # @line L7
                    kind = "redundancy-later" if same else "shadowing"
                    out.append(Anomaly(kind, x + 1, y + 1, y + 1 if same else None))
                elif rel == SUBSET and not same:  # @line L8
                    out.append(Anomaly("generalization", x + 1, y + 1, None))
                elif rel == SUBSET and not blocked:  # @line L9
                    out.append(Anomaly("redundancy-earlier", x + 1, y + 1, x + 1))
                elif rel == CORRELATED and not same:  # @line L10
                    out.append(Anomaly("correlation", x + 1, y + 1, None))
                if not same:  # @line L11
                    blocked = True
    return out  # @line L12


def decide(rules: list[Rule], packet: tuple, default: str = "deny") -> str:
    """The action of the first rule that matches, or the default."""
    for r in rules:
        if all(lo <= v <= hi for (lo, hi), v in zip(r.box, packet, strict=True)):
            return r.action
    return default


def subtract(a: Box, b: Box) -> list[Box]:
    """Disjoint boxes whose union is a minus b. At most 2d of them."""
    if relation(a, b) == DISJOINT:
        return [a]
    out = []
    cur = list(a)
    for i, ((lo, hi), (blo, bhi)) in enumerate(zip(a, b, strict=True)):
        if lo < blo:
            out.append(tuple(cur[:i] + [(lo, blo - 1)] + cur[i + 1 :]))
        if bhi < hi:
            out.append(tuple(cur[:i] + [(bhi + 1, hi)] + cur[i + 1 :]))
        cur[i] = (max(lo, blo), min(hi, bhi))
    return out


def is_dead(rules: list[Rule], y: int) -> bool:
    """True when the earlier rules together cover rule y (1-based), so it never
    decides a packet. This catches shadowing by a union of rules, which the
    pairwise test misses. The number of pieces can grow fast with the rules."""
    pieces = [rules[y - 1].box]
    for r in rules[: y - 1]:
        pieces = [p for piece in pieces for p in subtract(piece, r.box)]
        if not pieces:
            return True
    return False


ANY_PORT = (0, 65535)
ANY_PROTOCOL = (0, 255)
PROTOCOL = {"tcp": (6, 6), "udp": (17, 17), "any": ANY_PROTOCOL}


def prefix(s: str) -> tuple[int, int]:
    """The address interval of an IPv4 or IPv6 prefix such as 192.0.2.0/24."""
    net = ipaddress.ip_network(s, strict=True)
    return int(net.network_address), int(net.broadcast_address)


def port(s: str) -> tuple[int, int]:
    if s == "any":
        return ANY_PORT
    lo, _, hi = s.partition("-")
    return int(lo), int(hi or lo)


def rule(protocol: str, src: str, sport: str, dst: str, dport: str, action: str) -> Rule:
    """A rule from text fields, in the order of the page."""
    return Rule((PROTOCOL[protocol], prefix(src), port(sport), prefix(dst), port(dport)), action)
test_firewall_policy_anomaly_detection.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/firewall-policy-anomaly-detection/. The authors are listed in prov/MRZ666.jsonl.

import functools
import itertools
import random

import pytest

from firewall_policy_anomaly_detection import (
    Anomaly,
    Rule,
    anomalies,
    decide,
    is_dead,
    prefix,
    relation,
    rule,
    subtract,
)

# The rules only use documentation addresses (RFC 5737 and RFC 3849). The
# code reads rule lists and never touches a network.

# A small universe: protocol 0..1 and four other fields 0..3, 512 packets.
SIZES = [2, 4, 4, 4, 4]
PACKETS = list(itertools.product(*[range(s) for s in SIZES]))
ACTIONS = ["allow", "deny"]


@functools.lru_cache(maxsize=None)
def packet_set(box) -> int:
    """The packets of a box as a bit mask over PACKETS."""
    mask = 0
    for i, p in enumerate(PACKETS):
        if all(lo <= v <= hi for (lo, hi), v in zip(box, p)):
            mask |= 1 << i
    return mask


def random_box(rng: random.Random):
    out = []
    for s in SIZES:
        a, b = sorted((rng.randrange(s), rng.randrange(s)))
        if rng.random() < 0.3:
            a, b = 0, s - 1
        out.append((a, b))
    return tuple(out)


def random_policy(rng: random.Random, m: int) -> list:
    return [Rule(random_box(rng), rng.choice(ACTIONS)) for _ in range(m)]


def oracle_anomalies(rules: list) -> list:
    """The same classes, decided on explicit packet sets."""
    sets = [packet_set(r.box) for r in rules]
    out = []
    for x, y in itertools.combinations(range(len(rules)), 2):
        sx, sy = sets[x], sets[y]
        same = rules[x].action == rules[y].action
        if sx & sy == 0:
            continue
        if sy & ~sx == 0:
            out.append(Anomaly("redundancy-later" if same else "shadowing", x + 1, y + 1, y + 1 if same else None))
        elif sx & ~sy == 0:
            if not same:
                out.append(Anomaly("generalization", x + 1, y + 1, None))
            elif not any(sets[z] & sx and rules[z].action != rules[x].action for z in range(x + 1, y)):
                out.append(Anomaly("redundancy-earlier", x + 1, y + 1, x + 1))
        elif not same:
            out.append(Anomaly("correlation", x + 1, y + 1, None))
    return out


def decisions(rules: list) -> list:
    return [decide(rules, p) for p in PACKETS]


def test_relation_against_sets() -> None:
    rng = random.Random(2004)
    for _ in range(1500):
        a, b = random_box(rng), random_box(rng)
        sa, sb = packet_set(a), packet_set(b)
        if sa & sb == 0:
            expected = "disjoint"
        elif sa == sb:
            expected = "equal"
        elif sa & ~sb == 0:
            expected = "subset"
        elif sb & ~sa == 0:
            expected = "superset"
        else:
            expected = "correlated"
        assert relation(a, b) == expected


def test_anomalies_against_oracle() -> None:
    rng = random.Random(7)
    found = set()
    for _ in range(300):
        rules = random_policy(rng, rng.randint(1, 8))
        got = anomalies(rules)
        assert sorted(got) == sorted(oracle_anomalies(rules))
        found |= {a.kind for a in got}
    assert found == {"shadowing", "redundancy-later", "generalization", "redundancy-earlier", "correlation"}


def test_meaning_of_the_classes() -> None:
    """A shadowed or later redundant rule never decides a packet, and removing
    a redundant rule leaves every decision as it was."""
    rng = random.Random(11)
    checked = 0
    for _ in range(160):
        rules = random_policy(rng, rng.randint(2, 7))
        before = decisions(rules)
        for a in anomalies(rules):
            if a.kind in ("shadowing", "redundancy-later"):
                assert is_dead(rules, a.y)
            if a.removable is not None:
                rest = rules[: a.removable - 1] + rules[a.removable :]
                assert decisions(rest) == before
                checked += 1
    assert checked > 50


def test_published_redundancy_condition_is_not_enough() -> None:
    """R2 lies inside R1 with another action. It is shadowed by R1, not in a
    generalization or correlation with it, but removing R1 still changes the
    decision of R2's packets. The check of line L9 sees R2 and keeps R1."""
    r1 = Rule(((0, 1), (0, 1), (0, 3), (0, 3), (0, 3)), "allow")
    r2 = Rule(((0, 1), (0, 0), (0, 3), (0, 3), (0, 3)), "deny")
    r3 = Rule(((0, 1), (0, 3), (0, 3), (0, 3), (0, 3)), "allow")
    rules = [r1, r2, r3]
    kinds = {(a.kind, a.x, a.y) for a in anomalies(rules)}
    assert ("shadowing", 1, 2) in kinds
    assert ("redundancy-earlier", 1, 3) not in kinds
    assert decisions([r2, r3]) != decisions(rules)


def test_union_shadowing_needs_more_than_pairs() -> None:
    r1 = Rule(((0, 1), (0, 1), (0, 3), (0, 3), (0, 3)), "deny")
    r2 = Rule(((0, 1), (2, 3), (0, 3), (0, 3), (0, 3)), "deny")
    r3 = Rule(((0, 1), (0, 3), (0, 3), (0, 0), (0, 3)), "allow")
    rules = [r1, r2, r3]
    # R3 meets R1 and R2 but lies inside neither, so the pairs only show correlation.
    assert {a.kind for a in anomalies(rules)} == {"correlation"}
    assert is_dead(rules, 3)
    assert not is_dead(rules, 2)


def test_is_dead_and_subtract_against_sets() -> None:
    rng = random.Random(3)
    for _ in range(300):
        a, b = random_box(rng), random_box(rng)
        pieces = subtract(a, b)
        masks = [packet_set(p) for p in pieces]
        union = 0
        for mk in masks:
            assert mk & union == 0  # the pieces are disjoint
            union |= mk
        assert union == packet_set(a) & ~packet_set(b)
    for _ in range(120):
        rules = random_policy(rng, rng.randint(1, 7))
        for y in range(1, len(rules) + 1):
            covered = 0
            for r in rules[: y - 1]:
                covered |= packet_set(r.box)
            assert is_dead(rules, y) == (packet_set(rules[y - 1].box) & ~covered == 0)


PAGE_POLICY = [
    rule("tcp", "198.51.100.0/25", "any", "203.0.113.10/32", "80", "allow"),
    rule("tcp", "198.51.100.0/24", "any", "203.0.113.10/32", "80", "deny"),
    rule("tcp", "198.51.100.200/32", "any", "203.0.113.10/32", "80", "allow"),
    rule("tcp", "198.51.100.128/26", "any", "203.0.113.0/24", "any", "allow"),
    rule("udp", "192.0.2.53/32", "53", "203.0.113.0/24", "any", "allow"),
    rule("udp", "192.0.2.0/24", "53", "203.0.113.0/24", "any", "allow"),
    rule("udp", "192.0.2.10/32", "53", "203.0.113.5/32", "53", "allow"),
]


def test_page_example() -> None:
    got = [(a.kind, a.x, a.y, a.removable) for a in anomalies(PAGE_POLICY)]
    assert got == [
        ("generalization", 1, 2, None),
        ("shadowing", 2, 3, None),
        ("correlation", 2, 4, None),
        ("redundancy-earlier", 5, 6, 5),
        ("redundancy-later", 6, 7, 7),
    ]
    assert is_dead(PAGE_POLICY, 3)
    assert not is_dead(PAGE_POLICY, 4)
    src, dst = prefix("198.51.100.150/32")[0], prefix("203.0.113.10/32")[0]
    assert decide(PAGE_POLICY, (6, src, 40000, dst, 80)) == "deny"  # R2 takes it from R4
    assert decide(PAGE_POLICY, (6, src, 40000, dst + 1, 80)) == "allow"  # R4
    assert prefix("2001:db8::/32") == (0x20010DB8 << 96, (0x20010DB8 << 96) + (1 << 96) - 1)


def test_bad_rules() -> None:
    with pytest.raises(ValueError):
        prefix("192.0.2.1/24")  # host bits set
    with pytest.raises(ValueError):
        relation(((0, 1),), ((0, 1), (0, 1)))

History

Al-Shaer and Hamed (IEEE Transactions on Network and Service Management, 2004) defined the relations between filtering rules and the shadowing, correlation, generalization and redundancy anomalies, and built a policy tree to find them. In the same year, their INFOCOM paper extended the classes to rules on different firewalls of a network path. Later work added decision diagrams that represent the whole policy, which also find rules that are covered by several earlier rules together.

References

  1. Ehab S. Al-Shaer and Hazem H. Hamed, Modeling and management of firewall policies, IEEE Transactions on Network and Service Management 1(1), 2004, pages 2 to 10, doi:10.1109/TNSM.2004.4623689, the relations between rules, the definitions of shadowing, correlation, generalization and redundancy, and the policy tree used to detect them
  2. Ehab S. Al-Shaer and Hazem H. Hamed, Discovery of policy anomalies in distributed firewalls, IEEE INFOCOM 2004, pages 2605 to 2616, doi:10.1109/INFCOM.2004.1354680, the intra-firewall anomaly classes and their extension to rules on different firewalls of a 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 proofH2 full proof
  • correctness: no review record reviews/MRZ666/proof-correctness.yaml
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
  • at least three sources
  • a scene preset for the example