From 7b133d62206f782e1cb5a5050c2e0b522f05ca58 Mon Sep 17 00:00:00 2001
From: theanarkh <theratliter@gmail.com>
Date: Mon, 2 Dec 2024 12:48:53 +0800
Subject: [PATCH] dgram: check udp buffer size to avoid fd leak

PR-URL: https://github.com/nodejs/node/pull/56084
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
---
 lib/dgram.js                                  |  7 +++++++
 test/parallel/test-dgram-createSocket-type.js | 13 +++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/lib/dgram.js b/lib/dgram.js
index 74dd83889990ca..09630b6c901181 100644
--- a/lib/dgram.js
+++ b/lib/dgram.js
@@ -61,6 +61,7 @@ const {
   validateString,
   validateNumber,
   validatePort,
+  validateUint32,
 } = require('internal/validators');
 const { Buffer } = require('buffer');
 const { deprecate, guessHandleType, promisify } = require('internal/util');
@@ -110,6 +111,12 @@ function Socket(type, listener) {
     options = type;
     type = options.type;
     lookup = options.lookup;
+    if (options.recvBufferSize) {
+      validateUint32(options.recvBufferSize, 'options.recvBufferSize');
+    }
+    if (options.sendBufferSize) {
+      validateUint32(options.sendBufferSize, 'options.sendBufferSize');
+    }
     recvBufferSize = options.recvBufferSize;
     sendBufferSize = options.sendBufferSize;
   }
diff --git a/test/parallel/test-dgram-createSocket-type.js b/test/parallel/test-dgram-createSocket-type.js
index 19bbd6c1b2b088..ba033839cd1306 100644
--- a/test/parallel/test-dgram-createSocket-type.js
+++ b/test/parallel/test-dgram-createSocket-type.js
@@ -59,3 +59,16 @@ validTypes.forEach((validType) => {
     socket.close();
   }));
 }
+
+{
+  [
+    { type: 'udp4', recvBufferSize: 'invalid' },
+    { type: 'udp4', sendBufferSize: 'invalid' },
+  ].forEach((options) => {
+    assert.throws(() => {
+      dgram.createSocket(options);
+    }, {
+      code: 'ERR_INVALID_ARG_TYPE',
+    });
+  });
+}