Skip to content

Reject a netmask that has its own prefix length - #146

Open
bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-mask-with-prefix-length
Open

bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-mask-with-prefix-length

Conversation

@bardrop

@bardrop bardrop commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What was wrong

A netmask string that has its own /prefix was accepted, and the extra prefix was applied to the mask:

IPAddr.new("192.168.0.1/255.255.255.0/8")
# before: #<IPAddr: IPv4:192.0.0.0/255.0.0.0>
# after:  IPAddr::InvalidAddressError (invalid mask 255.255.255.0/8)

IPAddr.new("3ffe:505::1/ffff:ffff::/16")
# before: #<IPAddr: IPv6:3ffe:0000:...:0000/ffff:0000:...:0000>
# after:  IPAddr::InvalidAddressError

IPAddr.new("192.168.2.0/24").mask("255.255.255.0/8")
# before: #<IPAddr: IPv4:192.0.0.0/255.0.0.0>
# after:  IPAddr::InvalidAddressError

mask! parses the mask string with IPAddr.new, so "255.255.255.0/8" becomes 255.0.0.0. The user asked for a /24 mask and silently got /8. Python's ipaddress rejects the same input.

IPAddr.new("192.168.0.1/32/20") already raises InvalidAddressError (there is a test for it), so this looks like an oversight only for the netmask form.

The fix

In mask!, raise InvalidAddressError when the mask string contains /. I used InvalidAddressError to match the error "192.168.0.1/32/20" already gives.

Tests

Added 4 assertions (2 in test_s_new, 2 in test_mask).

  • Before the fix: 43 tests, 632 assertions, 2 failures
  • After the fix: 43 tests, 639 assertions, 0 failures

IPAddr.new("192.168.0.1/255.255.255.0/8") was accepted and gave
192.0.0.0/8. The netmask string "255.255.255.0/8" was parsed with
IPAddr.new, which applied the "/8" to it, so the mask became
255.0.0.0. IPAddr#mask("255.255.255.0/8") had the same problem.

Raise InvalidAddressError for a mask string that contains "/",
the same error IPAddr.new("192.168.0.1/32/20") already raises.
@bardrop
bardrop requested a review from knu as a code owner November 26, 2026 10:38

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant