Skip to content

Commit 23d11a1

Browse files
LinkgoronBethGriggs
authored andcommitted
dgram: fix send with out of bounds offset + length
fix Socket.prototype.send sending garbage when the message is a string, or Buffer and offset+length is out of bounds. Fixes: #40491 PR-URL: #40568 Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent dab574e commit 23d11a1

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lib/dgram.js

+8
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ const {
4040
} = require('internal/dgram');
4141
const { guessHandleType } = internalBinding('util');
4242
const {
43+
ERR_BUFFER_OUT_OF_BOUNDS,
4344
ERR_INVALID_ARG_TYPE,
4445
ERR_MISSING_ARGS,
4546
ERR_SOCKET_ALREADY_BOUND,
@@ -487,6 +488,13 @@ function sliceBuffer(buffer, offset, length) {
487488

488489
offset = offset >>> 0;
489490
length = length >>> 0;
491+
if (offset > buffer.byteLength) {
492+
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
493+
}
494+
495+
if (offset + length > buffer.byteLength) {
496+
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
497+
}
490498

491499
return Buffer.from(buffer.buffer, buffer.byteOffset + offset, length);
492500
}

test/parallel/test-dgram-send-bad-arguments.js

+41
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,47 @@ function checkArgs(connected) {
7777
message: 'Already connected'
7878
}
7979
);
80+
81+
const longArray = [1, 2, 3, 4, 5, 6, 7, 8];
82+
for (const input of ['hello',
83+
Buffer.from('hello'),
84+
Buffer.from('hello world').subarray(0, 5),
85+
Buffer.from('hello world').subarray(4, 9),
86+
Buffer.from('hello world').subarray(6),
87+
new Uint8Array([1, 2, 3, 4, 5]),
88+
new Uint8Array(longArray).subarray(0, 5),
89+
new Uint8Array(longArray).subarray(2, 7),
90+
new Uint8Array(longArray).subarray(3),
91+
new DataView(new ArrayBuffer(5), 0),
92+
new DataView(new ArrayBuffer(6), 1),
93+
new DataView(new ArrayBuffer(7), 1, 5)]) {
94+
assert.throws(
95+
() => { sock.send(input, 6, 0); },
96+
{
97+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
98+
name: 'RangeError',
99+
message: '"offset" is outside of buffer bounds',
100+
}
101+
);
102+
103+
assert.throws(
104+
() => { sock.send(input, 0, 6); },
105+
{
106+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
107+
name: 'RangeError',
108+
message: '"length" is outside of buffer bounds',
109+
}
110+
);
111+
112+
assert.throws(
113+
() => { sock.send(input, 3, 4); },
114+
{
115+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
116+
name: 'RangeError',
117+
message: '"length" is outside of buffer bounds',
118+
}
119+
);
120+
}
80121
} else {
81122
assert.throws(() => { sock.send(buf, 1, 1, -1, host); }, RangeError);
82123
assert.throws(() => { sock.send(buf, 1, 1, 0, host); }, RangeError);

0 commit comments

Comments
 (0)