Skip to content

Commit 6b2f4fc

Browse files
committed
dgram: fix send with out of bounds offset + length
fix Socket.prototype.send sending garbage when the message is a string, and offset+length is out of bounds. Fixes: #40491
1 parent 89c0577 commit 6b2f4fc

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lib/dgram.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const { guessHandleType } = internalBinding('util');
4242
const {
4343
ERR_INVALID_ARG_TYPE,
4444
ERR_MISSING_ARGS,
45+
ERR_OUT_OF_RANGE,
4546
ERR_SOCKET_ALREADY_BOUND,
4647
ERR_SOCKET_BAD_BUFFER_SIZE,
4748
ERR_SOCKET_BUFFER_SIZE,
@@ -476,6 +477,18 @@ Socket.prototype.sendto = function(buffer,
476477
function sliceBuffer(buffer, offset, length) {
477478
if (typeof buffer === 'string') {
478479
buffer = Buffer.from(buffer);
480+
offset = offset >>> 0;
481+
length = length >>> 0;
482+
483+
if (offset > buffer.byteLength) {
484+
throw new ERR_OUT_OF_RANGE('offset', `<= ${buffer.byteLength}`, offset);
485+
}
486+
487+
if (offset + length > buffer.byteLength) {
488+
throw new ERR_OUT_OF_RANGE('length',
489+
`<= ${buffer.byteLength - offset}`, length);
490+
}
491+
479492
} else if (!isArrayBufferView(buffer)) {
480493
throw new ERR_INVALID_ARG_TYPE('buffer',
481494
['Buffer',

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,36 @@ function checkArgs(connected) {
7777
message: 'Already connected'
7878
}
7979
);
80+
81+
assert.throws(
82+
() => { sock.send('hello', 6, 0); },
83+
{
84+
code: 'ERR_OUT_OF_RANGE',
85+
name: 'RangeError',
86+
message: 'The value of "offset" is out of range. ' +
87+
'It must be <= 5. Received 6'
88+
}
89+
);
90+
91+
assert.throws(
92+
() => { sock.send('hello', 0, 6); },
93+
{
94+
code: 'ERR_OUT_OF_RANGE',
95+
name: 'RangeError',
96+
message: 'The value of "length" is out of range. ' +
97+
'It must be <= 5. Received 6'
98+
}
99+
);
100+
101+
assert.throws(
102+
() => { sock.send('hello', 3, 4); },
103+
{
104+
code: 'ERR_OUT_OF_RANGE',
105+
name: 'RangeError',
106+
message: 'The value of "length" is out of range. ' +
107+
'It must be <= 2. Received 4'
108+
}
109+
);
80110
} else {
81111
assert.throws(() => { sock.send(buf, 1, 1, -1, host); }, RangeError);
82112
assert.throws(() => { sock.send(buf, 1, 1, 0, host); }, RangeError);

0 commit comments

Comments
 (0)