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