Coverage Report

Created: 2025-06-13 06:56

/src/openssl/crypto/property/property.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2019-2025 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 <openssl/trace.h>
23
#include "internal/thread_once.h"
24
#include "crypto/lhash.h"
25
#include "crypto/sparse_array.h"
26
#include "property_local.h"
27
#include "crypto/context.h"
28
29
/*
30
 * The number of elements in the query cache before we initiate a flush.
31
 * If reducing this, also ensure the stochastic test in test/property_test.c
32
 * isn't likely to fail.
33
 */
34
0
#define IMPL_CACHE_FLUSH_THRESHOLD  500
35
36
typedef struct {
37
    void *method;
38
    int (*up_ref)(void *);
39
    void (*free)(void *);
40
} METHOD;
41
42
typedef struct {
43
    const OSSL_PROVIDER *provider;
44
    OSSL_PROPERTY_LIST *properties;
45
    METHOD method;
46
} IMPLEMENTATION;
47
48
DEFINE_STACK_OF(IMPLEMENTATION)
49
50
typedef struct {
51
    const OSSL_PROVIDER *provider;
52
    const char *query;
53
    METHOD method;
54
    char body[1];
55
} QUERY;
56
57
DEFINE_LHASH_OF_EX(QUERY);
58
59
typedef struct {
60
    int nid;
61
    STACK_OF(IMPLEMENTATION) *impls;
62
    LHASH_OF(QUERY) *cache;
63
} ALGORITHM;
64
65
struct ossl_method_store_st {
66
    OSSL_LIB_CTX *ctx;
67
    SPARSE_ARRAY_OF(ALGORITHM) *algs;
68
    /*
69
     * Lock to protect the |algs| array from concurrent writing, when
70
     * individual implementations or queries are inserted.  This is used
71
     * by the appropriate functions here.
72
     */
73
    CRYPTO_RWLOCK *lock;
74
    /*
75
     * Lock to reserve the whole store.  This is used when fetching a set
76
     * of algorithms, via these functions, found in crypto/core_fetch.c:
77
     * ossl_method_construct_reserve_store()
78
     * ossl_method_construct_unreserve_store()
79
     */
80
    CRYPTO_RWLOCK *biglock;
81
82
    /* query cache specific values */
83
84
    /* Count of the query cache entries for all algs */
85
    size_t cache_nelem;
86
87
    /* Flag: 1 if query cache entries for all algs need flushing */
88
    int cache_need_flush;
89
};
90
91
typedef struct {
92
    LHASH_OF(QUERY) *cache;
93
    size_t nelem;
94
    uint32_t seed;
95
    unsigned char using_global_seed;
96
} IMPL_CACHE_FLUSH;
97
98
DEFINE_SPARSE_ARRAY_OF(ALGORITHM);
99
100
DEFINE_STACK_OF(ALGORITHM)
101
102
typedef struct ossl_global_properties_st {
103
    OSSL_PROPERTY_LIST *list;
104
#ifndef FIPS_MODULE
105
    unsigned int no_mirrored : 1;
106
#endif
107
} OSSL_GLOBAL_PROPERTIES;
108
109
static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store,
110
                                        ALGORITHM *alg);
111
static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid);
112
113
/* Global properties are stored per library context */
114
void ossl_ctx_global_properties_free(void *vglobp)
115
2
{
116
2
    OSSL_GLOBAL_PROPERTIES *globp = vglobp;
117
118
2
    if (globp != NULL) {
119
2
        ossl_property_free(globp->list);
120
2
        OPENSSL_free(globp);
121
2
    }
122
2
}
123
124
void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *ctx)
125
2
{
126
2
    return OPENSSL_zalloc(sizeof(OSSL_GLOBAL_PROPERTIES));
127
2
}
128
129
OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *libctx,
130
                                                ossl_unused int loadconfig)
131
0
{
132
0
    OSSL_GLOBAL_PROPERTIES *globp;
133
134
0
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
135
0
    if (loadconfig && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
136
0
        return NULL;
137
0
#endif
138
0
    globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
139
140
0
    return globp != NULL ? &globp->list : NULL;
141
0
}
142
143
#ifndef FIPS_MODULE
144
int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx)
145
0
{
146
0
    OSSL_GLOBAL_PROPERTIES *globp
147
0
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
148
149
0
    return globp != NULL && globp->no_mirrored ? 1 : 0;
150
0
}
151
152
void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx)
153
0
{
154
0
    OSSL_GLOBAL_PROPERTIES *globp
155
0
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES);
156
157
0
    if (globp != NULL)
