testutil: return 1 on success
[openssl.git] / test / d2i_test.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL licenses, (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * https://www.openssl.org/source/license.html
8  * or in the file LICENSE in the source distribution.
9  */
10
11 /* Regression tests for ASN.1 parsing bugs. */
12
13 #include <stdio.h>
14 #include <string.h>
15
16 #include "testutil.h"
17
18 #include <openssl/asn1.h>
19 #include <openssl/bio.h>
20 #include <openssl/err.h>
21 #include <openssl/x509.h>
22 #include <openssl/x509v3.h>
23
24 static const ASN1_ITEM *item_type;
25 static const char *test_file;
26
27 typedef struct d2i_test_fixture {
28     const char *test_case_name;
29 } D2I_TEST_FIXTURE;
30
31
32 static D2I_TEST_FIXTURE set_up(const char *const test_case_name)
33 {
34     D2I_TEST_FIXTURE fixture;
35     fixture.test_case_name = test_case_name;
36     return fixture;
37 }
38
39 static int execute_test(D2I_TEST_FIXTURE fixture)
40 {
41     BIO *bio = NULL;
42     ASN1_VALUE *value = NULL;
43     int ret = 0;
44     unsigned char buf[2048];
45     const unsigned char *buf_ptr = buf;
46     int len;
47
48     if ((bio = BIO_new_file(test_file, "r")) == NULL)
49         return 0;
50
51     /*
52      * We don't use ASN1_item_d2i_bio because it, apparently,
53      * errors too early for some inputs.
54      */
55     len = BIO_read(bio, buf, sizeof buf);
56     if (len < 0)
57         goto err;
58
59     value = ASN1_item_d2i(NULL, &buf_ptr, len, item_type);
60     if (value != NULL)
61         goto err;
62
63     ret = 1;
64
65  err:
66     BIO_free(bio);
67     ASN1_item_free(value, item_type);
68     return ret;
69 }
70
71 static void tear_down(D2I_TEST_FIXTURE fixture)
72 {
73     ERR_print_errors_fp(stderr);
74 }
75
76 #define SETUP_D2I_TEST_FIXTURE() \
77     SETUP_TEST_FIXTURE(D2I_TEST_FIXTURE, set_up)
78
79 #define EXECUTE_D2I_TEST() \
80     EXECUTE_TEST(execute_test, tear_down)
81
82 static int test_bad_asn1()
83 {
84     SETUP_D2I_TEST_FIXTURE();
85     EXECUTE_D2I_TEST();
86 }
87
88 /*
89  * Usage: d2i_test <type> <file>, e.g.
90  * d2i_test generalname bad_generalname.der
91  */
92 int main(int argc, char **argv)
93 {
94     int result = 0;
95     const char *test_type_name;
96
97     if (argc != 3)
98         return 1;
99
100     test_type_name = argv[1];
101     test_file = argv[2];
102
103     if (strcmp(test_type_name, "generalname") == 0) {
104         item_type = ASN1_ITEM_rptr(GENERAL_NAME);
105     } else if (strcmp(test_type_name, "x509") == 0) {
106         item_type = ASN1_ITEM_rptr(X509);
107     } else {
108         fprintf(stderr, "Bad type %s\n", test_type_name);
109         return 1;
110     }
111
112     ADD_TEST(test_bad_asn1);
113
114     result = run_tests(argv[0]);
115
116     return result;
117 }