1/*
2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License").  You may not use
5 * this file except in compliance with the License.  You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10#include <stdlib.h>
11#include "crypto/cryptlib.h"
12#include "internal/thread_once.h"
13
14int ossl_do_ex_data_init(OSSL_LIB_CTX *ctx)
15{
16    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
17
18    if (global == NULL)
19        return 0;
20
21    global->ex_data_lock = CRYPTO_THREAD_lock_new();
22    return global->ex_data_lock != NULL;
23}
24
25/*
26 * Return the EX_CALLBACKS from the |ex_data| array that corresponds to
27 * a given class.  On success, *holds the lock.*
28 * The |global| parameter is assumed to be non null (checked by the caller).
29 */
30static EX_CALLBACKS *get_and_lock(OSSL_EX_DATA_GLOBAL *global, int class_index)
31{
32    EX_CALLBACKS *ip;
33
34    if (class_index < 0 || class_index >= CRYPTO_EX_INDEX__COUNT) {
35        ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT);
36        return NULL;
37    }
38
39    if (global->ex_data_lock == NULL) {
40        /*
41         * If we get here, someone (who?) cleaned up the lock, so just
42         * treat it as an error.
43         */
44         return NULL;
45    }
46
47    if (!CRYPTO_THREAD_write_lock(global->ex_data_lock))
48        return NULL;
49    ip = &global->ex_data[class_index];
50    return ip;
51}
52
53static void cleanup_cb(EX_CALLBACK *funcs)
54{
55    OPENSSL_free(funcs);
56}
57
58/*
59 * Release all "ex_data" state to prevent memory leaks. This can't be made
60 * thread-safe without overhauling a lot of stuff, and shouldn't really be
61 * called under potential race-conditions anyway (it's for program shutdown
62 * after all).
63 */
64void ossl_crypto_cleanup_all_ex_data_int(OSSL_LIB_CTX *ctx)
65{
66    int i;
67    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
68
69    if (global == NULL)
70        return;
71
72    for (i = 0; i < CRYPTO_EX_INDEX__COUNT; ++i) {
73        EX_CALLBACKS *ip = &global->ex_data[i];
74
75        sk_EX_CALLBACK_pop_free(ip->meth, cleanup_cb);
76        ip->meth = NULL;
77    }
78
79    CRYPTO_THREAD_lock_free(global->ex_data_lock);
80    global->ex_data_lock = NULL;
81}
82
83
84/*
85 * Unregister a new index by replacing the callbacks with no-ops.
86 * Any in-use instances are leaked.
87 */
88static void dummy_new(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
89                     long argl, void *argp)
90{
91}
92
93static void dummy_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
94                       long argl, void *argp)
95{
96}
97
98static int dummy_dup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
99                     void **from_d, int idx,
100                     long argl, void *argp)
101{
102    return 1;
103}
104
105int ossl_crypto_free_ex_index_ex(OSSL_LIB_CTX *ctx, int class_index, int idx)
106{
107    EX_CALLBACKS *ip;
108    EX_CALLBACK *a;
109    int toret = 0;
110    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
111
112    if (global == NULL)
113        return 0;
114
115    ip = get_and_lock(global, class_index);
116    if (ip == NULL)
117        return 0;
118
119    if (idx < 0 || idx >= sk_EX_CALLBACK_num(ip->meth))
120        goto err;
121    a = sk_EX_CALLBACK_value(ip->meth, idx);
122    if (a == NULL)
123        goto err;
124    a->new_func = dummy_new;
125    a->dup_func = dummy_dup;
126    a->free_func = dummy_free;
127    toret = 1;
128err:
129    CRYPTO_THREAD_unlock(global->ex_data_lock);
130    return toret;
131}
132
133int CRYPTO_free_ex_index(int class_index, int idx)
134{
135    return ossl_crypto_free_ex_index_ex(NULL, class_index, idx);
136}
137
138/*
139 * Register a new index.
140 */
141int ossl_crypto_get_ex_new_index_ex(OSSL_LIB_CTX *ctx, int class_index,
142                                    long argl, void *argp,
143                                    CRYPTO_EX_new *new_func,
144                                    CRYPTO_EX_dup *dup_func,
145                                    CRYPTO_EX_free *free_func,
146                                    int priority)
147{
148    int toret = -1;
149    EX_CALLBACK *a;
150    EX_CALLBACKS *ip;
151    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
152
153    if (global == NULL)
154        return -1;
155
156    ip = get_and_lock(global, class_index);
157    if (ip == NULL)
158        return -1;
159
160    if (ip->meth == NULL) {
161        ip->meth = sk_EX_CALLBACK_new_null();
162        /* We push an initial value on the stack because the SSL
163         * "app_data" routines use ex_data index zero.  See RT 3710. */
164        if (ip->meth == NULL
165            || !sk_EX_CALLBACK_push(ip->meth, NULL)) {
166            sk_EX_CALLBACK_free(ip->meth);
167            ip->meth = NULL;
168            ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
169            goto err;
170        }
171    }
172
173    a = (EX_CALLBACK *)OPENSSL_malloc(sizeof(*a));
174    if (a == NULL) {
175        ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
176        goto err;
177    }
178    a->argl = argl;
179    a->argp = argp;
180    a->new_func = new_func;
181    a->dup_func = dup_func;
182    a->free_func = free_func;
183    a->priority = priority;
184
185    if (!sk_EX_CALLBACK_push(ip->meth, NULL)) {
186        ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
187        OPENSSL_free(a);
188        goto err;
189    }
190    toret = sk_EX_CALLBACK_num(ip->meth) - 1;
191    (void)sk_EX_CALLBACK_set(ip->meth, toret, a);
192
193 err:
194    CRYPTO_THREAD_unlock(global->ex_data_lock);
195    return toret;
196}
197
198int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
199                            CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
200                            CRYPTO_EX_free *free_func)
201{
202    return ossl_crypto_get_ex_new_index_ex(NULL, class_index, argl, argp,
203                                           new_func, dup_func, free_func, 0);
204}
205
206/*
207 * Initialise a new CRYPTO_EX_DATA for use in a particular class - including
208 * calling new() callbacks for each index in the class used by this variable
209 * Thread-safe by copying a class's array of "EX_CALLBACK" entries
210 * in the lock, then using them outside the lock. Note this only applies
211 * to the global "ex_data" state (ie. class definitions), not 'ad' itself.
212 */
213int ossl_crypto_new_ex_data_ex(OSSL_LIB_CTX *ctx, int class_index, void *obj,
214                               CRYPTO_EX_DATA *ad)
215{
216    int mx, i;
217    void *ptr;
218    EX_CALLBACK **storage = NULL;
219    EX_CALLBACK *stack[10];
220    EX_CALLBACKS *ip;
221    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
222
223    if (global == NULL)
224        return 0;
225
226    ip = get_and_lock(global, class_index);
227    if (ip == NULL)
228        return 0;
229
230    ad->ctx = ctx;
231    ad->sk = NULL;
232    mx = sk_EX_CALLBACK_num(ip->meth);
233    if (mx > 0) {
234        if (mx < (int)OSSL_NELEM(stack))
235            storage = stack;
236        else
237            storage = OPENSSL_malloc(sizeof(*storage) * mx);
238        if (storage != NULL)
239            for (i = 0; i < mx; i++)
240                storage[i] = sk_EX_CALLBACK_value(ip->meth, i);
241    }
242    CRYPTO_THREAD_unlock(global->ex_data_lock);
243
244    if (mx > 0 && storage == NULL) {
245        ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
246        return 0;
247    }
248    for (i = 0; i < mx; i++) {
249        if (storage[i] != NULL && storage[i]->new_func != NULL) {
250            ptr = CRYPTO_get_ex_data(ad, i);
251            storage[i]->new_func(obj, ptr, ad, i,
252                                 storage[i]->argl, storage[i]->argp);
253        }
254    }
255    if (storage != stack)
256        OPENSSL_free(storage);
257    return 1;
258}
259
260int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
261{
262    return ossl_crypto_new_ex_data_ex(NULL, class_index, obj, ad);
263}
264
265/*
266 * Duplicate a CRYPTO_EX_DATA variable - including calling dup() callbacks
267 * for each index in the class used by this variable
268 */
269int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
270                       const CRYPTO_EX_DATA *from)
271{
272    int mx, j, i;
273    void *ptr;
274    EX_CALLBACK *stack[10];
275    EX_CALLBACK **storage = NULL;
276    EX_CALLBACKS *ip;
277    int toret = 0;
278    OSSL_EX_DATA_GLOBAL *global;
279
280    to->ctx = from->ctx;
281    if (from->sk == NULL)
282        /* Nothing to copy over */
283        return 1;
284
285    global = ossl_lib_ctx_get_ex_data_global(from->ctx);
286    if (global == NULL)
287        return 0;
288
289    ip = get_and_lock(global, class_index);
290    if (ip == NULL)
291        return 0;
292
293    mx = sk_EX_CALLBACK_num(ip->meth);
294    j = sk_void_num(from->sk);
295    if (j < mx)
296        mx = j;
297    if (mx > 0) {
298        if (mx < (int)OSSL_NELEM(stack))
299            storage = stack;
300        else
301            storage = OPENSSL_malloc(sizeof(*storage) * mx);
302        if (storage != NULL)
303            for (i = 0; i < mx; i++)
304                storage[i] = sk_EX_CALLBACK_value(ip->meth, i);
305    }
306    CRYPTO_THREAD_unlock(global->ex_data_lock);
307
308    if (mx == 0)
309        return 1;
310    if (storage == NULL) {
311        ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
312        return 0;
313    }
314    /*
315     * Make sure the ex_data stack is at least |mx| elements long to avoid
316     * issues in the for loop that follows; so go get the |mx|'th element
317     * (if it does not exist CRYPTO_get_ex_data() returns NULL), and assign
318     * to itself. This is normally a no-op; but ensures the stack is the
319     * proper size
320     */
321    if (!CRYPTO_set_ex_data(to, mx - 1, CRYPTO_get_ex_data(to, mx - 1)))
322        goto err;
323
324    for (i = 0; i < mx; i++) {
325        ptr = CRYPTO_get_ex_data(from, i);
326        if (storage[i] != NULL && storage[i]->dup_func != NULL)
327            if (!storage[i]->dup_func(to, from, &ptr, i,
328                                      storage[i]->argl, storage[i]->argp))
329                goto err;
330        CRYPTO_set_ex_data(to, i, ptr);
331    }
332    toret = 1;
333 err:
334    if (storage != stack)
335        OPENSSL_free(storage);
336    return toret;
337}
338
339struct ex_callback_entry {
340    const EX_CALLBACK *excb;
341    int index;
342};
343
344static int ex_callback_compare(const void *a, const void *b)
345{
346    const struct ex_callback_entry *ap = (const struct ex_callback_entry *)a;
347    const struct ex_callback_entry *bp = (const struct ex_callback_entry *)b;
348
349    if (ap->excb == bp->excb)
350        return 0;
351
352    if (ap->excb == NULL)
353        return 1;
354    if (bp->excb == NULL)
355        return -1;
356    if (ap->excb->priority == bp->excb->priority)
357        return 0;
358    return ap->excb->priority > bp->excb->priority ? -1 : 1;
359}
360
361/*
362 * Cleanup a CRYPTO_EX_DATA variable - including calling free() callbacks for
363 * each index in the class used by this variable
364 */
365void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
366{
367    int mx, i;
368    EX_CALLBACKS *ip;
369    void *ptr;
370    const EX_CALLBACK *f;
371    struct ex_callback_entry stack[10];
372    struct ex_callback_entry *storage = NULL;
373    OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ad->ctx);
374
375    if (global == NULL)
376        goto err;
377
378    ip = get_and_lock(global, class_index);
379    if (ip == NULL)
380        goto err;
381
382    mx = sk_EX_CALLBACK_num(ip->meth);
383    if (mx > 0) {
384        if (mx < (int)OSSL_NELEM(stack))
385            storage = stack;
386        else
387            storage = OPENSSL_malloc(sizeof(*storage) * mx);
388        if (storage != NULL)
389            for (i = 0; i < mx; i++) {
390                storage[i].excb = sk_EX_CALLBACK_value(ip->meth, i);
391                storage[i].index = i;
392            }
393    }
394    CRYPTO_THREAD_unlock(global->ex_data_lock);
395
396    if (storage != NULL) {
397        /* Sort according to priority. High priority first */
398        qsort(storage, mx, sizeof(*storage), ex_callback_compare);
399        for (i = 0; i < mx; i++) {
400            f = storage[i].excb;
401
402            if (f != NULL && f->free_func != NULL) {
403                ptr = CRYPTO_get_ex_data(ad, storage[i].index);
404                f->free_func(obj, ptr, ad, storage[i].index, f->argl, f->argp);
405            }
406        }
407    }
408
409    if (storage != stack)
410        OPENSSL_free(storage);
411 err:
412    sk_void_free(ad->sk);
413    ad->sk = NULL;
414    ad->ctx = NULL;
415}
416
417/*
418 * Allocate a given CRYPTO_EX_DATA item using the class specific allocation
419 * function
420 */
421int CRYPTO_alloc_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad,
422                         int idx)
423{
424    void *curval;
425
426    curval = CRYPTO_get_ex_data(ad, idx);
427    /* Already there, no need to allocate */
428    if (curval != NULL)
429        return 1;
430
431    return ossl_crypto_alloc_ex_data_intern(class_index, obj, ad, idx);
432}
433
434int ossl_crypto_alloc_ex_data_intern(int class_index, void *obj,
435                                     CRYPTO_EX_DATA *ad, int idx)
436{
437    EX_CALLBACK *f;
438    EX_CALLBACKS *ip;
439    OSSL_EX_DATA_GLOBAL *global;
440
441    global = ossl_lib_ctx_get_ex_data_global(ad->ctx);
442    if (global == NULL)
443        return 0;
444
445    ip = get_and_lock(global, class_index);
446    if (ip == NULL)
447        return 0;
448    f = sk_EX_CALLBACK_value(ip->meth, idx);
449    CRYPTO_THREAD_unlock(global->ex_data_lock);
450
451    /*
452     * This should end up calling CRYPTO_set_ex_data(), which allocates
453     * everything necessary to support placing the new data in the right spot.
454     */
455    if (f->new_func == NULL)
456        return 0;
457
458    f->new_func(obj, NULL, ad, idx, f->argl, f->argp);
459
460    return 1;
461}
462
463/*
464 * For a given CRYPTO_EX_DATA variable, set the value corresponding to a
465 * particular index in the class used by this variable
466 */
467int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val)
468{
469    int i;
470
471    if (ad->sk == NULL) {
472        if ((ad->sk = sk_void_new_null()) == NULL) {
473            ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
474            return 0;
475        }
476    }
477
478    for (i = sk_void_num(ad->sk); i <= idx; ++i) {
479        if (!sk_void_push(ad->sk, NULL)) {
480            ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
481            return 0;
482        }
483    }
484    if (sk_void_set(ad->sk, idx, val) != val) {
485        /* Probably the index is out of bounds */
486        ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT);
487        return 0;
488    }
489    return 1;
490}
491
492/*
493 * For a given CRYPTO_EX_DATA_ variable, get the value corresponding to a
494 * particular index in the class used by this variable
495 */
496void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx)
497{
498    if (ad->sk == NULL || idx >= sk_void_num(ad->sk))
499        return NULL;
500    return sk_void_value(ad->sk, idx);
501}
502
503OSSL_LIB_CTX *ossl_crypto_ex_data_get_ossl_lib_ctx(const CRYPTO_EX_DATA *ad)
504{
505    return ad->ctx;
506}
507