158
0
        globp->no_mirrored = 1;
159
0
}
160
#endif
161
162
static int ossl_method_up_ref(METHOD *method)
163
0
{
164
0
    return (*method->up_ref)(method->method);
165
0
}
166
167
static void ossl_method_free(METHOD *method)
168
0
{
169
0
    (*method->free)(method->method);
170
0
}
171
172
static __owur int ossl_property_read_lock(OSSL_METHOD_STORE *p)
173
0
{
174
0
    return p != NULL ? CRYPTO_THREAD_read_lock(p->lock) : 0;
175
0
}
176
177
static __owur int ossl_property_write_lock(OSSL_METHOD_STORE *p)
178
0
{
179
0
    return p != NULL ? CRYPTO_THREAD_write_lock(p->lock) : 0;
180
0
}
181
182
static int ossl_property_unlock(OSSL_METHOD_STORE *p)
183
0
{
184
0
    return p != 0 ? CRYPTO_THREAD_unlock(p->lock) : 0;
185
0
}
186
187
static unsigned long query_hash(const QUERY *a)
188
0
{
189
0
    return OPENSSL_LH_strhash(a->query);
190
0
}
191
192
static int query_cmp(const QUERY *a, const QUERY *b)
193
0
{
194
0
    int res = strcmp(a->query, b->query);
195
196
0
    if (res == 0 && a->provider != NULL && b->provider != NULL)
197
0
        res = b->provider > a->provider ? 1
198
0
            : b->provider < a->provider ? -1
199
0
            : 0;
200
0
    return res;
201
0
}
202
203
static void impl_free(IMPLEMENTATION *impl)
204
0
{
205
0
    if (impl != NULL) {
206
0
        ossl_method_free(&impl->method);
207
0
        OPENSSL_free(impl);
208
0
    }
209
0
}
210
211
static void impl_cache_free(QUERY *elem)
212
0
{
213
0
    if (elem != NULL) {
214
0
        ossl_method_free(&elem->method);
215
0
        OPENSSL_free(elem);
216
0
    }
217
0
}
218
219
static void impl_cache_flush_alg(ossl_uintmax_t idx, ALGORITHM *alg)
220
0
{
221
0
    lh_QUERY_doall(alg->cache, &impl_cache_free);
222
0
    lh_QUERY_flush(alg->cache);
223
0
}
224
225
static void alg_cleanup(ossl_uintmax_t idx, ALGORITHM *a, void *arg)
226
0
{
227
0
    OSSL_METHOD_STORE *store = arg;
228
229
0
    if (a != NULL) {
230
0
        sk_IMPLEMENTATION_pop_free(a->impls, &impl_free);
231
0
        lh_QUERY_doall(a->cache, &impl_cache_free);
232
0
        lh_QUERY_free(a->cache);
233
0
        OPENSSL_free(a);
234
0
    }
235
0
    if (store != NULL)
236
0
        ossl_sa_ALGORITHM_set(store->algs, idx, NULL);
237
0
}
238
239
/*
240
 * The OSSL_LIB_CTX param here allows access to underlying property data needed
241
 * for computation
242
 */
243
OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx)
244
8
{
245
8
    OSSL_METHOD_STORE *res;
246
247
8
    res = OPENSSL_zalloc(sizeof(*res));
248
8
    if (res != NULL) {
249
8
        res->ctx = ctx;
250
8
        if ((res->algs = ossl_sa_ALGORITHM_new()) == NULL
251
8
            || (res->lock = CRYPTO_THREAD_lock_new()) == NULL
252
8
            || (res->biglock = CRYPTO_THREAD_lock_new()) == NULL) {
253
0
            ossl_method_store_free(res);
254
0
            return NULL;
255
0
        }
256
8
    }
257
8
    return res;
258
8
}
259
260
void ossl_method_store_free(OSSL_METHOD_STORE *store)
261
8
{
262
8
    if (store != NULL) {
263
8
        if (store->algs != NULL)
264
8
            ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup, store);
265
8
        ossl_sa_ALGORITHM_free(store->algs);
266
8
        CRYPTO_THREAD_lock_free(store->lock);
267
8
        CRYPTO_THREAD_lock_free(store->biglock);
268
8
        OPENSSL_free(store);
269
8
    }
