a68f7010629b521a58cea12d2c9f05a393d68e48
[openssl.git] / crypto / cmp / cmp_util.c
1 /*
2  * Copyright 2007-2019 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 /*
20  * use trace API for CMP-specific logging, prefixed by "CMP " and severity
21  */
22
23 int OSSL_CMP_log_open(void) /* is designed to be idempotent */
24 {
25 #ifndef OPENSSL_NO_STDIO
26     BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE);
27
28     if (bio != NULL && OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, bio))
29         return 1;
30     BIO_free(bio);
31 #endif
32     CMPerr(0, CMP_R_NO_STDIO);
33     return 0;
34 }
35
36 void OSSL_CMP_log_close(void) /* is designed to be idempotent */
37 {
38     (void)OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, NULL);
39 }
40
41 /* return >= 0 if level contains logging level, possibly preceded by "CMP " */
42 #define max_level_len 5 /* = max length of the below strings, e.g., "EMERG" */
43 static OSSL_CMP_severity parse_level(const char *level)
44 {
45     const char *end_level = strchr(level, ':');
46     int len;
47     char level_copy[max_level_len + 1];
48
49     if (end_level == NULL)
50         return -1;
51
52     if (strncmp(level, OSSL_CMP_LOG_PREFIX,
53                 strlen(OSSL_CMP_LOG_PREFIX)) == 0)
54         level += strlen(OSSL_CMP_LOG_PREFIX);
55     len = end_level - level;
56     if (len > max_level_len)
57         return -1;
58     OPENSSL_strlcpy(level_copy, level, len + 1);
59     return
60         strcmp(level_copy, "EMERG") == 0 ? OSSL_CMP_LOG_EMERG :
61         strcmp(level_copy, "ALERT") == 0 ? OSSL_CMP_LOG_ALERT :
62         strcmp(level_copy, "CRIT") == 0 ? OSSL_CMP_LOG_CRIT :
63         strcmp(level_copy, "ERROR") == 0 ? OSSL_CMP_LOG_ERR :
64         strcmp(level_copy, "WARN") == 0 ? OSSL_CMP_LOG_WARNING :
65         strcmp(level_copy, "NOTE") == 0 ? OSSL_CMP_LOG_NOTICE :
66         strcmp(level_copy, "INFO") == 0 ? OSSL_CMP_LOG_INFO :
67         strcmp(level_copy, "DEBUG") == 0 ? OSSL_CMP_LOG_DEBUG :
68         -1;
69 }
70
71 const char *ossl_cmp_log_parse_metadata(const char *buf,
72                                         OSSL_CMP_severity *level,
73                                         char **func, char **file, int *line)
74 {
75     const char *p_func = buf;
76     const char *p_file = buf == NULL ? NULL : strchr(buf, ':');
77     const char *p_level = buf;
78     const char *msg = buf;
79
80     *level = -1;
81     *func = NULL;
82     *file = NULL;
83     *line = 0;
84
85     if (p_file != NULL) {
86         const char *p_line = strchr(++p_file, ':');
87
88         if ((*level = parse_level(buf)) < 0 && p_line != NULL) {
89             /* check if buf contains location info and logging level */
90             char *p_level_tmp = (char *)p_level;
91             const long line_number = strtol(++p_line, &p_level_tmp, 10);
92
93             p_level = p_level_tmp;
94             if (p_level > p_line && *(p_level++) == ':') {
95                 if ((*level = parse_level(p_level)) >= 0) {
96                     *func = OPENSSL_strndup(p_func, p_file - 1 - p_func);
97                     *file = OPENSSL_strndup(p_file, p_line - 1 - p_file);
98                     /* no real problem if OPENSSL_strndup() returns NULL */
99                     *line = (int)line_number;
100                     msg = strchr(p_level, ':') + 1;
101                     if (*msg == ' ')
102                         msg++;
103                 }
104             }
105         }
106     }
107     return msg;
108 }
109
110 #define UNKNOWN_FUNC "(unknown function)" /* the default for OPENSSL_FUNC */
111 /*
112  * substitute fallback if component/function name is NULL or empty or contains
113  * just pseudo-information "(unknown function)" due to -pedantic and macros.h
114  */
115 static const char *improve_location_name(const char *func, const char *fallback)
116 {
117     if (!ossl_assert(fallback != NULL))
118         return NULL;
119     return func == NULL || *func == '\0' || strcmp(func, UNKNOWN_FUNC) == 0
120         ? fallback : func;
121 }
122
123 int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file,
124                           int line, OSSL_CMP_severity level, const char *msg)
125 {
126     const char *level_string =
127         level == OSSL_CMP_LOG_EMERG ? "EMERG" :
128         level == OSSL_CMP_LOG_ALERT ? "ALERT" :
129         level == OSSL_CMP_LOG_CRIT ? "CRIT" :
130         level == OSSL_CMP_LOG_ERR ? "error" :
131         level == OSSL_CMP_LOG_WARNING ? "warning" :
132         level == OSSL_CMP_LOG_NOTICE ? "NOTE" :
133         level == OSSL_CMP_LOG_INFO ? "info" :
134         level == OSSL_CMP_LOG_DEBUG ? "DEBUG" : "(unknown level)";
135
136 #ifndef NDEBUG
137     if (BIO_printf(bio, "%s:%s:%d:", improve_location_name(component, "CMP"),
138                    file, line) < 0)
139         return 0;
140 #endif
141     return BIO_printf(bio, OSSL_CMP_LOG_PREFIX"%s: %s\n",
142                       level_string, msg) >= 0;
143 }
144
145 /*
146  * auxiliary function for incrementally reporting texts via the error queue
147  */
148 static void put_error(int lib, const char *func, int reason,
149                       const char *file, int line)
150 {
151     ERR_new();
152     ERR_set_debug(file, line, func);
153     ERR_set_error(lib, reason, NULL /* no data here, so fmt is NULL */);
154 }
155
156 #define ERR_print_errors_cb_LIMIT 4096 /* size of char buf[] variable there */
157 #define TYPICAL_MAX_OUTPUT_BEFORE_DATA 100
158 #define MAX_DATA_LEN (ERR_print_errors_cb_LIMIT-TYPICAL_MAX_OUTPUT_BEFORE_DATA)
159 void ossl_cmp_add_error_txt(const char *separator, const char *txt)
160 {
161     const char *file = NULL;
162     int line;
163     const char *func = NULL;
164     const char *data = NULL;
165     int flags;
166     unsigned long err = ERR_peek_last_error();
167
168     if (separator == NULL)
169         separator = "";
170     if (err == 0)
171         put_error(ERR_LIB_CMP, NULL, 0, "", 0);
172
173     do {
174         size_t available_len, data_len;
175         const char *curr = txt, *next = txt;
176         char *tmp;
177
178         ERR_peek_last_error_all(&file, &line, &func, &data, &flags);
179         if ((flags & ERR_TXT_STRING) == 0) {
180             data = "";
181             separator = "";
182         }
183         data_len = strlen(data);
184
185         /* workaround for limit of ERR_print_errors_cb() */
186         if (data_len >= MAX_DATA_LEN
187                 || strlen(separator) >= (size_t)(MAX_DATA_LEN - data_len))
188             available_len = 0;
189         else
190             available_len = MAX_DATA_LEN - data_len - strlen(separator) - 1;
191         /* MAX_DATA_LEN > available_len >= 0 */
192
193         if (separator[0] == '\0') {
194             const size_t len_next = strlen(next);
195
196             if (len_next <= available_len) {
197                 next += len_next;
198                 curr = NULL; /* no need to split */
199             }
200             else {
201                 next += available_len;
202                 curr = next; /* will split at this point */
203             }
204         } else {
205             while (*next != '\0' && (size_t)(next - txt) <= available_len) {
206                 curr = next;
207                 next = strstr(curr, separator);
208                 if (next != NULL)
209                     next += strlen(separator);
210                 else
211                     next = curr + strlen(curr);
212             }
213             if ((size_t)(next - txt) <= available_len)
214                 curr = NULL; /* the above loop implies *next == '\0' */
215         }
216         if (curr != NULL) {
217             /* split error msg at curr since error data would get too long */
218             if (curr != txt) {
219                 tmp = OPENSSL_strndup(txt, curr - txt);
220                 if (tmp == NULL)
221                     return;
222                 ERR_add_error_data(2, separator, tmp);
223                 OPENSSL_free(tmp);
224             }
225             put_error(ERR_LIB_CMP, func, err, file, line);
226             txt = curr;
227         } else {
228             ERR_add_error_data(2, separator, txt);
229             txt = next; /* finished */
230         }
231     } while (*txt != '\0');
232 }
233
234 /* this is similar to ERR_print_errors_cb, but uses the CMP-specific cb type */
235 void OSSL_CMP_print_errors_cb(OSSL_cmp_log_cb_t log_fn)
236 {
237     unsigned long err;
238     char msg[ERR_print_errors_cb_LIMIT];
239     const char *file = NULL, *func = NULL, *data = NULL;
240     int line, flags;
241
242     while ((err = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) {
243         const char *component =
244             improve_location_name(func, ERR_lib_error_string(err));
245
246         if (!(flags & ERR_TXT_STRING))
247             data = NULL;
248         BIO_snprintf(msg, sizeof(msg), "%s%s%s", ERR_reason_error_string(err),
249                      data == NULL || *data == '\0' ? "" : " : ",
250                      data == NULL ? "" : data);
251         if (log_fn == NULL) {
252 #ifndef OPENSSL_NO_STDIO
253             BIO *bio = BIO_new_fp(stderr, BIO_NOCLOSE);
254
255             if (bio != NULL) {
256                 OSSL_CMP_print_to_bio(bio, component, file, line,
257                                       OSSL_CMP_LOG_ERR, msg);
258                 BIO_free(bio);
259             }
260 #else
261             /* CMPerr(0, CMP_R_NO_STDIO) makes no sense during error printing */
262 #endif
263         } else {
264             if (log_fn(component, file, line, OSSL_CMP_LOG_ERR, msg) <= 0)
265                 break; /* abort outputting the error report */
266         }
267     }
268 }
269
270 /*
271  * functions manipulating lists of certificates etc.
272  * these functions could be generally useful.
273  */
274
275 int ossl_cmp_sk_X509_add1_cert(STACK_OF(X509) *sk, X509 *cert,
276                                int no_dup, int prepend)
277 {
278     if (sk == NULL) {
279         CMPerr(0, CMP_R_NULL_ARGUMENT);
280         return 0;
281     }
282     if (no_dup) {
283         /*
284          * not using sk_X509_set_cmp_func() and sk_X509_find()
285          * because this re-orders the certs on the stack
286          */
287         int i;
288
289         for (i = 0; i < sk_X509_num(sk); i++) {
290             if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
291                 return 1;
292         }
293     }
294     if (!X509_up_ref(cert))
295         return 0;
296     if (!sk_X509_insert(sk, cert, prepend ? 0 : -1)) {
297         X509_free(cert);
298         return 0;
299     }
300     return 1;
301 }
302
303 int ossl_cmp_sk_X509_add1_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs,
304                                 int no_self_issued, int no_dups, int prepend)
305 /* compiler would allow 'const' for the list of certs, yet they are up-ref'ed */
306 {
307     int i;
308
309     if (sk == NULL) {
310         CMPerr(0, CMP_R_NULL_ARGUMENT);
311         return 0;
312     }
313     for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
314         X509 *cert = sk_X509_value(certs, i);
315
316         if (!no_self_issued || X509_check_issued(cert, cert) != X509_V_OK) {
317             if (!ossl_cmp_sk_X509_add1_cert(sk, cert, no_dups, prepend))
318                 return 0;
319         }
320     }
321     return 1;
322 }
323
324 int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs,
325                                    int only_self_issued)
326 {
327     int i;
328
329     if (store == NULL) {
330         CMPerr(0, CMP_R_NULL_ARGUMENT);
331         return 0;
332     }
333     if (certs == NULL)
334         return 1;
335     for (i = 0; i < sk_X509_num(certs); i++) {
336         X509 *cert = sk_X509_value(certs, i);
337
338         if (!only_self_issued || X509_check_issued(cert, cert) == X509_V_OK)
339             if (!X509_STORE_add_cert(store, cert)) /* ups cert ref counter */
340                 return 0;
341     }
342     return 1;
343 }
344
345 STACK_OF(X509) *ossl_cmp_X509_STORE_get1_certs(X509_STORE *store)
346 {
347     int i;
348     STACK_OF(X509) *sk;
349     STACK_OF(X509_OBJECT) *objs;
350
351     if (store == NULL) {
352         CMPerr(0, CMP_R_NULL_ARGUMENT);
353         return 0;
354     }
355     if ((sk = sk_X509_new_null()) == NULL)
356         return NULL;
357     objs = X509_STORE_get0_objects(store);
358     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
359         X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
360
361         if (cert != NULL) {
362             if (!sk_X509_push(sk, cert))
363                 goto err;
364             if (!X509_up_ref(cert)) {
365                 (void)sk_X509_pop(sk);
366                 goto err;
367             }
368         }
369     }
370     return sk;
371
372  err:
373     sk_X509_pop_free(sk, X509_free);
374     return NULL;
375 }
376
377 /*-
378  * Builds up the certificate chain of certs as high up as possible using
379  * the given list of certs containing all possible intermediate certificates and
380  * optionally the (possible) trust anchor(s). See also ssl_add_cert_chain().
381  *
382  * Intended use of this function is to find all the certificates above the trust
383  * anchor needed to verify an EE's own certificate.  Those are supposed to be
384  * included in the ExtraCerts field of every first sent message of a transaction
385  * when MSG_SIG_ALG is utilized.
386  *
387  * NOTE: This allocates a stack and increments the reference count of each cert,
388  * so when not needed any more the stack and all its elements should be freed.
389  * NOTE: in case there is more than one possibility for the chain,
390  * OpenSSL seems to take the first one, check X509_verify_cert() for details.
391  *
392  * returns a pointer to a stack of (up_ref'ed) X509 certificates containing:
393  *      - the EE certificate given in the function arguments (cert)
394  *      - all intermediate certificates up the chain toward the trust anchor
395  *        whereas the (self-signed) trust anchor is not included
396  * returns NULL on error
397  */
398 STACK_OF(X509) *ossl_cmp_build_cert_chain(STACK_OF(X509) *certs, X509 *cert)
399 {
400     STACK_OF(X509) *chain = NULL, *result = NULL;
401     X509_STORE *store = X509_STORE_new();
402     X509_STORE_CTX *csc = NULL;
403
404     if (certs == NULL || cert == NULL || store == NULL) {
405         CMPerr(0, CMP_R_NULL_ARGUMENT);
406         goto err;
407     }
408
409     csc = X509_STORE_CTX_new();
410     if (csc == NULL)
411         goto err;
412
413     if (!ossl_cmp_X509_STORE_add1_certs(store, certs, 0)
414             || !X509_STORE_CTX_init(csc, store, cert, NULL))
415         goto err;
416
417     (void)ERR_set_mark();
418     /*
419      * ignore return value as it would fail without trust anchor given in store
420      */
421     (void)X509_verify_cert(csc);
422
423     /* don't leave any new errors in the queue */
424     (void)ERR_pop_to_mark();
425
426     chain = X509_STORE_CTX_get0_chain(csc);
427
428     /* result list to store the up_ref'ed not self-issued certificates */
429     if ((result = sk_X509_new_null()) == NULL)
430         goto err;
431     if (!ossl_cmp_sk_X509_add1_certs(result, chain, 1 /* no self-issued */,
432                                      1 /* no duplicates */, 0)) {
433         sk_X509_free(result);
434         result = NULL;
435     }
436
437  err:
438     X509_STORE_free(store);
439     X509_STORE_CTX_free(csc);
440     return result;
441 }
442
443 int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt,
444                                     const ASN1_OCTET_STRING *src)
445 {
446     ASN1_OCTET_STRING *new;
447     if (tgt == NULL) {
448         CMPerr(0, CMP_R_NULL_ARGUMENT);
449         return 0;
450     }
451     if (*tgt == src) /* self-assignment */
452         return 1;
453
454     if (src != NULL) {
455         if ((new = ASN1_OCTET_STRING_dup(src)) == NULL)
456             return 0;
457     } else {
458         new = NULL;
459     }
460
461     ASN1_OCTET_STRING_free(*tgt);
462     *tgt = new;
463     return 1;
464 }
465
466 int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt,
467                                           const unsigned char *bytes, int len)
468 {
469     ASN1_OCTET_STRING *new = NULL;
470
471     if (tgt == NULL) {
472         CMPerr(0, CMP_R_NULL_ARGUMENT);
473         return 0;
474     }
475     if (bytes != NULL) {
476         if ((new = ASN1_OCTET_STRING_new()) == NULL
477                 || !(ASN1_OCTET_STRING_set(new, bytes, len))) {
478             ASN1_OCTET_STRING_free(new);
479             return 0;
480         }
481     }
482
483     ASN1_OCTET_STRING_free(*tgt);
484     *tgt = new;
485     return 1;
486 }