x509write_csr: Reduce stack usage of mbedtls_x509write_csr_pem()

Using 4096 bytes of stack for the temporary buffer used for holding a
throw-away DER-formatted CSR limits the portability of generating
certificate signing requests to only devices with lots of stack space.
To increase portability, use the mbedtls_pem_write_buffer() in-place
capability instead, using the same buffer for input and output. This
works since the DER encoding for some given data is always smaller than
that same data PEM-encoded.

PEM format is desirable to use even on stack-constrained devices as the
format is easy to work with (for example, copy-pasting from a tiny
device's serial console output, for CSRs generated on tiny devices
without the private key leaving said tiny device).
This commit is contained in:
Jaeden Amero 2019-10-18 16:02:07 +01:00
parent 7b6d8c27c8
commit 6ffac75995

View file

@ -274,17 +274,16 @@ int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, s
void *p_rng )
{
int ret;
unsigned char output_buf[4096];
size_t olen = 0;
if( ( ret = mbedtls_x509write_csr_der( ctx, output_buf, sizeof(output_buf),
if( ( ret = mbedtls_x509write_csr_der( ctx, buf, size,
f_rng, p_rng ) ) < 0 )
{
return( ret );
}
if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CSR, PEM_END_CSR,
output_buf + sizeof(output_buf) - ret,
buf + size - ret,
ret, buf, size, &olen ) ) != 0 )
{
return( ret );