270
8
}
271
272
int ossl_method_lock_store(OSSL_METHOD_STORE *store)
273
0
{
274
0
    return store != NULL ? CRYPTO_THREAD_write_lock(store->biglock) : 0;
275
0
}
276
277
int ossl_method_unlock_store(OSSL_METHOD_STORE *store)
278
0
{
279
0
    return store != NULL ? CRYPTO_THREAD_unlock(store->biglock) : 0;
280
0
}
281
282
static ALGORITHM *ossl_method_store_retrieve(OSSL_METHOD_STORE *store, int nid)
283
0
{
284
0
    return ossl_sa_ALGORITHM_get(store->algs, nid);
285
0
}
286
287
static int ossl_method_store_insert(OSSL_METHOD_STORE *store, ALGORITHM *alg)
288
0
{
289
0
    return ossl_sa_ALGORITHM_set(store->algs, alg->nid, alg);
290
0
}
291
292
/**
293
 * @brief Adds a method to the specified method store.
294
 *
295
 * This function adds a new method to the provided method store, associating it
296
 * with a specified id, properties, and provider. The method is stored with
297
 * reference count and destruction callbacks.
298
 *
299
 * @param store Pointer to the OSSL_METHOD_STORE where the method will be added.
300
 *              Must be non-null.
301
 * @param prov Pointer to the OSSL_PROVIDER for the provider of the method.
302
 *             Must be non-null.
303
 * @param nid (identifier) associated with the method, must be > 0
304
 * @param properties String containing properties of the method.
305
 * @param method Pointer to the method to be added.
306
 * @param method_up_ref Function pointer for incrementing the method ref count.
307
 * @param method_destruct Function pointer for destroying the method.
308
 *
309
 * @return 1 if the method is successfully added, 0 on failure.
310
 *
311
 * If tracing is enabled, a message is printed indicating that the method is
312
 * being added to the method store.
313
 *
314
 * NOTE: The nid parameter here is _not_ a nid in the sense of the NID_* macros.
315
 * It is an internal unique identifier.
316
 */
317
int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov,
318
                          int nid, const char *properties, void *method,
319
                          int (*method_up_ref)(void *),
320
                          void (*method_destruct)(void *))
321
0
{
322
0
    ALGORITHM *alg = NULL;
323
0
    IMPLEMENTATION *impl;
324
0
    int ret = 0;
325
0
    int i;
326
327
0
    if (nid <= 0 || method == NULL || store == NULL)
328
0
        return 0;
329
330
0
    if (properties == NULL)
331
0
        properties = "";
332
333
0
    if (!ossl_assert(prov != NULL))
334
0
        return 0;
335
336
    /* Create new entry */
337
0
    impl = OPENSSL_malloc(sizeof(*impl));
338
0
    if (impl == NULL)
339
0
        return 0;
340
0
    impl->method.method = method;
341
0
    impl->method.up_ref = method_up_ref;
342
0
    impl->method.free = method_destruct;
343
0
    if (!ossl_method_up_ref(&impl->method)) {
344
0
        OPENSSL_free(impl);
345
0
        return 0;
346
0
    }
347
0
    impl->provider = prov;
348
349
    /* Insert into the hash table if required */
350
0
    if (!ossl_property_write_lock(store)) {
351
0
        impl_free(impl);
352
0
        return 0;
353
0
    }
354
355
    /*
356
     * Flush the alg cache of any implementation that already exists
357
     * for this id.
358
     * This is done to ensure that on the next lookup we go through the
359
     * provider comparison in ossl_method_store_fetch.  If we don't do this
360
     * then this new method won't be given a chance to get selected.
361
     * NOTE: This doesn't actually remove the method from the backing store
362
     * It just ensures that we query the backing store when (re)-adding a
363
     * method to the algorithm cache, in case the one selected by the next
364
     * query selects a different implementation
365
     */
366
0
    ossl_method_cache_flush(store, nid);
367
368
    /*
369
     * Parse the properties associated with this method, and convert it to a
370
     * property list stored against the implementation for later comparison
371
     * during fetch operations
372
     */
373
0
    if ((impl->properties = ossl_prop_defn_get(store->ctx, properties)) == NULL) {
374
0
        impl->properties = ossl_parse_property(store->ctx, properties);
375
0
        if (impl->properties == NULL)
376
0
            goto err;
377
0
        if (!ossl_prop_defn_set(store->ctx, properties, &impl->properties)) {
378
0
            ossl_property_free(impl->properties);
379
0
            impl->properties = NULL;
380
0
            goto err;
381
0
        }
382
0
    }
383
384
    /*
385
     * Check if we have an algorithm cache already for this nid.  If so use
386
     * it, otherwise, create it, and insert it into the store
387
     */
388
0
    alg = ossl_method_store_retrieve(store, nid);
389
0
    if (alg == NULL) {
390
0
        if ((alg = OPENSSL_zalloc(sizeof(*alg))) == NULL
391
0
                || (alg->impls = sk_IMPLEMENTATION_new_null()) == NULL
392
0
                || (alg->cache = lh_QUERY_new(&query_hash, &query_cmp)) == NULL)
393
0
            goto err;
394
0
        alg->nid = nid;
395
0
        if (!ossl_method_store_insert(store, alg))
396
0
            goto err;
397
0
        OSSL_TRACE2(QUERY, "Inserted an alg with nid %d into the store %p\n", nid, (void *)store);
398
0
    }
399
400
    /* Push onto stack if there isn't one there already */
401
0
    for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
402
0
        const IMPLEMENTATION *tmpimpl = sk_IMPLEMENTATION_value(alg->impls, i);
403
404
0
        if (tmpimpl->provider == impl->provider
405
0
            && tmpimpl->properties == impl->properties)
406
0
            break;
407
0
    }
