2 * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* Regression tests for ASN.1 parsing bugs. */
16 #include "test_main_custom.h"
18 #include <openssl/asn1.h>
19 #include <openssl/asn1t.h>
20 #include <openssl/bio.h>
21 #include <openssl/err.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
26 static const ASN1_ITEM *item_type;
27 static const char *test_file;
40 expected_error_t code;
43 static expected_error_t expected_error = ASN1_UNKNOWN;
45 static int test_bad_asn1()
48 ASN1_VALUE *value = NULL;
50 unsigned char buf[2048];
51 const unsigned char *buf_ptr = buf;
52 unsigned char *der = NULL;
56 bio = BIO_new_file(test_file, "r");
60 if (expected_error == ASN1_BIO) {
61 if (TEST_ptr_null(ASN1_item_d2i_bio(item_type, bio, NULL)))
67 * Unless we are testing it we don't use ASN1_item_d2i_bio because it
68 * performs sanity checks on the input and can reject it before the
71 len = BIO_read(bio, buf, sizeof buf);
72 if (!TEST_int_ge(len, 0))
75 value = ASN1_item_d2i(NULL, &buf_ptr, len, item_type);
77 if (TEST_int_eq(expected_error, ASN1_DECODE))
82 derlen = ASN1_item_i2d(value, &der, item_type);
84 if (der == NULL || derlen < 0) {
85 if (TEST_int_eq(expected_error, ASN1_ENCODE))
90 if (derlen != len || memcmp(der, buf, derlen) != 0) {
91 if (TEST_int_eq(expected_error, ASN1_COMPARE))
96 if (TEST_int_eq(expected_error, ASN1_OK))
100 /* Don't indicate success for memory allocation errors */
102 && !TEST_false(ERR_GET_REASON(ERR_peek_error()) == ERR_R_MALLOC_FAILURE))
106 ASN1_item_free(value, item_type);
111 * Usage: d2i_test <type> <file>, e.g.
112 * d2i_test generalname bad_generalname.der
114 int test_main(int argc, char *argv[])
116 const char *test_type_name;
117 const char *expected_error_string;
121 static error_enum expected_errors[] = {
124 {"decode", ASN1_DECODE},
125 {"encode", ASN1_ENCODE},
126 {"compare", ASN1_COMPARE}
129 if (!TEST_int_eq(argc, 4)) {
130 fprintf(stderr, "Usage: d2i_test item_name expected_error file.der\n");
134 test_type_name = argv[1];
135 expected_error_string = argv[2];
138 item_type = ASN1_ITEM_lookup(test_type_name);
140 if (item_type == NULL) {
141 TEST_error("Unknown type %s\n", test_type_name);
142 fprintf(stderr, "Supported types:\n");
144 const ASN1_ITEM *it = ASN1_ITEM_get(i);
148 fprintf(stderr, "\t%s\n", it->sname);
153 for (i = 0; i < OSSL_NELEM(expected_errors); i++) {
154 if (strcmp(expected_errors[i].str, expected_error_string) == 0) {
155 expected_error = expected_errors[i].code;
160 if (expected_error == ASN1_UNKNOWN) {
161 TEST_error("Unknown expected error %s\n", expected_error_string);
165 ADD_TEST(test_bad_asn1);
167 return run_tests(argv[0]);