From 9e8de7de8d91d4336755606feaa19ff2e44e99ba Mon Sep 17 00:00:00 2001 From: divVerent Date: Fri, 21 Aug 2026 10:49:36 +0200 Subject: [PATCH] Do not assume that ASN1_STRING is null terminated. The OpenSSL docs say: > In general it cannot be assumed that the data returned by > ASN1_STRING_data() is null terminated or does not contain embedded > nulls. The actual format of the data will depend on the actual string > type itself: for example for an IA5String the data will be ASCII, for a > BMPString two bytes per character in big endian format, and for a > UTF8String it will be in UTF8 format. This ASN1 timestamp function was the only remaining function in pyOpenSSL that assumed null termination. --- src/OpenSSL/crypto.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/OpenSSL/crypto.py b/src/OpenSSL/crypto.py index 314b577f..a7e8de69 100644 --- a/src/OpenSSL/crypto.py +++ b/src/OpenSSL/crypto.py @@ -203,12 +203,14 @@ def _get_asn1_time(timestamp: Any) -> bytes | None: format. Or C{None} if the object contains no time value. """ string_timestamp = _ffi.cast("ASN1_STRING*", timestamp) - if _lib.ASN1_STRING_length(string_timestamp) == 0: + string_length = _lib.ASN1_STRING_length(string_timestamp) + if string_length == 0: return None elif ( _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME ): - return _ffi.string(_lib.ASN1_STRING_get0_data(string_timestamp)) + string_data = _lib.ASN1_STRING_get0_data(string_timestamp) + return _ffi.buffer(string_data, string_length)[:] else: generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**") _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp) @@ -216,7 +218,8 @@ def _get_asn1_time(timestamp: Any) -> bytes | None: string_timestamp = _ffi.cast("ASN1_STRING*", generalized_timestamp[0]) string_data = _lib.ASN1_STRING_get0_data(string_timestamp) - string_result = _ffi.string(string_data) + string_length = _lib.ASN1_STRING_length(string_timestamp) + string_result = _ffi.buffer(string_data, string_length)[:] _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0]) return string_result