408
409
0
    if (i == sk_IMPLEMENTATION_num(alg->impls)
410
0
        && sk_IMPLEMENTATION_push(alg->impls, impl)) {
411
0
        ret = 1;
412
0
#ifndef FIPS_MODULE
413
0
        OSSL_TRACE_BEGIN(QUERY) {
414
0
            BIO_printf(trc_out, "Adding to method store "
415
0
                       "nid: %d\nproperties: %s\nprovider: %s\n",
416
0
                       nid, properties,
417
0
                       ossl_provider_name(prov) == NULL ? "none" :
418
0
                       ossl_provider_name(prov));
419
0
        } OSSL_TRACE_END(QUERY);
420
0
#endif
421
0
    }
422
0
    ossl_property_unlock(store);
423
0
    if (ret == 0)
424
0
        impl_free(impl);
425
0
    return ret;
426
427
0
err:
428
0
    ossl_property_unlock(store);
429
0
    alg_cleanup(0, alg, NULL);
430
0
    impl_free(impl);
431
0
    return 0;
432
0
}
433
434
int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid,
435
                             const void *method)
436
0
{
437
0
    ALGORITHM *alg = NULL;
438
0
    int i;
439
440
0
    if (nid <= 0 || method == NULL || store == NULL)
441
0
        return 0;
442
443
0
    if (!ossl_property_write_lock(store))
444
0
        return 0;
445
0
    ossl_method_cache_flush(store, nid);
446
0
    alg = ossl_method_store_retrieve(store, nid);
447
0
    if (alg == NULL) {
448
0
        ossl_property_unlock(store);
449
0
        return 0;
450
0
    }
451
452
    /*
453
     * A sorting find then a delete could be faster but these stacks should be
454
     * relatively small, so we avoid the overhead.  Sorting could also surprise
455
     * users when result orderings change (even though they are not guaranteed).
456
     */
457
0
    for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
458
0
        IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
459
460
0
        if (impl->method.method == method) {
461
0
            impl_free(impl);
462
0
            (void)sk_IMPLEMENTATION_delete(alg->impls, i);
463
0
            ossl_property_unlock(store);
464
0
            return 1;
465
0
        }
466
0
    }
467
0
    ossl_property_unlock(store);
468
0
    return 0;
469
0
}
470
471
struct alg_cleanup_by_provider_data_st {
472
    OSSL_METHOD_STORE *store;
473
    const OSSL_PROVIDER *prov;
474
};
475
476
/**
477
 * @brief Cleans up implementations of an algorithm associated with a provider.
478
 *
479
 * This function removes all implementations of a specified algorithm that are
480
 * associated with a given provider. The function walks through the stack of
481
 * implementations backwards to handle deletions without affecting indexing.
482
 *
483
 * @param idx Index of the algorithm (unused in this function).
484
 * @param alg Pointer to the ALGORITHM structure containing the implementations.
485
 * @param arg Pointer to the data containing the provider information.
486
 *
487
 * If tracing is enabled, messages are printed indicating the removal of each
488
 * implementation and its properties. If any implementation is removed, the
489
 * associated cache is flushed.
490
 */
491
static void
492
alg_cleanup_by_provider(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
493
0
{
494
0
    struct alg_cleanup_by_provider_data_st *data = arg;
495
0
    int i, count;
496
497
    /*
498
     * We walk the stack backwards, to avoid having to deal with stack shifts
499
     * caused by deletion
500
     */
501
0
    for (count = 0, i = sk_IMPLEMENTATION_num(alg->impls); i-- > 0;) {
502
0
        IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
503
504
0
        if (impl->provider == data->prov) {
505
0
#ifndef FIPS_MODULE
506
0
            OSSL_TRACE_BEGIN(QUERY) {
507
0
                char buf[512];
508
0
                size_t size;
509
510
0
                size = ossl_property_list_to_string(NULL, impl->properties, buf,
511
0
                                                    sizeof(buf));
512
0
                BIO_printf(trc_out, "Removing implementation from "
513
0
                           "query cache\nproperties %s\nprovider %s\n",
514
0
                           size == 0 ? "none" : buf,
515
0
                           ossl_provider_name(impl->provider) == NULL ? "none" :
516
0
                           ossl_provider_name(impl->provider));
517
0
            } OSSL_TRACE_END(QUERY);
518
0
#endif
519
520
0
            (void)sk_IMPLEMENTATION_delete(alg->impls, i);
521
0
            count++;
522
0
            impl_free(impl);
523
0
        }
524
0
    }
525
526
    /*
527
     * If we removed any implementation, we also clear the whole associated
528
     * cache, 'cause that's the sensible thing to do.
529
     * There's no point flushing the cache entries where we didn't remove
530
     * any implementation, though.
531
     */
532
0
    if (count > 0)
533
0
        ossl_method_cache_flush_alg(data->store, alg);
534
0
}
535
536
int ossl_method_store_remove_all_provided(OSSL_METHOD_STORE *store,
537
                                          const OSSL_PROVIDER *prov)
538
0
{
539
0
    struct alg_cleanup_by_provider_data_st data;
540
541
0
    if (!ossl_property_write_lock(store))
542
0
        return 0;
543
0
    data.prov = prov;
544
0
    data.store = store;
545
0
    ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup_by_provider, &data);
546
0
    ossl_property_unlock(store);
547
0
    return 1;
548
0
}
549
550
static void alg_do_one(ALGORITHM *alg, IMPLEMENTATION *impl,
551
                       void (*fn)(int id, void *method, void *fnarg),
552
                       void *fnarg)
