Skip to content

Commit

Permalink
dgram: fix send with out of bounds offset + length
Browse files Browse the repository at this point in the history
fix Socket.prototype.send sending garbage when the message is a string,
and offset+length is out of bounds.

Fixes: #40491
  • Loading branch information
Linkgoron committed Oct 22, 2021
1 parent 89c0577 commit 6b2f4fc
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/dgram.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const { guessHandleType } = internalBinding('util');
const {
ERR_INVALID_ARG_TYPE,
ERR_MISSING_ARGS,
ERR_OUT_OF_RANGE,
ERR_SOCKET_ALREADY_BOUND,
ERR_SOCKET_BAD_BUFFER_SIZE,
ERR_SOCKET_BUFFER_SIZE,
Expand Down Expand Up @@ -476,6 +477,18 @@ Socket.prototype.sendto = function(buffer,
function sliceBuffer(buffer, offset, length) {
if (typeof buffer === 'string') {
buffer = Buffer.from(buffer);
offset = offset >>> 0;
length = length >>> 0;

if (offset > buffer.byteLength) {
throw new ERR_OUT_OF_RANGE('offset', `<= ${buffer.byteLength}`, offset);
}

if (offset + length > buffer.byteLength) {
throw new ERR_OUT_OF_RANGE('length',
`<= ${buffer.byteLength - offset}`, length);
}

} else if (!isArrayBufferView(buffer)) {
throw new ERR_INVALID_ARG_TYPE('buffer',
['Buffer',
Expand Down
30 changes: 30 additions & 0 deletions test/parallel/test-dgram-send-bad-arguments.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,36 @@ function checkArgs(connected) {
message: 'Already connected'
}
);

assert.throws(
() => { sock.send('hello', 6, 0); },
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: 'The value of "offset" is out of range. ' +
'It must be <= 5. Received 6'
}
);

assert.throws(
() => { sock.send('hello', 0, 6); },
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: 'The value of "length" is out of range. ' +
'It must be <= 5. Received 6'
}
);

assert.throws(
() => { sock.send('hello', 3, 4); },
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: 'The value of "length" is out of range. ' +
'It must be <= 2. Received 4'
}
);
} else {
assert.throws(() => { sock.send(buf, 1, 1, -1, host); }, RangeError);
assert.throws(() => { sock.send(buf, 1, 1, 0, host); }, RangeError);
Expand Down

0 comments on commit 6b2f4fc

Please sign in to comment.