Skip to content

Commit d0edabe

Browse files
committed
net: strict checking for internal/net isLegalPort
Add stricter testing for the isLegalPort method in internal/net. This ensures that odd inputs such as isLegalPort(true) and isLegalPort([1]) aren't acceptable as valid port inputs. PR-URL: nodejs#5733 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
1 parent 287bdab commit d0edabe

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

lib/internal/net.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ module.exports = { isLegalPort };
55
// Check that the port number is not NaN when coerced to a number,
66
// is an integer and that it falls within the legal range of port numbers.
77
function isLegalPort(port) {
8-
if (typeof port === 'string' && port.trim() === '')
8+
if ((typeof port !== 'number' && typeof port !== 'string') ||
9+
(typeof port === 'string' && port.trim().length === 0))
910
return false;
10-
return +port === (port >>> 0) && port >= 0 && port <= 0xFFFF;
11+
return +port === (+port >>> 0) && port <= 0xFFFF;
1112
}

test/parallel/test-net-internal.js

+14-9
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@
44

55
require('../common');
66
const assert = require('assert');
7-
const net = require('internal/net');
8-
9-
assert.strictEqual(net.isLegalPort(''), false);
10-
assert.strictEqual(net.isLegalPort('0'), true);
11-
assert.strictEqual(net.isLegalPort(0), true);
12-
assert.strictEqual(net.isLegalPort(65536), false);
13-
assert.strictEqual(net.isLegalPort('65535'), true);
14-
assert.strictEqual(net.isLegalPort(undefined), false);
15-
assert.strictEqual(net.isLegalPort(null), true);
7+
const isLegalPort = require('internal/net').isLegalPort;
8+
9+
for (var n = 0; n <= 0xFFFF; n++) {
10+
assert(isLegalPort(n));
11+
assert(isLegalPort('' + n));
12+
assert(`0x${n.toString(16)}`);
13+
assert(`0o${n.toString(8)}`);
14+
assert(`0b${n.toString(2)}`);
15+
}
16+
17+
const bad = [-1, 'a', {}, [], false, true, 0xFFFF + 1, Infinity,
18+
-Infinity, NaN, undefined, null, '', ' ', 1.1, '0x',
19+
'-0x1', '-0o1', '-0b1', '0o', '0b'];
20+
bad.forEach((i) => assert(!isLegalPort(i)));

0 commit comments

Comments
 (0)