0390c23e66ce178db2596522ca0051bef8cd1184
[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, char **func, char **file, int *line)
73 {
74     const char *p_func = buf;
75     const char *p_file = buf == NULL ? NULL : strchr(buf, ':');
76     const char *p_level = buf;
77     const char *msg = buf;
78
79     *level = -1;
80     *func = NULL;
81     *file = NULL;
82     *line = 0;
83
84     if (p_file != NULL) {
85         const char *p_line = strchr(++p_file, ':');
86
87         if ((*level = parse_level(buf)) < 0 && p_line != NULL) {
88             /* check if buf contains location info and logging level */
89             char *p_level_tmp = (char *)p_level;
90             const long line_number = strtol(++p_line, &p_level_tmp, 10);
91
92             p_level = p_level_tmp;
93             if (p_level > p_line && *(p_level++) == ':') {
94                 if ((*level = parse_level(p_level)) >= 0) {
95                     *func = OPENSSL_strndup(p_func, p_file - 1 - p_func);
96                     *file = OPENSSL_strndup(p_file, p_line - 1 - p_file);
97                     /* no real problem if OPENSSL_strndup() returns NULL */
98                     *line = (int)line_number;
99                     msg = strchr(p_level, ':') + 1;
100                     if (*msg == ' ')
101                         msg++;
102                 }
103             }
104         }
105     }
106     return msg;
107 }
108
109
110 /*
111  * auxiliary function for incrementally reporting texts via the error queue
112  */
113 static void put_error(int lib, const char *func, int reason,
114                       const char *file, int line)
115 {
116     ERR_new();
117     ERR_set_debug(file, line, func);
118     ERR_set_error(lib, reason, NULL /* no data here, so fmt is NULL */);
119 }
120
121 #define ERR_print_errors_cb_LIMIT 4096 /* size of char buf[] variable there */
122 #define TYPICAL_MAX_OUTPUT_BEFORE_DATA 100
123 #define MAX_DATA_LEN (ERR_print_errors_cb_LIMIT-TYPICAL_MAX_OUTPUT_BEFORE_DATA)
124 void ossl_cmp_add_error_txt(const char *separator, const char *txt)
125 {
126     const char *file = NULL;
127     int line;
128     const char *func = NULL;
129     const char *data = NULL;
130     int flags;
131     unsigned long err = ERR_peek_last_error();
132
133     if (separator == NULL)
134         separator = "";
135     if (err == 0)
136         put_error(ERR_LIB_CMP, NULL, 0, "", 0);
137
138     do {
139         size_t available_len, data_len;
140         const char *curr = txt, *next = txt;
141         char *tmp;
142
143         ERR_peek_last_error_all(&file, &line, &func, &data, &flags);
144         if ((flags & ERR_TXT_STRING) == 0) {
145             data = "";
146             separator = "";
147         }
148         data_len = strlen(data);
149
150         /* workaround for limit of ERR_print_errors_cb() */
151         if (data_len >= MAX_DATA_LEN
152                 || strlen(separator) >= (size_t)(MAX_DATA_LEN - data_len))
153             available_len = 0;
154         else
155             available_len = MAX_DATA_LEN - data_len - strlen(separator) - 1;
156         /* MAX_DATA_LEN > available_len >= 0 */
157
158         if (separator[0] == '\0') {
159             const size_t len_next = strlen(next);
160
161             if (len_next <= available_len) {
162                 next += len_next;
163                 curr = NULL; /* no need to split */
164             }
165             else {
166                 next += available_len;
167                 curr = next; /* will split at this point */
168             }
169         } else {
170             while (*next != '\0' && (size_t)(next - txt) <= available_len) {
171                 curr = next;
172                 next = strstr(curr, separator);
173                 if (next != NULL)
174                     next += strlen(separator);
175                 else
176                     next = curr + strlen(curr);
177             }
178             if ((size_t)(next - txt) <= available_len)
179                 curr = NULL; /* the above loop implies *next == '\0' */
180         }
181         if (curr != NULL) {
182             /* split error msg at curr since error data would get too long */
183             if (curr != txt) {
184                 tmp = OPENSSL_strndup(txt, curr - txt);
185                 if (tmp == NULL)
186                     return;
187                 ERR_add_error_data(2, separator, tmp);
188                 OPENSSL_free(tmp);
189             }
190             put_error(ERR_LIB_CMP, func, err, file, line);
191             txt = curr;
192         } else {
193             ERR_add_error_data(2, separator, txt);
194             txt = next; /* finished */
195         }
196     } while (*txt != '\0');
197 }
198
199 /* this is similar to ERR_print_errors_cb, but uses the CMP-specific cb type */
200 void OSSL_CMP_print_errors_cb(OSSL_cmp_log_cb_t log_fn)
201 {
202     unsigned long err;
203     char msg[ERR_print_errors_cb_LIMIT];
204     const char *file = NULL, *func = NULL, *data = NULL;
205     int line, flags;
206
207     if (log_fn == NULL) {
208 #ifndef OPENSSL_NO_STDIO
209         ERR_print_errors_fp(stderr);
210 #else
211         /* CMPerr(0, CMP_R_NO_STDIO) makes no sense during error printing */
212 #endif
213         return;
214     }
215
216     while ((err = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) {
217         char component[128];
218         const char *func_ = func != NULL && *func != '\0' ? func : "<unknown>";
219
220         if (!(flags & ERR_TXT_STRING))
221             data = NULL;
222 #ifdef OSSL_CMP_PRINT_LIBINFO
223         BIO_snprintf(component, sizeof(component), "OpenSSL:%s:%s",
224                      ERR_lib_error_string(err), func_);
225 #else
226         BIO_snprintf(component, sizeof(component), "%s",func_);
227 #endif
228         BIO_snprintf(msg, sizeof(msg), "%s%s%s", ERR_reason_error_string(err),
229                      data == NULL ? "" : " : ", data == NULL ? "" : data);
230         if (log_fn(component, file, line, OSSL_CMP_LOG_ERR, msg) <= 0)
231             break;              /* abort outputting the error report */
232     }
233 }
234
235 /*
236  * functions manipulating lists of certificates etc.
237  * these functions could be generally useful.
238  */
239
240 int ossl_cmp_sk_X509_add1_cert(STACK_OF(X509) *sk, X509 *cert,
241                                int no_dup, int prepend)
242 {
243     if (sk == NULL) {
244         CMPerr(0, CMP_R_NULL_ARGUMENT);
245         return 0;
246     }
247     if (no_dup) {
248         /*
249          * not using sk_X509_set_cmp_func() and sk_X509_find()
250          * because this re-orders the certs on the stack
251          */
252         int i;
253
254         for (i = 0; i < sk_X509_num(sk); i++) {
255             if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
256                 return 1;
257         }
258     }
259     if (!X509_up_ref(cert))
260         return 0;
261     if (!sk_X509_insert(sk, cert, prepend ? 0 : -1)) {
262         X509_free(cert);
263         return 0;
264     }
265     return 1;
266 }
267
268 int ossl_cmp_sk_X509_add1_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs,
269                                 int no_self_signed, int no_dups, int prepend)
270 /* compiler would allow 'const' for the list of certs, yet they are up-ref'ed */
271 {
272     int i;
273
274     if (sk == NULL) {
275         CMPerr(0, CMP_R_NULL_ARGUMENT);
276         return 0;
277     }
278     for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
279         X509 *cert = sk_X509_value(certs, i);
280
281         if (!no_self_signed || X509_check_issued(cert, cert) != X509_V_OK) {
282             if (!ossl_cmp_sk_X509_add1_cert(sk, cert, no_dups, prepend))
283                 return 0;
284         }
285     }
286     return 1;
287 }
288
289 int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs,
290                                    int only_self_signed)
291 {
292     int i;
293
294     if (store == NULL) {
295         CMPerr(0, CMP_R_NULL_ARGUMENT);
296         return 0;
297     }
298     if (certs == NULL)
299         return 1;
300     for (i = 0; i < sk_X509_num(certs); i++) {
301         X509 *cert = sk_X509_value(certs, i);
302
303         if (!only_self_signed || X509_check_issued(cert, cert) == X509_V_OK)
304             if (!X509_STORE_add_cert(store, cert)) /* ups cert ref counter */
305                 return 0;
306     }
307     return 1;
308 }
309
310 STACK_OF(X509) *ossl_cmp_X509_STORE_get1_certs(X509_STORE *store)
311 {
312     int i;
313     STACK_OF(X509) *sk;
314     STACK_OF(X509_OBJECT) *objs;
315
316     if (store == NULL) {
317         CMPerr(0, CMP_R_NULL_ARGUMENT);
318         return 0;
319     }
320     if ((sk = sk_X509_new_null()) == NULL)
321         return NULL;
322     objs = X509_STORE_get0_objects(store);
323     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
324         X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
325
326         if (cert != NULL) {
327             if (!sk_X509_push(sk, cert))
328                 goto err;
329             if (!X509_up_ref(cert)) {
330                 (void)sk_X509_pop(sk);
331                 goto err;
332             }
333         }
334     }
335     return sk;
336
337  err:
338     sk_X509_pop_free(sk, X509_free);
339     return NULL;
340 }
341
342 /*-
343  * Builds up the certificate chain of certs as high up as possible using
344  * the given list of certs containing all possible intermediate certificates and
345  * optionally the (possible) trust anchor(s). See also ssl_add_cert_chain().
346  *
347  * Intended use of this function is to find all the certificates above the trust
348  * anchor needed to verify an EE's own certificate.  Those are supposed to be
349  * included in the ExtraCerts field of every first sent message of a transaction
350  * when MSG_SIG_ALG is utilized.
351  *
352  * NOTE: This allocates a stack and increments the reference count of each cert,
353  * so when not needed any more the stack and all its elements should be freed.
354  * NOTE: in case there is more than one possibility for the chain,
355  * OpenSSL seems to take the first one, check X509_verify_cert() for details.
356  *
357  * returns a pointer to a stack of (up_ref'ed) X509 certificates containing:
358  *      - the EE certificate given in the function arguments (cert)
359  *      - all intermediate certificates up the chain toward the trust anchor
360  *        whereas the (self-signed) trust anchor is not included
361  * returns NULL on error
362  */
363 STACK_OF(X509) *ossl_cmp_build_cert_chain(STACK_OF(X509) *certs, X509 *cert)
364 {
365     STACK_OF(X509) *chain = NULL, *result = NULL;
366     X509_STORE *store = X509_STORE_new();
367     X509_STORE_CTX *csc = NULL;
368
369     if (certs == NULL || cert == NULL || store == NULL) {
370         CMPerr(0, CMP_R_NULL_ARGUMENT);
371         goto err;
372     }
373
374     csc = X509_STORE_CTX_new();
375     if (csc == NULL)
376         goto err;
377
378     if (!ossl_cmp_X509_STORE_add1_certs(store, certs, 0)
379             || !X509_STORE_CTX_init(csc, store, cert, NULL))
380         goto err;
381
382     (void)ERR_set_mark();
383     /*
384      * ignore return value as it would fail without trust anchor given in store
385      */
386     (void)X509_verify_cert(csc);
387
388     /* don't leave any new errors in the queue */
389     (void)ERR_pop_to_mark();
390
391     chain = X509_STORE_CTX_get0_chain(csc);
392
393     /* result list to store the up_ref'ed not self-signed certificates */
394     if ((result = sk_X509_new_null()) == NULL)
395         goto err;
396     if (!ossl_cmp_sk_X509_add1_certs(result, chain, 1 /* no self-signed */,
397                                      1 /* no duplicates */, 0)) {
398         sk_X509_free(result);
399         result = NULL;
400     }
401
402  err:
403     X509_STORE_free(store);
404     X509_STORE_CTX_free(csc);
405     return result;
406 }
407
408 int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt,
409                                     const ASN1_OCTET_STRING *src)
410 {
411     ASN1_OCTET_STRING *new;
412     if (tgt == NULL) {
413         CMPerr(0, CMP_R_NULL_ARGUMENT);
414         return 0;
415     }
416     if (*tgt == src) /* self-assignment */
417         return 1;
418
419     if (src != NULL) {
420         if ((new = ASN1_OCTET_STRING_dup(src)) == NULL)
421             return 0;
422     } else {
423         new = NULL;
424     }
425
426     ASN1_OCTET_STRING_free(*tgt);
427     *tgt = new;
428     return 1;
429 }
430
431 int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt,
432                                           const unsigned char *bytes, int len)
433 {
434     ASN1_OCTET_STRING *new = NULL;
435
436     if (tgt == NULL) {
437         CMPerr(0, CMP_R_NULL_ARGUMENT);
438         return 0;
439     }
440     if (bytes != NULL) {
441         if ((new =  ASN1_OCTET_STRING_new()) == NULL
442                 || !(ASN1_OCTET_STRING_set(new, bytes, len))) {
443             ASN1_OCTET_STRING_free(new);
444             return 0;
445         }
446     }
447
448     ASN1_OCTET_STRING_free(*tgt);
449     *tgt = new;
450     return 1;
451 }