Firewall Rule Resolver with Longest-Prefix Priority
Math & Bit ManipulationAuto-graded · 21 test casesLast updated
Resolve an IPv4 address against CIDR allow/deny rules using longest-prefix precedence, later-rule tie-breaking, and a default of deny, via bitmask matching.
Firewall Rule Resolver
A firewall holds an ordered list of rules. Each rule is a pair [action, cidr]:
actionis either"allow"or"deny".cidris an IPv4 block written asa.b.c.d/p, wherepis the prefix length (0 to 32).
You are also given a single IPv4 address, target_ip, written in dotted-decimal form such as 192.168.1.25.
Decide whether traffic from target_ip is permitted, and return either "allow" or "deny".
How a decision is made
- A rule applies to the address if the address lies inside the rule's CIDR block, meaning the first
pbits of the address equal the firstpbits of the block's base address. Only thosepleading bits of the base address matter; any remaining bits of the base address are ignored (so10.1.2.3/8covers the same addresses as10.0.0.0/8). A/0block covers every address. - Among all applying rules, the one with the largest prefix length decides the outcome.
- If several applying rules share that largest prefix length, the one that appears latest in the list decides.
- If no rule applies, the answer is
"deny".
Function
Implement a function that receives the list of rules and the target address and returns the string "allow" or "deny".
Constraints
- Every address and CIDR block is valid; each octet is in
[0, 255]and each prefix length is in[0, 32]. - The rule list may be empty.
- Actions are exactly
"allow"or"deny"(lowercase). - The return value must be exactly
"allow"or"deny".
Examples
Example 1
Input: resolve_firewall_rules([['allow', '192.168.0.0/16'], ['deny', '192.168.1.0/24']], '192.168.1.25')
Output: 'deny'
Example 2
Input: resolve_firewall_rules([['deny', '10.0.0.0/8'], ['allow', '10.1.0.0/16'], ['deny', '10.1.2.0/24']], '10.1.2.55')
Output: 'deny'
Example 3
Input: resolve_firewall_rules([['allow', '172.16.0.0/12'], ['deny', '172.16.5.0/24'], ['allow', '172.16.5.128/25']], '172.16.5.200')
Output: 'allow'
Hints
Hint 1
Convert each dotted address into a single 32-bit integer by shifting the running value left 8 bits and OR-ing in the next octet.
Hint 2
For prefix length p, a mask with p leading ones is (0xffffffff << (32 - p)) & 0xffffffff, with p = 0 handled separately as mask 0. An address is in the block when (address & mask) == (base & mask).
Hint 3
You do not need to sort. Scan the rules once while remembering the best prefix length seen so far (start at -1) and its action; replace them whenever an applying rule has prefix >= the best, so later rules win ties.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each IPv4 address as a 32-bit unsigned integer. Build it by folding the octets from left to right: shift the running value left by 8 bits and OR in the next octet.
A CIDR block base/p contains an address exactly when the top p bits of the address equal the top p bits of base. To test this:
- Build a mask with
pleading ones followed by32 - pzeros:(0xffffffff << (32 - p)) & 0xffffffff. The& 0xffffffffremoves bits above bit 31, which Python's unbounded integers would otherwise keep. Forp = 0the mask is simply0, so every address matches (and we avoid a shift by 32, which is a problem in fixed-width languages). - Compare
(target & mask) == (base & mask). Masking the base too means non-canonical blocks like10.1.2.3/8behave like10.0.0.0/8.
Then make one pass over the rules, tracking best_prefix (initially -1) and decision (initially "deny"). When a rule applies and its prefix is >= best_prefix, record its prefix and action.
Why it is correct
The invariant after each rule is: decision is the action of the applying rule with the largest prefix so far, and among those with equal largest prefix, the latest one.
- An applying rule with a larger prefix must take over, and
>=allows it. - An applying rule with an equal prefix comes later in the list, so it must take over, and
>=allows it. - An applying rule with a smaller prefix must not take over, and
>=rejects it.
If nothing applies, the initial "deny" is returned. Since -1 is smaller than every real prefix, even a /0 rule overrides the default.
Complexity
- Time: O(R) for R rules, constant work per rule.
- Space: O(1) beyond the input.
For many queries against a large rule set, a binary trie keyed on address bits would give O(32) per query, with later inserts at the same node overwriting earlier ones.
Reference solution
from typing import List
def _ip_to_int(ip: str) -> int:
value = 0
for part in ip.split('.'):
value = (value << 8) | int(part)
return value
def resolve_firewall_rules(rules: List[List[str]], target_ip: str) -> str:
target = _ip_to_int(target_ip)
best_prefix = -1
decision = 'deny'
for action, cidr in rules:
address, prefix_text = cidr.split('/')
prefix = int(prefix_text)
base = _ip_to_int(address)
mask = ((0xffffffff << (32 - prefix)) & 0xffffffff) if prefix else 0
if (target & mask) == (base & mask) and prefix >= best_prefix:
best_prefix = prefix
decision = action
return decision