]> git.ipfire.org Git - thirdparty/openssl.git/blob - test/testutil/load.c
testutil/load.c: Add checks for file(name) == NULL
[thirdparty/openssl.git] / test / testutil / load.c
1 /*
2 * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (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
8 */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12
13 #include <openssl/x509.h>
14 #include <openssl/pem.h>
15
16 #include "../testutil.h"
17
18 X509 *load_cert_pem(const char *file, OSSL_LIB_CTX *libctx)
19 {
20 X509 *cert = NULL;
21 BIO *bio = NULL;
22
23 if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file())))
24 return NULL;
25 if (TEST_int_gt(BIO_read_filename(bio, file), 0)
26 && TEST_ptr(cert = X509_new_ex(libctx, NULL)))
27 (void)TEST_ptr(cert = PEM_read_bio_X509(bio, &cert, NULL, NULL));
28
29 BIO_free(bio);
30 return cert;
31 }
32
33 STACK_OF(X509) *load_certs_pem(const char *file)
34 {
35 STACK_OF(X509) *certs;
36 BIO *bio;
37 X509 *x;
38
39 if (!TEST_ptr(file) || (bio = BIO_new_file(file, "r")) == NULL)
40 return NULL;
41
42 certs = sk_X509_new_null();
43 if (certs == NULL) {
44 BIO_free(bio);
45 return NULL;
46 }
47
48 ERR_set_mark();
49 do {
50 x = PEM_read_bio_X509(bio, NULL, 0, NULL);
51 if (x != NULL && !sk_X509_push(certs, x)) {
52 sk_X509_pop_free(certs, X509_free);
53 BIO_free(bio);
54 return NULL;
55 } else if (x == NULL) {
56 /*
57 * We probably just ran out of certs, so ignore any errors
58 * generated
59 */
60 ERR_pop_to_mark();
61 }
62 } while (x != NULL);
63
64 BIO_free(bio);
65
66 return certs;
67 }
68
69 EVP_PKEY *load_pkey_pem(const char *file, OSSL_LIB_CTX *libctx)
70 {
71 EVP_PKEY *key = NULL;
72 BIO *bio = NULL;
73
74 if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file())))
75 return NULL;
76 if (TEST_int_gt(BIO_read_filename(bio, file), 0))
77 (void)TEST_ptr(key = PEM_read_bio_PrivateKey_ex(bio, NULL, NULL, NULL,
78 libctx, NULL));
79
80 BIO_free(bio);
81 return key;
82 }
83
84 X509_REQ *load_csr_der(const char *file)
85 {
86 X509_REQ *csr = NULL;
87 BIO *bio = NULL;
88
89 if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new_file(file, "rb")))
90 return NULL;
91 (void)TEST_ptr(csr = d2i_X509_REQ_bio(bio, NULL));
92 BIO_free(bio);
93 return csr;
94 }