From 1ced463496ddf3ff0c33d595ee102e975f69554d Mon Sep 17 00:00:00 2001
From: Frantisek Sumsal <frantisek@sumsal.cz>
Date: Thu, 4 May 2023 16:45:36 +0200
Subject: [PATCH] shared: refuse fd == INT_MAX

Since we do `FD_TO_PTR(fd)` that expands to `INT_TO_PTR(fd) + 1` which
triggers an integer overflow.

Resolves: #27522
(cherry picked from commit cc938f1ce0f1eafc435e0dd1d9fe45aaedc526e1)
(cherry picked from commit 154b108513fe4aa50e7f347abeb0f0d9789a32df)
(cherry picked from commit dd38a90202a78d54d163049d2f0a96f8153470b3)

Conflict:NA
Reference:https://github.com/systemd/systemd-stable/commit/1ced463496ddf3ff0c33d595ee102e975f69554d
---
 src/shared/fdset.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/src/shared/fdset.c b/src/shared/fdset.c
index 183fa239b6..c621c14ba6 100644
--- a/src/shared/fdset.c
+++ b/src/shared/fdset.c
@@ -74,6 +74,10 @@ int fdset_put(FDSet *s, int fd) {
         assert(s);
         assert(fd >= 0);
 
+        /* Avoid integer overflow in FD_TO_PTR() */
+        if (fd == INT_MAX)
+                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Refusing invalid fd: %d", fd);
+
         return set_put(MAKE_SET(s), FD_TO_PTR(fd));
 }
 
@@ -100,6 +104,12 @@ bool fdset_contains(FDSet *s, int fd) {
         assert(s);
         assert(fd >= 0);
 
+        /* Avoid integer overflow in FD_TO_PTR() */
+        if (fd == INT_MAX) {
+                log_debug("Refusing invalid fd: %d", fd);
+                return false;
+        }
+
         return !!set_get(MAKE_SET(s), FD_TO_PTR(fd));
 }
 
@@ -107,6 +117,10 @@ int fdset_remove(FDSet *s, int fd) {
         assert(s);
         assert(fd >= 0);
 
+        /* Avoid integer overflow in FD_TO_PTR() */
+        if (fd == INT_MAX)
+                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "Refusing invalid fd: %d", fd);
+
         return set_remove(MAKE_SET(s), FD_TO_PTR(fd)) ? fd : -ENOENT;
 }
 
-- 
2.33.0

