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