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).
diff --git a/library/x509write_csr.c b/library/x509write_csr.c
index 0d62d1d..accb448 100644
--- a/library/x509write_csr.c
+++ b/library/x509write_csr.c
@@ -274,17 +274,16 @@
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 );