Skip to content

Fix potentially overflowing call to snprintf #2673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

odaysec
Copy link

@odaysec odaysec commented Jun 10, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant