From 122bb51721ad4faa0caf05b861de97f8a4b7d11e Mon Sep 17 00:00:00 2001 From: Siim Tiilen Date: Wed, 31 Oct 2018 21:35:51 +0200 Subject: [PATCH 1/2] add input validation for toLong it is possible to have ip value of null, for example from express. --- lib/ip.js | 3 +++ test/api-test.js | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/lib/ip.js b/lib/ip.js index c1799a8..fc281a0 100644 --- a/lib/ip.js +++ b/lib/ip.js @@ -401,6 +401,9 @@ ip.address = function(name, family) { ip.toLong = function(ip) { var ipl = 0; + if (!this.isV4Format(ip)) { + return ipl; + } ip.split('.').forEach(function(octet) { ipl <<= 8; ipl += parseInt(octet); diff --git a/test/api-test.js b/test/api-test.js index 2e390f9..063ffe2 100644 --- a/test/api-test.js +++ b/test/api-test.js @@ -396,6 +396,11 @@ describe('IP library for node.js', function() { assert.equal(ip.toLong('127.0.0.1'), 2130706433); assert.equal(ip.toLong('255.255.255.255'), 4294967295); }); + it('should be able handle bad input', function() { + assert.equal(ip.toLong('fd12:3456:789a:1::1'), 0); + assert.equal(ip.toLong(null), 0); + assert.equal(ip.toLong(undefined), 0); + }); }); describe('fromLong() method', function() { From 0adbf219e87e13ab63c30883b775bd456b13b528 Mon Sep 17 00:00:00 2001 From: Siim Tiilen Date: Thu, 1 Nov 2018 09:58:33 +0200 Subject: [PATCH 2/2] throw error if toLong parameter is invalid --- lib/ip.js | 4 ++-- test/api-test.js | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/ip.js b/lib/ip.js index fc281a0..ab010bd 100644 --- a/lib/ip.js +++ b/lib/ip.js @@ -400,10 +400,10 @@ ip.address = function(name, family) { }; ip.toLong = function(ip) { - var ipl = 0; if (!this.isV4Format(ip)) { - return ipl; + throw new Error('.toLong requires valid IPv4 as input: ' + ip); } + var ipl = 0; ip.split('.').forEach(function(octet) { ipl <<= 8; ipl += parseInt(octet); diff --git a/test/api-test.js b/test/api-test.js index 063ffe2..b39fcfa 100644 --- a/test/api-test.js +++ b/test/api-test.js @@ -386,7 +386,7 @@ describe('IP library for node.js', function() { var addr = ip.address(nic, 'ipv6'); assert.ok(!addr || net.isIPv6(addr)); }); - }) + }); }); }); }); @@ -397,9 +397,15 @@ describe('IP library for node.js', function() { assert.equal(ip.toLong('255.255.255.255'), 4294967295); }); it('should be able handle bad input', function() { - assert.equal(ip.toLong('fd12:3456:789a:1::1'), 0); - assert.equal(ip.toLong(null), 0); - assert.equal(ip.toLong(undefined), 0); + assert.throws(function () { + ip.toLong('fd12:3456:789a:1::1'); + }, Error); + assert.throws(function () { + ip.toLong(null); + }, Error); + assert.throws(function () { + ip.toLong(undefined); + }, Error); }); });