whitequark / ipaddr.js

IP address manipulation library in JavaScript
MIT License
570 stars 92 forks source link

CIDR parsing fails to apply mask. #144

Open haight6716 opened 3 years ago

haight6716 commented 3 years ago

While writing tests for that other issue I ran into this one - shouldn't this pass?

assert.equal(ipaddr.IPv4.parseCIDR('8.3.4.8/24').toString(), '8.3.4.0/24');

Admittedly it's invalid input, but shouldn't we silently fix it or throw? Instead, we produce invalid output.

kennethtran93 commented 3 years ago

This is because it parses the IP and CIDR separately. CIDR is used for checking through another function.

The octets stored is the one used from parsing the IP address irregardless of the existence of CIDR, thus toString will only return the parsed IP address, and if CIDR was given, then appends it afterwards.

You'll need to use the match function to test for CIDR (which only exists when using the parse function, not parseCIDR.

so

ipaddr.IPv4.parse('8.3.4.8').match(ipaddr.IPv4.parseCIDR('8.3.4.0/24'))

or

ipaddr.IPv4.parse('8.3.4.8').match(ipaddr.parse('8.3.4.0'), 24)

or

ipaddr.IPv4.parse('8.3.4.0').match(ipaddr.parse('8.3.4.8'), 24)

or

const test = ipaddr.IPv4.parseCIDR('8.3.4.8/24');
ipaddr.IPv4.parse('8.3.4.0').match(test[0], test[1]);

The parser doesn't know about any CIDR notations. It is only passed in the IP address string (without CIDR) for parsing. This is the same if you use parseCIDR, as it send everything before the slash to the parser for IP Address.