Skip to content
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

set_error can violate memory safety #1056

Closed
LunarLambda opened this issue Dec 22, 2020 · 1 comment · Fixed by #1057
Closed

set_error can violate memory safety #1056

LunarLambda opened this issue Dec 22, 2020 · 1 comment · Fixed by #1057
Labels

Comments

@LunarLambda
Copy link
Contributor

LunarLambda commented Dec 22, 2020

The set_error function turns the given str to a CString and passes it directly to SDL_SetError.

Note that SDL_SetError is a variadic function, and accepts a printf-like format string.

The problem with this is that the number of arguments is derived from the format string, and in most ABIs, variadic functions take their parameters on the stack

In effect, this means that code such as this:

SDL_SetError("%p%p%p%p%p%p%p%p");

or the rust equivalent

sdl2::set_error("%p%p%p%p%p%p%p%p");

will likely cause a crash due to corrupting the stack.

EDIT: This particular example does not crash on my machine, although it does allow to read memory from the stack, including the function's return address.

However, using a different specifier like %s will almost definitely cause a segmentation fault.
Furthermore, SDL_vsnprintf, which handles formatting for SDL_SetError, will delegate to the native C library's vsnprintf function when possible, meaning the %n specifier can be used to write to arbitrary (and likely invalid) memory, which definitely should not be possible from within safe rust.

Potential Fixes

  1. Remove set_error, as it is difficult to use correctly
  2. Make set_error unsafe, and document why
  3. Make set_error check for format specifiers, and fail if any are found
  4. Change set_error such that it passes "%s" as the format string, and the passed str as the only other argument

Documentation for SDL_SetError
Source code for SDL_vsnprintf
Article about format string attacks

@Cobrand
Copy link
Member

Cobrand commented Dec 22, 2020

  1. is the wisest, in C with printf you always use %s instead of custom strings as the first argument because of this reason (in the rare cases that you do). Users that will want a variadic function can always use sdl2_sys::SDL_SetError

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

Successfully merging a pull request may close this issue.

2 participants