From 2163a6616992e8348bafc69d42e9eed55e0848f0 Mon Sep 17 00:00:00 2001 From: Asdow <20314541+Asdow@users.noreply.github.com> Date: Tue, 25 Jul 2023 14:19:30 +0300 Subject: [PATCH] Prevent writing past array capacity (#185) Game would crash with stack-based buffer overrun when a MOLLE item had enough attachments and their texts were written past attachString capacity --- Tactical/Interface Items.cpp | 37 +++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/Tactical/Interface Items.cpp b/Tactical/Interface Items.cpp index 69a9b0a9..d71aa3ca 100644 --- a/Tactical/Interface Items.cpp +++ b/Tactical/Interface Items.cpp @@ -12648,28 +12648,39 @@ void GetHelpTextForItem( STR16 pzStr, OBJECTTYPE *pObject, SOLDIERTYPE *pSoldier // Add attachment string.... CHAR16 attachString[ 300 ]; + CHAR16 tempString[ 120 ]; memset(attachString,0,sizeof(attachString)); - for (attachmentList::iterator iter = (*pObject)[subObject]->attachments.begin(); iter != (*pObject)[subObject]->attachments.end(); ++iter) { - if(iter->exists()){ - - //Break off if it's too long. - if(wcslen(attachString)>270){ - wcscat( attachString, L"\n...." ); - break; - } + for (attachmentList::iterator iter = (*pObject)[subObject]->attachments.begin(); iter != (*pObject)[subObject]->attachments.end(); ++iter) + { + if(iter->exists()) + { + memset(tempString, 0, sizeof(tempString)); iNumAttachments++; - - if ( iNumAttachments == 1 ) + if (iNumAttachments == 1) { - swprintf( attachString, L"\n \n%s:\n", Message[ STR_ATTACHMENTS ] ); + swprintf(tempString, L"\n \n%s:\n", Message[STR_ATTACHMENTS]); } else { - wcscat( attachString, L"\n" ); + swprintf(tempString, L"\n"); } + wcscat(tempString, ItemNames[iter->usItem]); - wcscat( attachString, ItemNames[ iter->usItem ] ); + auto attachStringLength = wcslen(attachString); + auto tempStringLength = wcslen(tempString); + auto totalLength = attachStringLength + tempStringLength; + // Break off if the string to be added does not fit. + // attachStringLength[300] - L"\n...." -> 294 + if (totalLength > 294) + { + wcscat(attachString, L"\n...."); + break; + } + else + { + wcscat(attachString, tempString); + } } }