b2c71db4818eb17ef250af72f52cd89856172138
[openssl.git] / crypto / property / property.c
1 /*
2  * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <string.h>
12 #include <stdio.h>
13 #include <stdarg.h>
14 #include <openssl/crypto.h>
15 #include "internal/core.h"
16 #include "internal/property.h"
17 #include "internal/provider.h"
18 #include "crypto/ctype.h"
19 #include <openssl/lhash.h>
20 #include <openssl/rand.h>
21 #include "internal/thread_once.h"
22 #include "crypto/lhash.h"
23 #include "crypto/sparse_array.h"
24 #include "property_local.h"
25 #include "crypto/context.h"
26
27 /*
28  * The number of elements in the query cache before we initiate a flush.
29  * If reducing this, also ensure the stochastic test in test/property_test.c
30  * isn't likely to fail.
31  */
32 #define IMPL_CACHE_FLUSH_THRESHOLD  500
33
34 typedef struct {
35     void *method;
36     int (*up_ref)(void *);
37     void (*free)(void *);
38 } METHOD;
39
40 typedef struct {
41     const OSSL_PROVIDER *provider;
42     OSSL_PROPERTY_LIST *properties;
43     METHOD method;
44 } IMPLEMENTATION;
45
46 DEFINE_STACK_OF(IMPLEMENTATION)
47
48 typedef struct {
49     const OSSL_PROVIDER *provider;
50     const char *query;
51     METHOD method;
52     char body[1];
53 } QUERY;
54
55 DEFINE_LHASH_OF(QUERY);
56
57 typedef struct {
58     int nid;
59     STACK_OF(IMPLEMENTATION) *impls;
60     LHASH_OF(QUERY) *cache;
61 } ALGORITHM;
62
63 struct ossl_method_store_st {
64     OSSL_LIB_CTX *ctx;
65     SPARSE_ARRAY_OF(ALGORITHM) *algs;
66     CRYPTO_RWLOCK *lock;
67
68     /* query cache specific values */
69
70     /* Count of the query cache entries for all algs */
71     size_t cache_nelem;
72
73     /* Flag: 1 if query cache entries for all algs need flushing */
74     int cache_need_flush;
75 };
76
77 typedef struct {
78     LHASH_OF(QUERY) *cache;
79     size_t nelem;
80     uint32_t seed;
81 } IMPL_CACHE_FLUSH;
82
83 DEFINE_SPARSE_ARRAY_OF(ALGORITHM);
84
85 typedef struct ossl_global_properties_st {
86     OSSL_PROPERTY_LIST *list;
87 #ifndef FIPS_MODULE
88     unsigned int no_mirrored : 1;
89 #endif
90 } OSSL_GLOBAL_PROPERTIES;
91
92 static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid);
93
94 /* Global properties are stored per library context */
95 void ossl_ctx_global_properties_free(void *vglobp)
96 {
97     OSSL_GLOBAL_PROPERTIES *globp = vglobp;
98
99     if (globp != NULL) {
100         ossl_property_free(globp->list);
101         OPENSSL_free(globp);
102     }
103 }
104
105 void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *ctx)
106 {
107     return OPENSSL_zalloc(sizeof(OSSL_GLOBAL_PROPERTIES));
108 }
109
110 OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *libctx,
111                                                 int loadconfig)
112 {
113     OSSL_GLOBAL_PROPERTIES *globp;
114
115 #ifndef FIPS_MODULE
116     if (loadconfig && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
117         return NULL;
118 #endif
119     globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
120
121     return globp != NULL ? &globp->list : NULL;
122 }
123
124 #ifndef FIPS_MODULE
125 int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx)
126 {
127     OSSL_GLOBAL_PROPERTIES *globp
128         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
129
130     return globp != NULL && globp->no_mirrored ? 1 : 0;
131 }
132
133 void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx)
134 {
135     OSSL_GLOBAL_PROPERTIES *globp
136         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
137
138     if (globp != NULL)
139         globp->no_mirrored = 1;
140 }
141 #endif
142
143 static int ossl_method_up_ref(METHOD *method)
144 {
145     return (*method->up_ref)(method->method);
146 }
147
148 static void ossl_method_free(METHOD *method)
149 {
150     (*method->free)(method->method);
151 }
152
153 static __owur int ossl_property_read_lock(OSSL_METHOD_STORE *p)
154 {
155     return p != NULL ? CRYPTO_THREAD_read_lock(p->lock) : 0;
156 }
157
158 static __owur int ossl_property_write_lock(OSSL_METHOD_STORE *p)
159 {
160     return p != NULL ? CRYPTO_THREAD_write_lock(p->lock) : 0;
161 }
162
163 static int ossl_property_unlock(OSSL_METHOD_STORE *p)
164 {
165     return p != 0 ? CRYPTO_THREAD_unlock(p->lock) : 0;
166 }
167
168 static unsigned long query_hash(const QUERY *a)
169 {
170     return OPENSSL_LH_strhash(a->query);
171 }
172
173 static int query_cmp(const QUERY *a, const QUERY *b)
174 {
175     int res = strcmp(a->query, b->query);
176
177     if (res == 0 && a->provider != NULL && b->provider != NULL)
178         res = b->provider > a->provider ? 1
179             : b->provider < a->provider ? -1
180             : 0;
181     return res;
182 }
183
184 static void impl_free(IMPLEMENTATION *impl)
185 {
186     if (impl != NULL) {
187         ossl_method_free(&impl->method);
188         OPENSSL_free(impl);
189     }
190 }
191
192 static void impl_cache_free(QUERY *elem)
193 {
194     if (elem != NULL) {
195         ossl_method_free(&elem->method);
196         OPENSSL_free(elem);
197     }
198 }
199
200 static void alg_cleanup(ossl_uintmax_t idx, ALGORITHM *a)
201 {
202     if (a != NULL) {
203         sk_IMPLEMENTATION_pop_free(a->impls, &impl_free);
204         lh_QUERY_doall(a->cache, &impl_cache_free);
205         lh_QUERY_free(a->cache);
206         OPENSSL_free(a);
207     }
208 }
209
210 /*
211  * The OSSL_LIB_CTX param here allows access to underlying property data needed
212  * for computation
213  */
214 OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx)
215 {
216     OSSL_METHOD_STORE *res;
217
218     res = OPENSSL_zalloc(sizeof(*res));
219     if (res != NULL) {
220         res->ctx = ctx;
221         if ((res->algs = ossl_sa_ALGORITHM_new()) == NULL) {
222             OPENSSL_free(res);
223             return NULL;
224         }
225         if ((res->lock = CRYPTO_THREAD_lock_new()) == NULL) {
226             ossl_sa_ALGORITHM_free(res->algs);
227             OPENSSL_free(res);
228             return NULL;
229         }
230     }
231     return res;
232 }
233
234 void ossl_method_store_free(OSSL_METHOD_STORE *store)
235 {
236     if (store != NULL) {
237         ossl_sa_ALGORITHM_doall(store->algs, &alg_cleanup);
238         ossl_sa_ALGORITHM_free(store->algs);
239         CRYPTO_THREAD_lock_free(store->lock);
240         OPENSSL_free(store);
241     }
242 }
243
244 static ALGORITHM *ossl_method_store_retrieve(OSSL_METHOD_STORE *store, int nid)
245 {
246     return ossl_sa_ALGORITHM_get(store->algs, nid);
247 }
248
249 static int ossl_method_store_insert(OSSL_METHOD_STORE *store, ALGORITHM *alg)
250 {
251         return ossl_sa_ALGORITHM_set(store->algs, alg->nid, alg);
252 }
253
254 int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov,
255                           int nid, const char *properties, void *method,
256                           int (*method_up_ref)(void *),
257                           void (*method_destruct)(void *))
258 {
259     ALGORITHM *alg = NULL;
260     IMPLEMENTATION *impl;
261     int ret = 0;
262     int i;
263
264     if (nid <= 0 || method == NULL || store == NULL)
265         return 0;
266     if (properties == NULL)
267         properties = "";
268
269     if (!ossl_assert(prov != NULL))
270         return 0;
271
272     /* Create new entry */
273     impl = OPENSSL_malloc(sizeof(*impl));
274     if (impl == NULL)
275         return 0;
276     impl->method.method = method;
277     impl->method.up_ref = method_up_ref;
278     impl->method.free = method_destruct;
279     if (!ossl_method_up_ref(&impl->method)) {
280         OPENSSL_free(impl);
281         return 0;
282     }
283     impl->provider = prov;
284
285     /* Insert into the hash table if required */
286     if (!ossl_property_write_lock(store)) {
287         OPENSSL_free(impl);
288         return 0;
289     }
290     ossl_method_cache_flush(store, nid);
291     if ((impl->properties = ossl_prop_defn_get(store->ctx, properties)) == NULL) {
292         impl->properties = ossl_parse_property(store->ctx, properties);
293         if (impl->properties == NULL)
294             goto err;
295         ossl_prop_defn_set(store->ctx, properties, impl->properties);
296     }
297
298     alg = ossl_method_store_retrieve(store, nid);
299     if (alg == NULL) {
300         if ((alg = OPENSSL_zalloc(sizeof(*alg))) == NULL
301                 || (alg->impls = sk_IMPLEMENTATION_new_null()) == NULL
302                 || (alg->cache = lh_QUERY_new(&query_hash, &query_cmp)) == NULL)
303             goto err;
304         alg->nid = nid;
305         if (!ossl_method_store_insert(store, alg))
306             goto err;
307     }
308
309     /* Push onto stack if there isn't one there already */
310     for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
311         const IMPLEMENTATION *tmpimpl = sk_IMPLEMENTATION_value(alg->impls, i);
312
313         if (tmpimpl->provider == impl->provider
314             && tmpimpl->properties == impl->properties)
315             break;
316     }
317     if (i == sk_IMPLEMENTATION_num(alg->impls)
318         && sk_IMPLEMENTATION_push(alg->impls, impl))
319         ret = 1;
320     ossl_property_unlock(store);
321     if (ret == 0)
322         impl_free(impl);
323     return ret;
324
325 err:
326     ossl_property_unlock(store);
327     alg_cleanup(0, alg);
328     impl_free(impl);
329     return 0;
330 }
331
332 int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid,
333                              const void *method)
334 {
335     ALGORITHM *alg = NULL;
336     int i;
337
338     if (nid <= 0 || method == NULL || store == NULL)
339         return 0;
340
341     if (!ossl_property_write_lock(store))
342         return 0;
343     ossl_method_cache_flush(store, nid);
344     alg = ossl_method_store_retrieve(store, nid);
345     if (alg == NULL) {
346         ossl_property_unlock(store);
347         return 0;
348     }
349
350     /*
351      * A sorting find then a delete could be faster but these stacks should be
352      * relatively small, so we avoid the overhead.  Sorting could also surprise
353      * users when result orderings change (even though they are not guaranteed).
354      */
355     for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
356         IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
357
358         if (impl->method.method == method) {
359             impl_free(impl);
360             (void)sk_IMPLEMENTATION_delete(alg->impls, i);
361             ossl_property_unlock(store);
362             return 1;
363         }
364     }
365     ossl_property_unlock(store);
366     return 0;
367 }
368
369 static void alg_do_one(ALGORITHM *alg, IMPLEMENTATION *impl,
370                        void (*fn)(int id, void *method, void *fnarg),
371                        void *fnarg)
372 {
373     fn(alg->nid, impl->method.method, fnarg);
374 }
375
376 struct alg_do_each_data_st {
377     void (*fn)(int id, void *method, void *fnarg);
378     void *fnarg;
379 };
380
381 static void alg_do_each(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
382 {
383     struct alg_do_each_data_st *data = arg;
384     int i, end = sk_IMPLEMENTATION_num(alg->impls);
385
386     for (i = 0; i < end; i++) {
387         IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
388
389         alg_do_one(alg, impl, data->fn, data->fnarg);
390     }
391 }
392
393 void ossl_method_store_do_all(OSSL_METHOD_STORE *store,
394                               void (*fn)(int id, void *method, void *fnarg),
395                               void *fnarg)
396 {
397     struct alg_do_each_data_st data;
398
399     data.fn = fn;
400     data.fnarg = fnarg;
401     if (store != NULL)
402         ossl_sa_ALGORITHM_doall_arg(store->algs, alg_do_each, &data);
403 }
404
405 int ossl_method_store_fetch(OSSL_METHOD_STORE *store,
406                             int nid, const char *prop_query,
407                             const OSSL_PROVIDER **prov_rw, void **method)
408 {
409     OSSL_PROPERTY_LIST **plp;
410     ALGORITHM *alg;
411     IMPLEMENTATION *impl, *best_impl = NULL;
412     OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
413     const OSSL_PROVIDER *prov = prov_rw != NULL ? *prov_rw : NULL;
414     int ret = 0;
415     int j, best = -1, score, optional;
416
417 #ifndef FIPS_MODULE
418     if (!OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
419         return 0;
420 #endif
421
422     if (nid <= 0 || method == NULL || store == NULL)
423         return 0;
424
425     /* This only needs to be a read lock, because the query won't create anything */
426     if (!ossl_property_read_lock(store))
427         return 0;
428     alg = ossl_method_store_retrieve(store, nid);
429     if (alg == NULL) {
430         ossl_property_unlock(store);
431         return 0;
432     }
433
434     if (prop_query != NULL)
435         p2 = pq = ossl_parse_query(store->ctx, prop_query, 0);
436     plp = ossl_ctx_global_properties(store->ctx, 0);
437     if (plp != NULL && *plp != NULL) {
438         if (pq == NULL) {
439             pq = *plp;
440         } else {
441             p2 = ossl_property_merge(pq, *plp);
442             ossl_property_free(pq);
443             if (p2 == NULL)
444                 goto fin;
445             pq = p2;
446         }
447     }
448
449     if (pq == NULL) {
450         for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
451             if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
452                 && (prov == NULL || impl->provider == prov)) {
453                 best_impl = impl;
454                 ret = 1;
455                 break;
456             }
457         }
458         goto fin;
459     }
460     optional = ossl_property_has_optional(pq);
461     for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
462         if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
463             && (prov == NULL || impl->provider == prov)) {
464             score = ossl_property_match_count(pq, impl->properties);
465             if (score > best) {
466                 best_impl = impl;
467                 best = score;
468                 ret = 1;
469                 if (!optional)
470                     goto fin;
471             }
472         }
473     }
474 fin:
475     if (ret && ossl_method_up_ref(&best_impl->method)) {
476         *method = best_impl->method.method;
477         if (prov_rw != NULL)
478             *prov_rw = best_impl->provider;
479     } else {
480         ret = 0;
481     }
482     ossl_property_unlock(store);
483     ossl_property_free(p2);
484     return ret;
485 }
486
487 static void impl_cache_flush_alg(ossl_uintmax_t idx, ALGORITHM *alg)
488 {
489     lh_QUERY_doall(alg->cache, &impl_cache_free);
490     lh_QUERY_flush(alg->cache);
491 }
492
493 static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid)
494 {
495     ALGORITHM *alg = ossl_method_store_retrieve(store, nid);
496
497     if (alg != NULL) {
498         store->cache_nelem -= lh_QUERY_num_items(alg->cache);
499         impl_cache_flush_alg(0, alg);
500     }
501 }
502
503 int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store)
504 {
505     if (!ossl_property_write_lock(store))
506         return 0;
507     ossl_sa_ALGORITHM_doall(store->algs, &impl_cache_flush_alg);
508     store->cache_nelem = 0;
509     ossl_property_unlock(store);
510     return 1;
511 }
512
513 IMPLEMENT_LHASH_DOALL_ARG(QUERY, IMPL_CACHE_FLUSH);
514
515 /*
516  * Flush an element from the query cache (perhaps).
517  *
518  * In order to avoid taking a write lock or using atomic operations
519  * to keep accurate least recently used (LRU) or least frequently used
520  * (LFU) information, the procedure used here is to stochastically
521  * flush approximately half the cache.
522  *
523  * This procedure isn't ideal, LRU or LFU would be better.  However,
524  * in normal operation, reaching a full cache would be unexpected.
525  * It means that no steady state of algorithm queries has been reached.
526  * That is, it is most likely an attack of some form.  A suboptimal clearance
527  * strategy that doesn't degrade performance of the normal case is
528  * preferable to a more refined approach that imposes a performance
529  * impact.
530  */
531 static void impl_cache_flush_cache(QUERY *c, IMPL_CACHE_FLUSH *state)
532 {
533     uint32_t n;
534
535     /*
536      * Implement the 32 bit xorshift as suggested by George Marsaglia in:
537      *      https://doi.org/10.18637/jss.v008.i14
538      *
539      * This is a very fast PRNG so there is no need to extract bits one at a
540      * time and use the entire value each time.
541      */
542     n = state->seed;
543     n ^= n << 13;
544     n ^= n >> 17;
545     n ^= n << 5;
546     state->seed = n;
547
548     if ((n & 1) != 0)
549         impl_cache_free(lh_QUERY_delete(state->cache, c));
550     else
551         state->nelem++;
552 }
553
554 static void impl_cache_flush_one_alg(ossl_uintmax_t idx, ALGORITHM *alg,
555                                      void *v)
556 {
557     IMPL_CACHE_FLUSH *state = (IMPL_CACHE_FLUSH *)v;
558
559     state->cache = alg->cache;
560     lh_QUERY_doall_IMPL_CACHE_FLUSH(state->cache, &impl_cache_flush_cache,
561                                     state);
562 }
563
564 static void ossl_method_cache_flush_some(OSSL_METHOD_STORE *store)
565 {
566     IMPL_CACHE_FLUSH state;
567
568     state.nelem = 0;
569     if ((state.seed = OPENSSL_rdtsc()) == 0)
570         state.seed = 1;
571     store->cache_need_flush = 0;
572     ossl_sa_ALGORITHM_doall_arg(store->algs, &impl_cache_flush_one_alg, &state);
573     store->cache_nelem = state.nelem;
574 }
575
576 int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
577                                 int nid, const char *prop_query, void **method)
578 {
579     ALGORITHM *alg;
580     QUERY elem, *r;
581     int res = 0;
582
583     if (nid <= 0 || store == NULL || prop_query == NULL)
584         return 0;
585
586     if (!ossl_property_read_lock(store))
587         return 0;
588     alg = ossl_method_store_retrieve(store, nid);
589     if (alg == NULL)
590         goto err;
591
592     elem.query = prop_query;
593     elem.provider = prov;
594     r = lh_QUERY_retrieve(alg->cache, &elem);
595     if (r == NULL)
596         goto err;
597     if (ossl_method_up_ref(&r->method)) {
598         *method = r->method.method;
599         res = 1;
600     }
601 err:
602     ossl_property_unlock(store);
603     return res;
604 }
605
606 int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
607                                 int nid, const char *prop_query, void *method,
608                                 int (*method_up_ref)(void *),
609                                 void (*method_destruct)(void *))
610 {
611     QUERY elem, *old, *p = NULL;
612     ALGORITHM *alg;
613     size_t len;
614     int res = 1;
615
616     if (nid <= 0 || store == NULL || prop_query == NULL)
617         return 0;
618
619     if (!ossl_assert(prov != NULL))
620         return 0;
621
622     if (!ossl_property_write_lock(store))
623         return 0;
624     if (store->cache_need_flush)
625         ossl_method_cache_flush_some(store);
626     alg = ossl_method_store_retrieve(store, nid);
627     if (alg == NULL)
628         goto err;
629
630     if (method == NULL) {
631         elem.query = prop_query;
632         elem.provider = prov;
633         if ((old = lh_QUERY_delete(alg->cache, &elem)) != NULL) {
634             impl_cache_free(old);
635             store->cache_nelem--;
636         }
637         goto end;
638     }
639     p = OPENSSL_malloc(sizeof(*p) + (len = strlen(prop_query)));
640     if (p != NULL) {
641         p->query = p->body;
642         p->provider = prov;
643         p->method.method = method;
644         p->method.up_ref = method_up_ref;
645         p->method.free = method_destruct;
646         if (!ossl_method_up_ref(&p->method))
647             goto err;
648         memcpy((char *)p->query, prop_query, len + 1);
649         if ((old = lh_QUERY_insert(alg->cache, p)) != NULL) {
650             impl_cache_free(old);
651             goto end;
652         }
653         if (!lh_QUERY_error(alg->cache)) {
654             if (++store->cache_nelem >= IMPL_CACHE_FLUSH_THRESHOLD)
655                 store->cache_need_flush = 1;
656             goto end;
657         }
658         ossl_method_free(&p->method);
659     }
660 err:
661     res = 0;
662     OPENSSL_free(p);
663 end:
664     ossl_property_unlock(store);
665     return res;
666 }