Fix safestack issues in asn1.h
[openssl.git] / crypto / cmp / cmp_util.c
1 /*
2  * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Nokia 2007-2019
4  * Copyright Siemens AG 2015-2019
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include <string.h>
13 #include <openssl/cmp_util.h>
14 #include "cmp_local.h" /* just for decls of internal functions defined here */
15 #include <openssl/cmperr.h>
16 #include <openssl/err.h> /* should be implied by cmperr.h */
17 #include <openssl/x509v3.h>
18
19 DEFINE_STACK_OF(X509_OBJECT)
20
21 /*
22  * use trace API for CMP-specific logging, prefixed by "CMP " and severity
23  */
24
25 int OSSL_CMP_log_open(void) /* is designed to be idempotent */
26 {
27 #ifndef OPENSSL_NO_STDIO
28     BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE);
29
30     if (bio != NULL && OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, bio))
31         return 1;
32     BIO_free(bio);
33 #endif
34     CMPerr(0, CMP_R_NO_STDIO);
35     return 0;
36 }
37
38 void OSSL_CMP_log_close(void) /* is designed to be idempotent */
39 {
40     (void)OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, NULL);
41 }
42
43 /* return >= 0 if level contains logging level, possibly preceded by "CMP " */
44 #define max_level_len 5 /* = max length of the below strings, e.g., "EMERG" */
45 static OSSL_CMP_severity parse_level(const char *level)
46 {
47     const char *end_level = strchr(level, ':');
48     int len;
49     char level_copy[max_level_len + 1];
50
51     if (end_level == NULL)
52         return -1;
53
54     if (strncmp(level, OSSL_CMP_LOG_PREFIX,
55                 strlen(OSSL_CMP_LOG_PREFIX)) == 0)
56         level += strlen(OSSL_CMP_LOG_PREFIX);
57     len = end_level - level;
58     if (len > max_level_len)
59         return -1;
60     OPENSSL_strlcpy(level_copy, level, len + 1);
61     return
62         strcmp(level_copy, "EMERG") == 0 ? OSSL_CMP_LOG_EMERG :
63         strcmp(level_copy, "ALERT") == 0 ? OSSL_CMP_LOG_ALERT :
64         strcmp(level_copy, "CRIT") == 0 ? OSSL_CMP_LOG_CRIT :
65         strcmp(level_copy, "ERROR") == 0 ? OSSL_CMP_LOG_ERR :
66         strcmp(level_copy, "WARN") == 0 ? OSSL_CMP_LOG_WARNING :
67         strcmp(level_copy, "NOTE") == 0 ? OSSL_CMP_LOG_NOTICE :
68         strcmp(level_copy, "INFO") == 0 ? OSSL_CMP_LOG_INFO :
69         strcmp(level_copy, "DEBUG") == 0 ? OSSL_CMP_LOG_DEBUG :
70         -1;
71 }
72
73 const char *ossl_cmp_log_parse_metadata(const char *buf,
74                                         OSSL_CMP_severity *level,
75                                         char **func, char **file, int *line)
76 {
77     const char *p_func = buf;
78     const char *p_file = buf == NULL ? NULL : strchr(buf, ':');
79     const char *p_level = buf;
80     const char *msg = buf;
81
82     *level = -1;
83     *func = NULL;
84     *file = NULL;
85     *line = 0;
86
87     if (p_file != NULL) {
88         const char *p_line = strchr(++p_file, ':');
89
90         if ((*level = parse_level(buf)) < 0 && p_line != NULL) {
91             /* check if buf contains location info and logging level */
92             char *p_level_tmp = (char *)p_level;
93             const long line_number = strtol(++p_line, &p_level_tmp, 10);
94
95             p_level = p_level_tmp;
96             if (p_level > p_line && *(p_level++) == ':') {
97                 if ((*level = parse_level(p_level)) >= 0) {
98                     *func = OPENSSL_strndup(p_func, p_file - 1 - p_func);
99                     *file = OPENSSL_strndup(p_file, p_line - 1 - p_file);
100                     /* no real problem if OPENSSL_strndup() returns NULL */
101                     *line = (int)line_number;
102                     msg = strchr(p_level, ':') + 1;
103                     if (*msg == ' ')
104                         msg++;
105                 }
106             }
107         }
108     }
109     return msg;
110 }
111
112 #define UNKNOWN_FUNC "(unknown function)" /* the default for OPENSSL_FUNC */
113 /*
114  * substitute fallback if component/function name is NULL or empty or contains
115  * just pseudo-information "(unknown function)" due to -pedantic and macros.h
116  */
117 static const char *improve_location_name(const char *func, const char *fallback)
118 {
119     if (fallback == NULL)
120         return func == NULL ? UNKNOWN_FUNC : func;
121
122     return func == NULL || *func == '\0' || strcmp(func, UNKNOWN_FUNC) == 0
123         ? fallback : func;
124 }
125
126 int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file,
127                           int line, OSSL_CMP_severity level, const char *msg)
128 {
129     const char *level_string =
130         level == OSSL_CMP_LOG_EMERG ? "EMERG" :
131         level == OSSL_CMP_LOG_ALERT ? "ALERT" :
132         level == OSSL_CMP_LOG_CRIT ? "CRIT" :
133         level == OSSL_CMP_LOG_ERR ? "error" :
134         level == OSSL_CMP_LOG_WARNING ? "warning" :
135         level == OSSL_CMP_LOG_NOTICE ? "NOTE" :
136         level == OSSL_CMP_LOG_INFO ? "info" :
137         level == OSSL_CMP_LOG_DEBUG ? "DEBUG" : "(unknown level)";
138
139 #ifndef NDEBUG
140     if (BIO_printf(bio, "%s:%s:%d:", improve_location_name(component, "CMP"),
141                    file, line) < 0)
142         return 0;
143 #endif
144     return BIO_printf(bio, OSSL_CMP_LOG_PREFIX"%s: %s\n",
145                       level_string, msg) >= 0;
146 }
147
148 #define ERR_PRINT_BUF_SIZE 4096
149 /* this is similar to ERR_print_errors_cb, but uses the CMP-specific cb type */
150 void OSSL_CMP_print_errors_cb(OSSL_CMP_log_cb_t log_fn)
151 {
152     unsigned long err;
153     char msg[ERR_PRINT_BUF_SIZE];
154     const char *file = NULL, *func = NULL, *data = NULL;
155     int line, flags;
156
157     while ((err = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) {
158         const char *component =
159             improve_location_name(func, ERR_lib_error_string(err));
160
161         if (!(flags & ERR_TXT_STRING))
162             data = NULL;
163         BIO_snprintf(msg, sizeof(msg), "%s%s%s", ERR_reason_error_string(err),
164                      data == NULL || *data == '\0' ? "" : " : ",
165                      data == NULL ? "" : data);
166         if (log_fn == NULL) {
167 #ifndef OPENSSL_NO_STDIO
168             BIO *bio = BIO_new_fp(stderr, BIO_NOCLOSE);
169
170             if (bio != NULL) {
171                 OSSL_CMP_print_to_bio(bio, component, file, line,
172                                       OSSL_CMP_LOG_ERR, msg);
173                 BIO_free(bio);
174             }
175 #else
176             /* CMPerr(0, CMP_R_NO_STDIO) makes no sense during error printing */
177 #endif
178         } else {
179             if (log_fn(component, file, line, OSSL_CMP_LOG_ERR, msg) <= 0)
180                 break; /* abort outputting the error report */
181         }
182     }
183 }
184
185 int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs,
186                                    int only_self_signed)
187 {
188     int i;
189
190     if (store == NULL) {
191         CMPerr(0, CMP_R_NULL_ARGUMENT);
192         return 0;
193     }
194     if (certs == NULL)
195         return 1;
196     for (i = 0; i < sk_X509_num(certs); i++) {
197         X509 *cert = sk_X509_value(certs, i);
198
199         if (!only_self_signed || X509_self_signed(cert, 0) == 1)
200             if (!X509_STORE_add_cert(store, cert)) /* ups cert ref counter */
201                 return 0;
202     }
203     return 1;
204 }
205
206 /*-
207  * Builds a certificate chain starting from <cert>
208  * using the optional list of intermediate CA certificates <certs>.
209  * If <store> is NULL builds the chain as far down as possible, ignoring errors.
210  * Else the chain must reach a trust anchor contained in <store>.
211  *
212  * Returns NULL on error, else a pointer to a stack of (up_ref'ed) certificates
213  * starting with given EE certificate and followed by all available intermediate
214  * certificates down towards any trust anchor but without including the latter.
215  *
216  * NOTE: If a non-NULL stack is returned the caller is responsible for freeing.
217  * NOTE: In case there is more than one possibility for the chain,
218  * OpenSSL seems to take the first one; check X509_verify_cert() for details.
219  */
220 /* TODO this should be of more general interest and thus be exported. */
221 STACK_OF(X509)
222     *ossl_cmp_build_cert_chain(OPENSSL_CTX *libctx, const char *propq,
223                                X509_STORE *store,
224                                STACK_OF(X509) *certs, X509 *cert)
225 {
226     STACK_OF(X509) *chain = NULL, *result = NULL;
227     X509_STORE *ts = store == NULL ? X509_STORE_new() : store;
228     X509_STORE_CTX *csc = NULL;
229
230     if (ts == NULL || cert == NULL) {
231         CMPerr(0, CMP_R_NULL_ARGUMENT);
232         goto err;
233     }
234
235     if ((csc = X509_STORE_CTX_new_with_libctx(libctx, propq)) == NULL)
236         goto err;
237     if (store == NULL && certs != NULL
238             && !ossl_cmp_X509_STORE_add1_certs(ts, certs, 0))
239         goto err;
240     if (!X509_STORE_CTX_init(csc, ts, cert,
241                              store == NULL ? NULL : certs))
242         goto err;
243     /* disable any cert status/revocation checking etc. */
244     X509_VERIFY_PARAM_clear_flags(X509_STORE_CTX_get0_param(csc),
245                                   ~(X509_V_FLAG_USE_CHECK_TIME
246                                     | X509_V_FLAG_NO_CHECK_TIME));
247
248     if (X509_verify_cert(csc) <= 0 && store != NULL)
249         goto err;
250     chain = X509_STORE_CTX_get0_chain(csc);
251
252     /* result list to store the up_ref'ed not self-signed certificates */
253     if ((result = sk_X509_new_null()) == NULL)
254         goto err;
255     if (!X509_add_certs(result, chain,
256                         X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
257                         | X509_ADD_FLAG_NO_SS)) {
258         sk_X509_free(result);
259         result = NULL;
260     }
261
262  err:
263     if (store == NULL)
264         X509_STORE_free(ts);
265     X509_STORE_CTX_free(csc);
266     return result;
267 }
268
269 int ossl_cmp_sk_ASN1_UTF8STRING_push_str(STACK_OF(ASN1_UTF8STRING) *sk,
270                                          const char *text)
271 {
272     ASN1_UTF8STRING *utf8string;
273
274     if (!ossl_assert(sk != NULL && text != NULL))
275         return 0;
276     if ((utf8string = ASN1_UTF8STRING_new()) == NULL)
277         return 0;
278     if (!ASN1_STRING_set(utf8string, text, -1))
279         goto err;
280     if (!sk_ASN1_UTF8STRING_push(sk, utf8string))
281         goto err;
282     return 1;
283
284  err:
285     ASN1_UTF8STRING_free(utf8string);
286     return 0;
287 }
288
289 int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt,
290                                     const ASN1_OCTET_STRING *src)
291 {
292     ASN1_OCTET_STRING *new;
293     if (tgt == NULL) {
294         CMPerr(0, CMP_R_NULL_ARGUMENT);
295         return 0;
296     }
297     if (*tgt == src) /* self-assignment */
298         return 1;
299
300     if (src != NULL) {
301         if ((new = ASN1_OCTET_STRING_dup(src)) == NULL)
302             return 0;
303     } else {
304         new = NULL;
305     }
306
307     ASN1_OCTET_STRING_free(*tgt);
308     *tgt = new;
309     return 1;
310 }
311
312 int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt,
313                                           const unsigned char *bytes, int len)
314 {
315     ASN1_OCTET_STRING *new = NULL;
316
317     if (tgt == NULL) {
318         CMPerr(0, CMP_R_NULL_ARGUMENT);
319         return 0;
320     }
321     if (bytes != NULL) {
322         if ((new = ASN1_OCTET_STRING_new()) == NULL
323                 || !(ASN1_OCTET_STRING_set(new, bytes, len))) {
324             ASN1_OCTET_STRING_free(new);
325             return 0;
326         }
327     }
328
329     ASN1_OCTET_STRING_free(*tgt);
330     *tgt = new;
331     return 1;
332 }