esp-rs / esp-mbedtls

mbedtls for ESP32 bare-metal
Apache License 2.0
21 stars 10 forks source link

Do not make a copy of the X509 when parsing it to save RAM. #17

Closed AnthonyGrondin closed 3 months ago

AnthonyGrondin commented 1 year ago

We currently already own Certificates<'a> for the lifetime of the session, so this should be a drop-in replacement. This would allow to re-use the same certs in multiple sessions, or with the client and the server at the same time without making unnecessary copies.

I'll paste the doc here:

X.509:link:

Parsing X.509 certificates without copying the raw certificate data:link:

The X.509 CRT parsing APIs mbedtls_x509_crt_parse() and mbedtls_x509_crt_parse_der() create an internal copy of the raw certificate data passed to them. While this allows you to free or reuse the input buffer, it means the raw certificate data will be twice in memory at some point.

To avoid that, the following API can be used to set up an X.509 certificate structure without making a copy of the input buffer:

int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain,
                                       const unsigned char *buf,
                                       size_t buflen );

The only difference between mbedtls_x509_crt_parse_der_nocopy() and mbedtls_x509_crt_parse_der() is that the buffer passed to mbedtls_x509_crt_parse_der_nocopy() holding the raw DER-encoded certificate must stay unmodified for the lifetime of the established X.509 certificate context. See the documentation for more information.

Example: If your own certificate and/or the trusted CA certificates are hardcoded in ROM, you may use mbedtls_x509_parse_der_nocopy() to create X.509 certificate contexts from them without an additional copy in RAM.