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