553
0
{
554
0
    fn(alg->nid, impl->method.method, fnarg);
555
0
}
556
557
static void alg_copy(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
558
0
{
559
0
    STACK_OF(ALGORITHM) *newalg = arg;
560
561
0
    (void)sk_ALGORITHM_push(newalg, alg);
562
0
}
563
564
void ossl_method_store_do_all(OSSL_METHOD_STORE *store,
565
                              void (*fn)(int id, void *method, void *fnarg),
566
                              void *fnarg)
567
0
{
568
0
    int i, j;
569
0
    int numalgs, numimps;
570
0
    STACK_OF(ALGORITHM) *tmpalgs;
571
0
    ALGORITHM *alg;
572
573
0
    if (store != NULL) {
574
575
0
        if (!ossl_property_read_lock(store))
576
0
            return;
577
       
578
0
        tmpalgs = sk_ALGORITHM_new_reserve(NULL,
579
0
                                           ossl_sa_ALGORITHM_num(store->algs));
580
0
        if (tmpalgs == NULL) {
581
0
            ossl_property_unlock(store);
582
0
            return;
583
0
        }
584
585
0
        ossl_sa_ALGORITHM_doall_arg(store->algs, alg_copy, tmpalgs);
586
0
        ossl_property_unlock(store);
587
0
        numalgs = sk_ALGORITHM_num(tmpalgs);
588
0
        for (i = 0; i < numalgs; i++) {
589
0
            alg = sk_ALGORITHM_value(tmpalgs, i);
590
0
            numimps = sk_IMPLEMENTATION_num(alg->impls);
591
0
            for (j = 0; j < numimps; j++)
592
0
                alg_do_one(alg, sk_IMPLEMENTATION_value(alg->impls, j), fn, fnarg);
593
0
        }
594
0
        sk_ALGORITHM_free(tmpalgs);
595
0
    }
596
0
}
597
598
/**
599
 * @brief Fetches a method from the method store matching the given properties.
600
 *
601
 * This function searches the method store for an implementation of a specified
602
 * method, identified by its id (nid), and matching the given property query. If
603
 * successful, it returns the method and its associated provider.
604
 *
605
 * @param store Pointer to the OSSL_METHOD_STORE from which to fetch the method.
606
 *              Must be non-null.
607
 * @param nid (identifier) of the method to be fetched. Must be > 0
608
 * @param prop_query String containing the property query to match against.
609
 * @param prov_rw Pointer to the OSSL_PROVIDER to restrict the search to, or
610
 *                to receive the matched provider.
611
 * @param method Pointer to receive the fetched method. Must be non-null.
612
 *
613
 * @return 1 if the method is successfully fetched, 0 on failure.
614
 *
615
 * If tracing is enabled, a message is printed indicating the property query and
616
 * the resolved provider.
617
 *
618
 * NOTE: The nid parameter here is _not_ a NID in the sense of the NID_* macros.
619
 * It is a unique internal identifier value.
620
 */
621
int ossl_method_store_fetch(OSSL_METHOD_STORE *store,
622
                            int nid, const char *prop_query,
623
                            const OSSL_PROVIDER **prov_rw, void **method)
624
0
{
625
0
    OSSL_PROPERTY_LIST **plp;
626
0
    ALGORITHM *alg;
627
0
    IMPLEMENTATION *impl, *best_impl = NULL;
628
0
    OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
629
0
    const OSSL_PROVIDER *prov = prov_rw != NULL ? *prov_rw : NULL;
630
0
    int ret = 0;
631
0
    int j, best = -1, score, optional;
632
633
0
    if (nid <= 0 || method == NULL || store == NULL)
634
0
        return 0;
635
636
0
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
637
0
    if (ossl_lib_ctx_is_default(store->ctx)
638
0
            && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
639
0
        return 0;
640
0
#endif
641
642
    /* This only needs to be a read lock, because the query won't create anything */
643
0
    if (!ossl_property_read_lock(store))
644
0
        return 0;
645
646
0
    OSSL_TRACE2(QUERY, "Retrieving by nid %d from store %p\n", nid, (void *)store);
647
0
    alg = ossl_method_store_retrieve(store, nid);
648
0
    if (alg == NULL) {
649
0
        ossl_property_unlock(store);
650
0
        OSSL_TRACE2(QUERY, "Failed to retrieve by nid %d from store %p\n", nid, (void *)store);
651
0
        return 0;
652
0
    }
653
0
    OSSL_TRACE2(QUERY, "Retrieved by nid %d from store %p\n", nid, (void *)store);
654
655
    /*
656
     * If a property query string is provided, convert it to an
657
     * OSSL_PROPERTY_LIST structure
658
     */
659
0
    if (prop_query != NULL)
660
0
        p2 = pq = ossl_parse_query(store->ctx, prop_query, 0);
661
662
    /*
663
     * If the library context has default properties specified
664
     * then merge those with the properties passed to this function
665
     */
666
0
    plp = ossl_ctx_global_properties(store->ctx, 0);
667
0
    if (plp != NULL && *plp != NULL) {
668
0
        if (pq == NULL) {
669
0
            pq = *plp;
670
0
        } else {
671
0
            p2 = ossl_property_merge(pq, *plp);
672
0
            ossl_property_free(pq);
673
0
            if (p2 == NULL)
674
0
                goto fin;
675
0
            pq = p2;
676
0
        }
677
0
    }
678
679
    /*
680
     * Search for a provider that provides this implementation.
681
     * If the requested provider is NULL, then any provider will do,
682
     * otherwise we should try to find the one that matches the requested
683
     * provider.  Note that providers are given implicit preference via the
684
     * ordering of the implementation stack
685
     */
686
0
    if (pq == NULL) {
687
0
        for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
688
0
            if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
689
0
                && (prov == NULL || impl->provider == prov)) {
690
0
                best_impl = impl;
691
0
                ret = 1;
692
0
                break;
693
0
            }
694
0
        }
695
0
        goto fin;
696
0
    }
697
698
    /*
699
     * If there are optional properties specified
700
     * then run the search again, and select the provider that matches the
701
     * most options
702
     */
703
0
    optional = ossl_property_has_optional(pq);
704
0
    for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
705
0
        if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
706
0
            && (prov == NULL || impl->provider == prov)) {
707
0
            score = ossl_property_match_count(pq, impl->properties);
708
0
            if (score > best) {
709
0
                best_impl = impl;
710
0
                best = score;
711
0
                ret = 1;
712
0
                if (!optional)
713
0
                    goto fin;
714
0
            }
715
0
        }
716
0
    }
717
0
fin:
718
0
    if (ret && ossl_method_up_ref(&best_impl->method)) {
719
0
        *method = best_impl->method.method;
720
0
        if (prov_rw != NULL)
721
0
            *prov_rw = best_impl->provider;
722
0
    } else {
723
0
        ret = 0;
724
0
    }
725
726
0
#ifndef FIPS_MODULE
727
0
    OSSL_TRACE_BEGIN(QUERY) {
728
0
        char buf[512];
729
0
        int size;
730
731
0
        size = ossl_property_list_to_string(NULL, pq, buf, 512);
732
0
        BIO_printf(trc_out, "method store query with properties %s "
733
0
                   "resolves to provider %s\n",
734
0
                   size == 0 ? "none" : buf,
735
0
                   best_impl == NULL ? "none" :
736
0
                   ossl_provider_name(best_impl->provider));
737
0
    } OSSL_TRACE_END(QUERY);
738
0
#endif
739
740
0
    ossl_property_unlock(store);
741
0
    ossl_property_free(p2);
742
0
    return ret;
743
0
}
744
745
static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store,
746
                                        ALGORITHM *alg)
747
0
{
748
0
    store->cache_nelem -= lh_QUERY_num_items(alg->cache);
749
0
    impl_cache_flush_alg(0, alg);
750
0
}
751
752
static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid)
753
0
{
754
0
    ALGORITHM *alg = ossl_method_store_retrieve(store, nid);
755
756
0
    if (alg != NULL)
757
0
        ossl_method_cache_flush_alg(store, alg);
758
0
}
759
760
int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store)
761
0
{
762
0
    if (!ossl_property_write_lock(store))
763
0
        return 0;
764
0
    ossl_sa_ALGORITHM_doall(store->algs, &impl_cache_flush_alg);
765
0
    store->cache_nelem = 0;
766
0
    ossl_property_unlock(store);
767
0
    return 1;
768
0
}
769
770
IMPLEMENT_LHASH_DOALL_ARG(QUERY, IMPL_CACHE_FLUSH);
771
772
/*
773
 * Flush an element from the query cache (perhaps).
774
 *
775
 * In order to avoid taking a write lock or using atomic operations
776
 * to keep accurate least recently used (LRU) or least frequently used
777
 * (LFU) information, the procedure used here is to stochastically
778
 * flush approximately half the cache.
779
 *
780
 * This procedure isn't ideal, LRU or LFU would be better.  However,
781
 * in normal operation, reaching a full cache would be unexpected.
782
 * It means that no steady state of algorithm queries has been reached.
783
 * That is, it is most likely an attack of some form.  A suboptimal clearance
784
 * strategy that doesn't degrade performance of the normal case is
785
 * preferable to a more refined approach that imposes a performance
786
 * impact.
787
 */
788
static void impl_cache_flush_cache(QUERY *c, IMPL_CACHE_FLUSH *state)
789
0
{
790
0
    uint32_t n;
791
792
    /*
793
     * Implement the 32 bit xorshift as suggested by George Marsaglia in:
794
     *      https://doi.org/10.18637/jss.v008.i14
795
     *
796
     * This is a very fast PRNG so there is no need to extract bits one at a
797
     * time and use the entire value each time.
798
     */
799
0
    n = state->seed;
800
0
    n ^= n << 13;
801
0
    n ^= n >> 17;
802
0
    n ^= n << 5;
803
0
    state->seed = n;
804
805
0
    if ((n & 1) != 0)
806
0
        impl_cache_free(lh_QUERY_delete(state->cache, c));
807
0
    else
808
0
        state->nelem++;
809
0
}
810
811
static void impl_cache_flush_one_alg(ossl_uintmax_t idx, ALGORITHM *alg,
812
                                     void *v)
