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,
or Buffer and offset+length is out of bounds.

Fixes: #40491

PR-URL: #40568
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
  • Loading branch information
Linkgoron authored and targos committed Nov 6, 2021
1 parent 825a683 commit 79bf429
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/dgram.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const {
} = require('internal/dgram');
const { guessHandleType } = internalBinding('util');
const {
ERR_BUFFER_OUT_OF_BOUNDS,
ERR_INVALID_ARG_TYPE,
ERR_MISSING_ARGS,
ERR_SOCKET_ALREADY_BOUND,
Expand Down Expand Up @@ -487,6 +488,13 @@ function sliceBuffer(buffer, offset, length) {

offset = offset >>> 0;
length = length >>> 0;
if (offset > buffer.byteLength) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
}

if (offset + length > buffer.byteLength) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
}

return Buffer.from(buffer.buffer, buffer.byteOffset + offset, length);
}
Expand Down
41 changes: 41 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,47 @@ function checkArgs(connected) {
message: 'Already connected'
}
);

const longArray = [1, 2, 3, 4, 5, 6, 7, 8];
for (const input of ['hello',
Buffer.from('hello'),
Buffer.from('hello world').subarray(0, 5),
Buffer.from('hello world').subarray(4, 9),
Buffer.from('hello world').subarray(6),
new Uint8Array([1, 2, 3, 4, 5]),
new Uint8Array(longArray).subarray(0, 5),
new Uint8Array(longArray).subarray(2, 7),
new Uint8Array(longArray).subarray(3),
new DataView(new ArrayBuffer(5), 0),
new DataView(new ArrayBuffer(6), 1),
new DataView(new ArrayBuffer(7), 1, 5)]) {
assert.throws(
() => { sock.send(input, 6, 0); },
{
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"offset" is outside of buffer bounds',
}
);

assert.throws(
() => { sock.send(input, 0, 6); },
{
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"length" is outside of buffer bounds',
}
);

assert.throws(
() => { sock.send(input, 3, 4); },
{
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"length" is outside of buffer bounds',
}
);
}
} 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 79bf429

Please sign in to comment.