Skip to content

RCUTILS_SAFE_FWRITE_TO_STDERR with variable length messages #78

Closed

Description

@dhood

If you pass a message of type const char * to RCUTILS_SAFE_FWRITE_TO_STDERR e.g.

RCUTILS_SAFE_FWRITE_TO_STDERR(rcutils_get_error_string_safe());

then the sizeof(msg) calculation in the macro gives the size of the pointer:

#define RCUTILS_SAFE_FWRITE_TO_STDERR(msg) fwrite(msg, sizeof(char), sizeof(msg), stderr)

From what I can tell the count passed to fwrite is not a max size, but the size, so I think this line can cause buffer overrun if the msg is less than length 8. That doesn't happen with our existing code because they're all longer (instead our messages get truncated), but it could happen.

What's the appropriate fix here?

  • continue using sizeof(msg) and only use this macro with static buffers
  • switch to strlen(msg) and only use this macro will null-terminated buffers (also a risk)

Activity

  1. added
    bug
    on Dec 1, 2017
  2. added
    question
    on Dec 1, 2017
  3. clalancette commented on Dec 1, 2017

    @clalancette
    Contributor

    Ouch. I don't think we can stick with sizeof(msg) here; there is just way too much risk that someone will pass an allocated pointer to it (and there isn't really a good way to enforce that restriction at compile-time). While strlen(msg) is always a risk, it is a risk you have to take when using C, so I'd suggest we go with that.

  4. wjwwood commented on Dec 1, 2017

    @wjwwood
    Member
  5. clalancette commented on Dec 1, 2017

    @clalancette
    Contributor

    You can use strnlen_s with a relatively large bound to prevent a really malicious case:

    Oh, nice, I didn't know about that. That sounds like a good thing to use.

  6. dhood commented on Dec 1, 2017

    @dhood
    MemberAuthor

    To double check my understanding: strnlen_s with a large number doesn't remove the chance of buffer overrun, it's just that overrun length will have an upper bound, yeah?

  7. wjwwood commented on Dec 1, 2017

    @wjwwood
    Member

    Yeah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions