mujoco icon indicating copy to clipboard operation
mujoco copied to clipboard

Fix potentially overflowing call to snprintf

Open odaysec opened this issue 6 months ago • 0 comments

https://github.com/octodevark/mujoco/blob/caaf7b3a69d674c98572c0244dce1081abe49ca1/src/engine/engine_util_solve.c#L1391-L1411

Fix the issue return value of snprintf should be checked to ensure it does not exceed the remaining buffer size (logsz-logptr). If the return value is negative or greater than or equal to the remaining buffer size, the operation should be terminated to prevent buffer overflow. This involves adding a conditional check after the snprintf call and updating logptr only if the return value is valid.

The return value of a call to snprintf is the number of characters that would have been written to the buffer assuming there was sufficient space. In the event that the operation reaches the end of the buffer and more than one character is discarded, the return value will be greater than the buffer size. This can cause incorrect behavior

#define BUF_SIZE (32)

int main(int argc, char *argv[])
{
	char buffer[BUF_SIZE];
	size_t pos = 0;
	int i;

	for (i = 0; i < argc; i++)
	{
		pos += snprintf(buffer + pos, BUF_SIZE - pos, "%s", argv[i]);
			// BUF_SIZE - pos may overflow
	}
}

References

cplusplus snprintf Red Hat The trouble with snprintf

odaysec avatar Jun 10 '25 07:06 odaysec