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