From 92a00177b1792955d45f8653ea60eb986b21c90a Mon Sep 17 00:00:00 2001 From: tb <> Date: Sun, 4 Jan 2026 09:36:34 +0000 Subject: asn1basic: add example showing current bogus encoding There is a bug in i2c_ASN1_BIT_STRING() resulting in nonsense encoding of some BIT STRINGs with trailing zeroes if ASN1_STRING_FLAG_BITS_LEFT is not set (a rare corner case). This test currently passes when it shouldn't. --- src/regress/lib/libcrypto/asn1/asn1basic.c | 39 +++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/regress/lib/libcrypto/asn1/asn1basic.c b/src/regress/lib/libcrypto/asn1/asn1basic.c index f900e45be5..7c4e329e4b 100644 --- a/src/regress/lib/libcrypto/asn1/asn1basic.c +++ b/src/regress/lib/libcrypto/asn1/asn1basic.c @@ -1,4 +1,4 @@ -/* $OpenBSD: asn1basic.c,v 1.17 2025/12/18 09:15:28 tb Exp $ */ +/* $OpenBSD: asn1basic.c,v 1.18 2026/01/04 09:36:34 tb Exp $ */ /* * Copyright (c) 2017, 2021 Joel Sing * Copyright (c) 2021 Google, Inc @@ -66,6 +66,14 @@ const uint8_t asn1_bit_string_primitive[] = { 0x04, 0x0a, 0x3b, 0x5f, 0x29, 0x1c, 0xd0, }; +static const uint8_t asn1_bit_string_trailing_zeroes[] = { + 0x04, 0x00 +}; + +static const uint8_t asn1_bit_string_trailing_zeroes_encoded[] = { + 0x03, 0x03, 0x02, 0x04, 0x00, +}; + static int asn1_bit_string_test(void) { @@ -166,6 +174,35 @@ asn1_bit_string_test(void) sizeof(asn1_bit_string_primitive))) goto failed; + /* + * ASN1_STRING_set() attempts to truncate and picks up wrong unused bits + */ + + ASN1_BIT_STRING_free(abs); + abs = NULL; + if ((abs = ASN1_BIT_STRING_new()) == NULL) { + fprintf(stderr, "FAIL: ASN1_BIT_STRING_new\n"); + goto failed; + } + + if (!ASN1_STRING_set(abs, asn1_bit_string_trailing_zeroes, + sizeof(asn1_bit_string_trailing_zeroes))) { + fprintf(stderr, "FAIL: BIT STRING ASN1_BIT_STRING_set trailing zeroes\n"); + goto failed; + } + + freezero(p, len); + p = NULL; + if ((len = i2d_ASN1_BIT_STRING(abs, &p)) <= 0) { + fprintf(stderr, "FAIL: i2d_ASN1_BIT_STRING\n"); + len = 0; + goto failed; + } + if (!asn1_compare_bytes("BIT STRING trailing zeroes", p, len, + asn1_bit_string_trailing_zeroes_encoded, + sizeof(asn1_bit_string_trailing_zeroes_encoded))) + goto failed; + failed = 0; failed: -- cgit v1.2.3-55-g6feb