Minos Galanakis | 2c824b4 | 2025-03-20 09:28:45 +0000 | [diff] [blame^] | 1 | /** \file asn1_helpers.c |
| 2 | * |
| 3 | * \brief Helper functions for tests that manipulate ASN.1 data. |
| 4 | */ |
| 5 | |
| 6 | /* |
| 7 | * Copyright The Mbed TLS Contributors |
| 8 | * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later |
| 9 | */ |
| 10 | |
| 11 | #include <test/helpers.h> |
| 12 | #include <test/macros.h> |
| 13 | |
| 14 | #if defined(MBEDTLS_ASN1_PARSE_C) |
| 15 | |
| 16 | #include <mbedtls/asn1.h> |
| 17 | |
| 18 | #include <test/asn1_helpers.h> |
| 19 | |
| 20 | int mbedtls_test_asn1_skip_integer(unsigned char **p, const unsigned char *end, |
| 21 | size_t min_bits, size_t max_bits, |
| 22 | int must_be_odd) |
| 23 | { |
| 24 | size_t len; |
| 25 | size_t actual_bits; |
| 26 | unsigned char msb; |
| 27 | TEST_EQUAL(mbedtls_asn1_get_tag(p, end, &len, |
| 28 | MBEDTLS_ASN1_INTEGER), |
| 29 | 0); |
| 30 | |
| 31 | /* Check if the retrieved length doesn't extend the actual buffer's size. |
| 32 | * It is assumed here, that end >= p, which validates casting to size_t. */ |
| 33 | TEST_ASSERT(len <= (size_t) (end - *p)); |
| 34 | |
| 35 | /* Tolerate a slight departure from DER encoding: |
| 36 | * - 0 may be represented by an empty string or a 1-byte string. |
| 37 | * - The sign bit may be used as a value bit. */ |
| 38 | if ((len == 1 && (*p)[0] == 0) || |
| 39 | (len > 1 && (*p)[0] == 0 && ((*p)[1] & 0x80) != 0)) { |
| 40 | ++(*p); |
| 41 | --len; |
| 42 | } |
| 43 | if (min_bits == 0 && len == 0) { |
| 44 | return 1; |
| 45 | } |
| 46 | msb = (*p)[0]; |
| 47 | TEST_ASSERT(msb != 0); |
| 48 | actual_bits = 8 * (len - 1); |
| 49 | while (msb != 0) { |
| 50 | msb >>= 1; |
| 51 | ++actual_bits; |
| 52 | } |
| 53 | TEST_ASSERT(actual_bits >= min_bits); |
| 54 | TEST_ASSERT(actual_bits <= max_bits); |
| 55 | if (must_be_odd) { |
| 56 | TEST_ASSERT(((*p)[len-1] & 1) != 0); |
| 57 | } |
| 58 | *p += len; |
| 59 | return 1; |
| 60 | exit: |
| 61 | return 0; |
| 62 | } |
| 63 | |
| 64 | #endif /* MBEDTLS_ASN1_PARSE_C */ |