813
0
{
814
0
    IMPL_CACHE_FLUSH *state = (IMPL_CACHE_FLUSH *)v;
815
0
    unsigned long orig_down_load = lh_QUERY_get_down_load(alg->cache);
816
817
0
    state->cache = alg->cache;
818
0
    lh_QUERY_set_down_load(alg->cache, 0);
819
0
    lh_QUERY_doall_IMPL_CACHE_FLUSH(state->cache, &impl_cache_flush_cache,
820
0
                                    state);
821
0
    lh_QUERY_set_down_load(alg->cache, orig_down_load);
822
0
}
823
824
static void ossl_method_cache_flush_some(OSSL_METHOD_STORE *store)
825
0
{
826
0
    IMPL_CACHE_FLUSH state;
827
0
    static TSAN_QUALIFIER uint32_t global_seed = 1;
828
829
0
    state.nelem = 0;
830
0
    state.using_global_seed = 0;
831
0
    if ((state.seed = OPENSSL_rdtsc()) == 0) {
832
        /* If there is no timer available, seed another way */
833
0
        state.using_global_seed = 1;
834
0
        state.seed = tsan_load(&global_seed);
835
0
    }
836
0
    store->cache_need_flush = 0;
837
0
    ossl_sa_ALGORITHM_doall_arg(store->algs, &impl_cache_flush_one_alg, &state);
838
0
    store->cache_nelem = state.nelem;
839
    /* Without a timer, update the global seed */
840
0
    if (state.using_global_seed)
841
0
        tsan_add(&global_seed, state.seed);
842
0
}
843
844
int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
845
                                int nid, const char *prop_query, void **method)
846
0
{
847
0
    ALGORITHM *alg;
848
0
    QUERY elem, *r;
849
0
    int res = 0;
850
851
0
    if (nid <= 0 || store == NULL || prop_query == NULL)
852
0
        return 0;
853
854
0
    if (!ossl_property_read_lock(store))
855
0
        return 0;
856
0
    alg = ossl_method_store_retrieve(store, nid);
857
0
    if (alg == NULL)
858
0
        goto err;
859
860
0
    elem.query = prop_query;
861
0
    elem.provider = prov;
862
0
    r = lh_QUERY_retrieve(alg->cache, &elem);
863
0
    if (r == NULL)
864
0
        goto err;
865
0
    if (ossl_method_up_ref(&r->method)) {
866
0
        *method = r->method.method;
867
0
        res = 1;
868
0
    }
869
0
err:
870
0
    ossl_property_unlock(store);
871
0
    return res;
872
0
}
873
874
int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
875
                                int nid, const char *prop_query, void *method,
876
                                int (*method_up_ref)(void *),
877
                                void (*method_destruct)(void *))
878
0
{
879
0
    QUERY elem, *old, *p = NULL;
880
0
    ALGORITHM *alg;
881
0
    size_t len;
882
0
    int res = 1;
883
884
0
    if (nid <= 0 || store == NULL || prop_query == NULL)
885
0
        return 0;
886
887
0
    if (!ossl_assert(prov != NULL))
888
0
        return 0;
889
890
0
    if (!ossl_property_write_lock(store))
891
0
        return 0;
892
0
    if (store->cache_need_flush)
893
0
        ossl_method_cache_flush_some(store);
894
0
    alg = ossl_method_store_retrieve(store, nid);
895
0
    if (alg == NULL)
896
0
        goto err;
897
898
0
    if (method == NULL) {
899
0
        elem.query = prop_query;
900
0
        elem.provider = prov;
901
0
        if ((old = lh_QUERY_delete(alg->cache, &elem)) != NULL) {
902
0
            impl_cache_free(old);
903
0
            store->cache_nelem--;
904
0
        }
905
0
        goto end;
906
0
    }
907
0
    p = OPENSSL_malloc(sizeof(*p) + (len = strlen(prop_query)));
908
0
    if (p != NULL) {
909
0
        p->query = p->body;
910
0
        p->provider = prov;
911
0
        p->method.method = method;
912
0
        p->method.up_ref = method_up_ref;
913
0
        p->method.free = method_destruct;
914
0
        if (!ossl_method_up_ref(&p->method))
915
0
            goto err;
916
0
        memcpy((char *)p->query, prop_query, len + 1);
917
0
        if ((old = lh_QUERY_insert(alg->cache, p)) != NULL) {
918
0
            impl_cache_free(old);
919
0
            goto end;
920
0
        }
921
0
        if (!lh_QUERY_error(alg->cache)) {
922
0
            if (++store->cache_nelem >= IMPL_CACHE_FLUSH_THRESHOLD)
923
0
                store->cache_need_flush = 1;
924
0
            goto end;
925
0
        }
926
0
        ossl_method_free(&p->method);
927
0
    }
928
0
err:
929
0
    res = 0;
930
0
    OPENSSL_free(p);
931
0
end:
932
0
    ossl_property_unlock(store);
933
0
    return res;
934
0
}