Skip to content

Commit 243b0e4

Browse files
watilderichardlau
authored andcommitted
lib: reject string "0" in validatePort when allowZero is false
The allowZero guard compared the raw value with `port === 0`, but validatePort accepts strings and coerces them with `+port` in every other clause. Since `'0' === 0` is false, string forms of zero ('0', ' 0 ', '00', '0x0', ...) slipped past the guard when allowZero was false, while the numeric 0 was correctly rejected. This is reachable via dgram's send(), connect(), and bind(), which call validatePort(port, 'Port', false): passing '0' was silently accepted instead of throwing ERR_SOCKET_BAD_PORT. Coerce the value with `+port` so the zero check matches the rest of the validation. Signed-off-by: Daijiro Wachi <daijiro.wachi@gmail.com> PR-URL: #64174 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Richard Lau <richard.lau@ibm.com>
1 parent a483bfd commit 243b0e4

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

‎lib/internal/validators.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ const validatePort = hideStackFrames((port, name = 'Port', allowZero = true) =>
438438
(typeofport==='string'&&StringPrototypeTrim(port).length===0)||
439439
+port!==(+port>>>0)||
440440
port>0xFFFF||
441-
(port===0&&!allowZero)){
441+
(+port===0&&!allowZero)){
442442
thrownewERR_SOCKET_BAD_PORT(name,port,allowZero);
443443
}
444444
returnport|0;

‎test/parallel/test-internal-validators-validateport.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,17 @@ for (let n = 0; n <= 0xFFFF; n++) {
2121
].forEach((i)=>assert.throws(()=>validatePort(i),{
2222
code: 'ERR_SOCKET_BAD_PORT'
2323
}));
24+
25+
// When allowZero is false, every form of zero must be rejected, including
26+
// the string forms that coerce to 0. Refs: the zero check must coerce the
27+
// value the same way the rest of the validation does (`+port`).
28+
[
29+
0,'0',' 0 ','00','0x0','0o0','0b0',
30+
].forEach((i)=>assert.throws(()=>validatePort(i,'Port',false),{
31+
code: 'ERR_SOCKET_BAD_PORT'
32+
}));
33+
34+
// With allowZero left at its default (true), those same values are accepted.
35+
[
36+
0,'0',' 0 ','00','0x0','0o0','0b0',
37+
].forEach((i)=>assert.strictEqual(validatePort(i),0));

0 commit comments

Comments
 (0)