Backport 2.16: Remove Extraneous bytes from buffer post pem write #3935
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
In order to remove some big (4k) buffers from being created on the stack, the output buffer was re-used - in this case the raw der data is written to the buffer prior to being base64 encoded into an allocated buffer, and then overwritten with the pem data. However, even though the pem data is zero terminated, usually der data will remain in the buffer after the terminator.
Should this buffer get passed into mbedtls_x509_crt_parse() then it will likely fail to parse, as it decides whether or not a buffer is pem by checking the last byte of the buffer for being zero - if it isn't zero, it will attempt to parse as der, which will obviously fail.
This just ensures the buffer is cleaned to avoid the regression, there may be future work around this subject to make the area safer and tests to ensure this doesn't happen again.
This is a backport of #3898
Status
READY
Steps to test or reproduce
See #3682