From b82a1a1ac95d4e794657e99146f6777344c59dac Mon Sep 17 00:00:00 2001 From: cjihrig Date: Sat, 19 Jun 2021 18:12:54 -0400 Subject: [PATCH] src: compare IPv4 addresses in host byte order This commit updates compare_ipv4() to use the host byte order. PR-URL: https://github.com/nodejs/node/pull/39096 Fixes: https://github.com/nodejs/node/issues/39074 Reviewed-By: Khaidi Chu Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca --- src/node_sockaddr.cc | 6 ++++-- test/parallel/test-blocklist.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/node_sockaddr.cc b/src/node_sockaddr.cc index b15b6ab47194c1..09a74f302923f7 100644 --- a/src/node_sockaddr.cc +++ b/src/node_sockaddr.cc @@ -159,10 +159,12 @@ SocketAddress::CompareResult compare_ipv4( reinterpret_cast(one.data()); const sockaddr_in* two_in = reinterpret_cast(two.data()); + const uint32_t s_addr_one = ntohl(one_in->sin_addr.s_addr); + const uint32_t s_addr_two = ntohl(two_in->sin_addr.s_addr); - if (one_in->sin_addr.s_addr < two_in->sin_addr.s_addr) + if (s_addr_one < s_addr_two) return SocketAddress::CompareResult::LESS_THAN; - else if (one_in->sin_addr.s_addr == two_in->sin_addr.s_addr) + else if (s_addr_one == s_addr_two) return SocketAddress::CompareResult::SAME; else return SocketAddress::CompareResult::GREATER_THAN; diff --git a/test/parallel/test-blocklist.js b/test/parallel/test-blocklist.js index c72d9e30b5f2da..51f19e07bc649c 100644 --- a/test/parallel/test-blocklist.js +++ b/test/parallel/test-blocklist.js @@ -209,6 +209,27 @@ const util = require('util'); assert(!blockList.check('8592:757c:efaf:2fff:ffff:ffff:ffff:ffff', 'ipv6')); } +{ + // Regression test for https://github.com/nodejs/node/issues/39074 + const blockList = new BlockList(); + + blockList.addRange('10.0.0.2', '10.0.0.10'); + + // IPv4 checks against IPv4 range. + assert(blockList.check('10.0.0.2')); + assert(blockList.check('10.0.0.10')); + assert(!blockList.check('192.168.0.3')); + assert(!blockList.check('2.2.2.2')); + assert(!blockList.check('255.255.255.255')); + + // IPv6 checks against IPv4 range. + assert(blockList.check('::ffff:0a00:0002', 'ipv6')); + assert(blockList.check('::ffff:0a00:000a', 'ipv6')); + assert(!blockList.check('::ffff:c0a8:0003', 'ipv6')); + assert(!blockList.check('::ffff:0202:0202', 'ipv6')); + assert(!blockList.check('::ffff:ffff:ffff', 'ipv6')); +} + { const blockList = new BlockList(); assert.throws(() => blockList.addRange('1.1.1.2', '1.1.1.1'), /ERR_INVALID_ARG_VALUE/);