Buffer overflow in SOPC_String_GetCString when cast from SOPC_ByteString
Description
ASan notified that the function SOPC_String_GetCString
might overflow.
This is due to:
memcpy(cString, string->Data, (size_t) string->Length + 1);
Analysis
It appears that, even though SOPC_ByteString
is a synonymous of SOPC_String
, their fields have different semantics.
As commented in sources of the functions that use it, SOPC_String.Length
does not include the terminating \0
, which means that string.Length == strlen(string.Data)
, but the size of the allocated memory is string.Length+1
.
However, for ByteString
, the field Length
is the size of the allocated memory.
Hence, when using SOPC_String_GetCString
on a SOPC_ByteString
, there is a buffer overflow.
The primary invalid usage of this cast is found in LibSub's Helpers_NewValueFromDataValue
which prepares the value for StaMac_ProcessEvent_stActivated
which calls the applicative callback for data change notification.
However, code must be checked for other invalid usages:
- other calls to
SOPC_String_GetCString
were verified, no invalid cast -
SOPC_ByteString_Clear
,SOPC_ByteString_Delete
, andSOPC_ByteString_Initialize
cast the bytestring to a string and call the correspondingSOPC_String_
function; however, asLength
is not used by these function, this is valid - usages of the Length fields were verified
Fixes
Remove the cast, make a block copy, and add a length
field to the SOPC_LibSub_Value
for the bytestring case + open a ticket to discuss the field semantics.