From 06b49e99d9a8d03be898feef7d332e07c31c7136 Mon Sep 17 00:00:00 2001
From: Marko Lindqvist <cazfi74@gmail.com>
Date: Tue, 25 Aug 2026 03:12:34 +0300
Subject: [PATCH 2/4] savegame: Fix Heap Buffer Overflow in worklist_load()

Reported by Tristan

See RM #2161

Signed-off-by: Marko Lindqvist <cazfi74@gmail.com>
---
 server/savegame/savegame2.c | 8 ++++++++
 server/savegame/savegame3.c | 8 ++++++++
 2 files changed, 16 insertions(+)

diff --git a/server/savegame/savegame2.c b/server/savegame/savegame2.c
index 64baf0532e..7cb2a47a0a 100644
--- a/server/savegame/savegame2.c
+++ b/server/savegame/savegame2.c
@@ -764,6 +764,14 @@ static void worklist_load(struct section_file *file, int wlist_max_length,
   worklist_init(pwl);
   pwl->length = secfile_lookup_int_default(file, 0,
                                            "%s.wl_length", path_str);
+  if (pwl->length > MAX_LEN_WORKLIST) {
+    log_sg("worklist length %d, while MAX_LEN_WORKLIST %d.",
+           pwl->length, MAX_LEN_WORKLIST);
+    pwl->length = MAX_LEN_WORKLIST;
+  } else if (pwl->length > wlist_max_length) {
+    log_sg("worklist length %d, while player's max worklist length %d.",
+           pwl->length, wlist_max_length);
+  }
 
   for (i = 0; i < pwl->length; i++) {
     kind = secfile_lookup_str(file, "%s.wl_kind%d", path_str, i);
diff --git a/server/savegame/savegame3.c b/server/savegame/savegame3.c
index c451ab6262..289c35d106 100644
--- a/server/savegame/savegame3.c
+++ b/server/savegame/savegame3.c
@@ -954,6 +954,14 @@ static void worklist_load(struct section_file *file, int wlist_max_length,
   worklist_init(pwl);
   pwl->length = secfile_lookup_int_default(file, 0,
                                            "%s.wl_length", path_str);
+  if (pwl->length > MAX_LEN_WORKLIST) {
+    log_sg("worklist length %d, while MAX_LEN_WORKLIST %d.",
+           pwl->length, MAX_LEN_WORKLIST);
+    pwl->length = MAX_LEN_WORKLIST;
+  } else if (pwl->length > wlist_max_length) {
+    log_sg("worklist length %d, while player's max worklist length %d.",
+           pwl->length, wlist_max_length);
+  }
 
   for (i = 0; i < pwl->length; i++) {
     kind = secfile_lookup_str(file, "%s.wl_kind%d", path_str, i);
-- 
2.53.0

