Coverage Report

Created: 2025-12-10 06:24

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