Skip to content

Report out-of-memory and any other malloc failures already within CRYPTO_malloc and friends #6251

Closed

Description

@DDvO

As partly discussed already in #5781 and #6217:

Currently there are some 900 places within crypto/ and ssl/ where in case CRYPTO_malloc() and friends returned NULL an error report with the reason ERR_R_MALLOC_FAILURE is pushed on the ERR queue, rather than the allocation function reporting the error itself. This approach is not only pretty redundant and cumbersome but also more or less inaccurate and error-prone:

  • Assuming that the callers of the allocation function(s) are responsible for flagging memory allocation failure, it easily happens that callers simply forget (or do not care) to do so. There are (or at least were) many occurrences of such false negatives.
  • Indirect callers of functions that involve memory allocation can also report false positives regarding ERR_R_MALLOC_FAILURE where they misinterpret the reason for obtaining a NULL pointer in case this was not actually due to an malloc failure but due to some other issue (see, e.g.., two instances fixed in improve EVP cipher param diagnostics on unsupported cipher modes and malloc failure #6217).
  • It also happens that indirect callers of functions that involve memory allocation re-report ERR_R_MALLOC_FAILURE after obtaining a NULL pointer though the malloc failure has already been reported by a function in between (see, e.g.., two instances fixed in improve EVP cipher param diagnostics on unsupported cipher modes and malloc failure #6217 caused by the same calls PKCS12err(PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT, ERR_R_MALLOC_FAILURE); as in the item before).
  • If a function like CRYPTO_malloc() does the error reporting itself this relieves all its callers from doing so.
  • A function like CRYPTO_malloc() can do the failure/error reporting more accurately than its callers because it knows, in contrast to them, whether the failure is due to memory shortage or due to other issues like unsuitable arguments.

When I asked why CRYPTO_malloc() does not do the error reporting itself I learned about the following reasons.

  • An malloc failure could either be because the system is running low on memory, or the call to CRYPTO_malloc() was erroneous (e.g. because it incorrectly attempts to allocate a vast amount of memory). In the second case this kind of problem would be difficult to find if all you have is the error code in CRYPTO_malloc().
  • In the same direction goes the desire to preserve the file/line numbers (and if possible also the function name) of the caller(s) for being able to trace.
  • A entirely different issue is that the ERR reporting may in turn need memory allocation (in case its internal queue allocated so far has become full), which may cause a loop in case memory is exhausted.

Here are some thoughts on these issues and suggestions how to deal with them.

  • In case of an actual out-of-memory situation it would not help to obtain information about the caller because this is a low-level issue related to the execution environment (rather than to the caller).
  • In case of other reasons for malloc failures the malloc functions should give specific error reasons (which the callers cannot do), such as an overly large amount of memory requested or any internal allocation function issue. In case the caller gave an unsuitable argument it may be helpful to know which caller it was, but this is a very general issue that would better be solved more generally (such as, by providing a stack trace as far as possible). When specific value is seen in reporting malloc failures within some calling functions of course this can be done in addition to a more low-level reporting by the malloc function itself.
  • In order to remove the obstacle of a potential loop with the ERR queue, it should be possible to adapt its implementation such that there is always an element pre-allocated and reserved for use by malloc functions in case there is actually shortage of memory, such that in case the malloc function adds an ERR_R_OUT_OF_MEMORY entry there is no need to (recursively) allocate it. When an out-of-memory error has already been reported (and thus the reserved cell has been filled) any further requests to add elements to the ERR queue should be ignored in case the queue buffer is full and would need re-allocation (supposedly this would be acceptable because the entry regarding the out-of-memory error is already in the queue and at least from the library's point of view an out-of-memory condition is fatal anyway).

Activity

  1. mattcaswell commented on May 14, 2018

    @mattcaswell
    Member

    In case the caller gave an unsuitable argument it may be helpful to know which caller it was,

    As pointed out in #6217, CRYPTO_malloc() actually knows who the caller is because it gets passed the file and line number of the caller in its arguments. So it seems we could record information about the caller from inside the CRYPTO_malloc() implementation.

  2. bernd-edlinger commented on May 14, 2018

    @bernd-edlinger
    Member

    It is often the case that malfunction starts at a single malloc failure, and it is good to
    have the complete call stack when that happens, becase you cannot tell where exactly
    the error handling is broken, it is usually not the direct caller of CRYPTO_malloc.

  3. mspncp commented on May 14, 2018

    @mspncp
    Contributor

    As pointed out in #6217 (comment), there was some initial discussion in #6217 #5781 about doing the reporting in CRYPTO_malloc() itself, using file and line information provided by the caller. I don't really remember, why that thought was discarded at that time. Maybe it was simply overlayed by the discussion about the memory allocation problem in ERR_put_error(), which started briefly after that. Looking back, it's a pity that we did not follow that idea any further.

  4. bernd-edlinger commented on May 14, 2018

    @bernd-edlinger
    Member

    Maybe, but as I said, if you only know that you have a malfunction that started at a specific
    malloc call, then you have not enough data to track down the bug. There is no replacement
    for proper error handling at all. That includes recoding file names / line numbers along
    the whole call stack until the error condition is resolved.

  5. mspncp commented on May 14, 2018

    @mspncp
    Contributor

    Hmmm... but pushing all these file names and line numbers on the error stack after a malloc failure will most certainly fail. So unless you keep track of the call stacks before the error occurs (you would have to do it all the time, which is a waste) or rely on os methods to walk the stack, the best you can get is probably a single malloc error message (which is much better than no error message at all). And in that case, I don't see any reason why this could not have been done by CRYPTO_malloc() itself.

  6. DDvO commented on May 14, 2018

    @DDvO
    ContributorAuthor

    It is often the case that malfunction starts at a single malloc failure, and it is good to
    have the complete call stack when that happens, becase you cannot tell where exactly
    the error handling is broken, it is usually not the direct caller of CRYPTO_malloc.

    I see error reporting (and in particular the place where malloc failure reporting is done, which is the topic of this issue) and error handling as different things.
    Of course, if a (direct or indirect) caller of an malloc function fails to check the obtained pointer for NULL or does some other related mistake, this is a major issue, but not one for which the malloc function would be responsible. The malloc function might include the file name and line number of its (direct) caller in its error reports, but I'd see this only as a secondary extra service.

  7. DDvO commented on May 14, 2018

    @DDvO
    ContributorAuthor

    In other words, my suggestion is basically just to remove the need to have all those
    XYZerr(XYZ_F_NM, ERR_R_MALLOC_FAILURE) invocations, essentially by adding

        if (ret == NULL)
            CRYPTOerr(CRYPTO_F_CRYPTO_MALLOC, ERR_R_MALLOC_FAILURE); 
    

    to CRYPTO_malloc() and friends.
    Of course, the checks for NULL need to stay at the callers' side, such that a typical invocation would simplify from

        ptr = CRYPTO_malloc(size);
        if (ptr == NULL) {
            XYZerr(XYZ_F_NM, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    

    to

        ptr = CRYPTO_malloc(size);
        if (ptr == NULL)
            goto err;
    

    Or is there any real drawback or unsolvable obstacle for this?
    Of course, callers would still be free to keep their XYZerr(XYZ_F_NM, ERR_R_MALLOC_FAILURE) if that is felt to be of any help.

  8. richsalz commented on May 14, 2018

    @richsalz
    Contributor

    Use ERR_put_error inside the allocation routines (look at how CRYPTOerr is defined).
    That still has to address the error-in-error-handler loop issue.

  9. DDvO commented on May 14, 2018

    @DDvO
    ContributorAuthor

    Use ERR_put_error inside the allocation routines (look at how CRYPTOerr is defined).
    That still has to address the error-in-error-handler loop issue.

    Of course.
    I just checked and found that ERR_put_error(), as already mentioned by @bernd-edlinger #5781 (comment), invokes ERR_get_state() which in turn calls OPENSSL_zalloc() when called for the first time. After that, in contrast to what I expected, the queue is never re-allocated. This actually simplifies the solution to the loop issue.
    I see two approaches:

    • make sure, as already suggested by @FdaSilvaYY Push error onto the stack when malloc fails in scrypt #5781 (comment), that the dynamic allocation always happens during statup (where memory shortage does not need to be expected)
    • or make the whole ERR_STATE structure (rather than just the state pointer to it) a static element of the memory of the CRYPTO_THREAD, such that it is automatically allocated already on loading the library.
  10. bernd-edlinger commented on May 14, 2018

    @bernd-edlinger
    Member

    Yes, the interesting question is, how you want to make sure that the error state
    is always allocated whenever a new thread starts and how to prevent the new thread
    from running into an undefined state, when that allocation fails.

  11. bernd-edlinger commented on May 14, 2018

    @bernd-edlinger
    Member

    Additional question: how to allocate the error state for threads that are already running
    before OPENSSL_init_crypto is called for the first time.

  12. DDvO commented on May 14, 2018

    @DDvO
    ContributorAuthor

    Is there maybe a possibility to statically assign a memory area (of rather small size, in this case sizeof(ERR_STATE)) to each new thread of an application that uses OpenSSL?

  13. richsalz commented on May 14, 2018

    @richsalz
    Contributor

    How many static areas should we create? Do folks think the API doesn't malloc internally?

    Move on.

  14. DDvO commented on May 15, 2018

    @DDvO
    ContributorAuthor

    There are technically much simpler solutions to the ERR/malloc loop problem.

    How about replacing in ERR_get_state() the use of OPENSSL_zalloc() by malloc() and memset()
    (and consequently replacing in ERR_STATE_free() the OPENSSL_free() call by free())?

    Or even more straightforward and certainly acceptable:
    Replace in ERR_get_state() the use of OPENSSL_zalloc() by a variant of OPENSSL_malloc() that does not invoke CRYPTOerr() (while the default variant would do the error reporting as sketched above) and then, as above, use memset().

  15. added this to the milestone on May 15, 2018
  16. 1 remaining item

  17. added a commit that references this issue on Apr 12, 2021
    1a8143c
  18. modified the milestones: , Post 3.0.0 on May 13, 2021
  19. added
    branch: master
    triaged: feature
    on Aug 9, 2021
  20. added a commit that references this issue on Aug 15, 2022
    4ffb7d2
  21. modified the milestones: Post 3.0.0, 3.1.0 on Aug 15, 2022
  22. added
    triaged: bug
    on Aug 15, 2022
  23. changed the title [-]Report out-of-memory and any other malloc failures better already within CRYPTO_malloc and friends[/-] [+]Report out-of-memory and any other malloc failures already within CRYPTO_malloc and friends[/+] on Aug 15, 2022
  24. added a commit that references this issue on Aug 26, 2022
    d3fa6cc
  25. added a commit that references this issue on Sep 24, 2022
    155e16a
  26. added a commit that references this issue on Dec 26, 2022
    f26761c
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

    branch: mastertriaged: bugtriaged: feature

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions