-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Description
Checks
-
I agree to follow the MicroPython Code of Conduct to ensure a safe and respectful space for everyone.
-
I've searched for existing issues matching this bug, and didn't find any.
Port, board and/or hardware
unix, stm32, pybd
MicroPython version
MicroPython v1.20.0-1189.g49ce7a607 on 2024-04-24; linux [GCC 13.2.1] version
Reproduction
Generate the specific type of DER encoded KEY/CERT pair.
openssl genrsa -out key.pem 1024
openssl req -x509 -newkey rsa:1024 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"
openssl rsa -in key.pem -outform DER -out key.der
openssl x509 -in cert.pem -out cert.der -outform DER
Run interactivley or via script on unix or any STM32 port (all mbedtls ports will be affected)
import tls
ctx = tls.SSLContext(tls.PROTOCOL_TLS_CLIENT)
key = open("key.der", "rb").read()
cert = open("cert.der", "rb").read()
ctx.load_cert_chain(cert, key)
Expected behaviour
This script is expected to run without issue.
Observed behaviour
Traceback (most recent call last):
File "test.py", line 8, in <module>
ValueError: invalid key
Additional Information
As described here (mbedtls_pk_parse_key):
Size of key in bytes. For PEM data, this includes the terminating null byte, so keylen must be equal to strlen(key) + 1
But for DER data it must:
The buffer must contain the input exactly, with no extra trailing material.
The behaviour of mbedtls has changed since the switch to v3.5, it now checks that the provided key buffer does not contain any additional data but only of unencrypted PKCS8 data.
With the change added here, mbedtls_pk_parse_key now fails because the null terminator is included for the "DER" data.
If the simultaneous support for DER and PEM data is desired, there must be a distinction before calling mbedtls_pk_parse_key which must be called with key_len + 1 for PEM data and with key_len for DER data.
When converting the key with the following which results in a PKCS1 DER, the script runs without issue (with both key_len + 1 and key_len) because the PKCS1 parser does not check that the key buffer was fully utilized:
openssl pkey -in key.pem -outform der -out key.der