From 7059e40c7a487b17886e1d345b52fc0cfca8df72 Mon Sep 17 00:00:00 2001
From: Sebastian Pipping <sebastian@pipping.org>
Date: Wed, 2 Jun 2021 13:15:29 +0200
Subject: [PATCH] frontend/cmd.cc: Fix buffer overflow CVE-2021-30184

Based on prior work by Michael Vaughan,
with "break;" replaced by "return;" and
magic number 9 resolved by strlen("setboard ").

Mimics close-to-identical existing code from
elsewhere in the the same file.
---
 src/frontend/cmd.cc | 30 ++++++++++++++++++++++--------
 1 file changed, 22 insertions(+), 8 deletions(-)

diff --git a/src/frontend/cmd.cc b/src/frontend/cmd.cc
index a321fc2..394d03f 100644
--- a/src/frontend/cmd.cc
+++ b/src/frontend/cmd.cc
@@ -477,13 +477,20 @@ void cmd_pgnload(void)
     return;
   }
 
-  strcpy( data, "setboard " );
+  const char setboardCmd[] = "setboard ";
+  unsigned int setboardLen = strlen(setboardCmd);
+  strcpy( data, setboardCmd );
   int i=0;
   while ( epdline[i] != '\n' ) {
-    data[i+9] = epdline[i];
-    ++i;
+    if (i + setboardLen < MAXSTR - 1) {
+      data[i+setboardLen] = epdline[i];
+      ++i;
+    } else {
+      printf( _("Error reading contents of file '%s'.\n"), token[1] );
+      return;
+    }
   }
-  data[i+9] = '\0';
+  data[i+setboardLen] = '\0';
   SetDataToEngine( data );
   SetAutoGo( true );
   pgnloaded = 0;
@@ -501,13 +508,20 @@ void cmd_pgnreplay(void)
     return;
   }
 
-  strcpy( data, "setboard " );
+  const char setboardCmd[] = "setboard ";
+  unsigned int setboardLen = strlen(setboardCmd);
+  strcpy( data, setboardCmd );
   int i=0;
   while ( epdline[i] != '\n' ) {
-    data[i+9] = epdline[i];
-    ++i;
+    if (i + setboardLen < MAXSTR - 1) {
+      data[i+setboardLen] = epdline[i];
+      ++i;
+    } else {
+      printf( _("Error reading contents of file '%s'.\n"), token[1] );
+      return;
+    }
   }
-  data[i+9] = '\0';
+  data[i+setboardLen] = '\0';
 
   SetDataToEngine( data );
   SetAutoGo( true );
-- 
2.31.1

