From 6ffac75995f2a6df3d2cb8df58d6522cb73fda17 Mon Sep 17 00:00:00 2001 From: Jaeden Amero Date: Fri, 18 Oct 2019 16:02:07 +0100 Subject: [PATCH] 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). --- library/x509write_csr.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/library/x509write_csr.c b/library/x509write_csr.c index 0d62d1d48..accb44827 100644 --- a/library/x509write_csr.c +++ b/library/x509write_csr.c @@ -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 );