Coverage Report

Created: 2024-11-21 07:03

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