1/*
2 * Copyright 2002-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/* We need to use some engine deprecated APIs */
11#define OPENSSL_SUPPRESS_DEPRECATED
12
13#include "internal/cryptlib.h"
14#include <stdio.h>
15#include <ctype.h>
16#include <openssl/crypto.h>
17#include "internal/conf.h"
18#include <openssl/conf_api.h>
19#include "internal/dso.h"
20#include "internal/thread_once.h"
21#include <openssl/x509.h>
22#include <openssl/trace.h>
23#include <openssl/engine.h>
24#include "conf_local.h"
25
26DEFINE_STACK_OF(CONF_MODULE)
27DEFINE_STACK_OF(CONF_IMODULE)
28
29#define DSO_mod_init_name "OPENSSL_init"
30#define DSO_mod_finish_name "OPENSSL_finish"
31
32/*
33 * This structure contains a data about supported modules. entries in this
34 * table correspond to either dynamic or static modules.
35 */
36
37struct conf_module_st {
38    /* DSO of this module or NULL if static */
39    DSO *dso;
40    /* Name of the module */
41    char *name;
42    /* Init function */
43    conf_init_func *init;
44    /* Finish function */
45    conf_finish_func *finish;
46    /* Number of successfully initialized modules */
47    int links;
48    void *usr_data;
49};
50
51/*
52 * This structure contains information about modules that have been
53 * successfully initialized. There may be more than one entry for a given
54 * module.
55 */
56
57struct conf_imodule_st {
58    CONF_MODULE *pmod;
59    char *name;
60    char *value;
61    unsigned long flags;
62    void *usr_data;
63};
64
65static CRYPTO_ONCE init_module_list_lock = CRYPTO_ONCE_STATIC_INIT;
66static CRYPTO_RWLOCK *module_list_lock = NULL;
67static STACK_OF(CONF_MODULE) *supported_modules = NULL; /* protected by lock */
68static STACK_OF(CONF_IMODULE) *initialized_modules = NULL; /* protected by lock */
69
70static CRYPTO_ONCE load_builtin_modules = CRYPTO_ONCE_STATIC_INIT;
71
72static void module_free(CONF_MODULE *md);
73static void module_finish(CONF_IMODULE *imod);
74static int module_run(const CONF *cnf, const char *name, const char *value,
75                      unsigned long flags);
76static CONF_MODULE *module_add(DSO *dso, const char *name,
77                               conf_init_func *ifunc,
78                               conf_finish_func *ffunc);
79static CONF_MODULE *module_find(const char *name);
80static int module_init(CONF_MODULE *pmod, const char *name, const char *value,
81                       const CONF *cnf);
82static CONF_MODULE *module_load_dso(const CONF *cnf, const char *name,
83                                    const char *value);
84
85static int conf_modules_finish_int(void);
86
87static void module_lists_free(void)
88{
89    CRYPTO_THREAD_lock_free(module_list_lock);
90    module_list_lock = NULL;
91
92    sk_CONF_MODULE_free(supported_modules);
93    supported_modules = NULL;
94
95    sk_CONF_IMODULE_free(initialized_modules);
96    initialized_modules = NULL;
97}
98
99DEFINE_RUN_ONCE_STATIC(do_init_module_list_lock)
100{
101    module_list_lock = CRYPTO_THREAD_lock_new();
102    if (module_list_lock == NULL) {
103        ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
104        return 0;
105    }
106
107    return 1;
108}
109
110static int conf_diagnostics(const CONF *cnf)
111{
112    return _CONF_get_number(cnf, NULL, "config_diagnostics") != 0;
113}
114
115/* Main function: load modules from a CONF structure */
116
117int CONF_modules_load(const CONF *cnf, const char *appname,
118                      unsigned long flags)
119{
120    STACK_OF(CONF_VALUE) *values;
121    CONF_VALUE *vl;
122    char *vsection = NULL;
123    int ret, i;
124
125    if (!cnf)
126        return 1;
127
128    if (conf_diagnostics(cnf))
129        flags &= ~(CONF_MFLAGS_IGNORE_ERRORS
130                   | CONF_MFLAGS_IGNORE_RETURN_CODES
131                   | CONF_MFLAGS_SILENT
132                   | CONF_MFLAGS_IGNORE_MISSING_FILE);
133
134    ERR_set_mark();
135    if (appname)
136        vsection = NCONF_get_string(cnf, NULL, appname);
137
138    if (!appname || (!vsection && (flags & CONF_MFLAGS_DEFAULT_SECTION)))
139        vsection = NCONF_get_string(cnf, NULL, "openssl_conf");
140
141    if (!vsection) {
142        ERR_pop_to_mark();
143        return 1;
144    }
145
146    OSSL_TRACE1(CONF, "Configuration in section %s\n", vsection);
147    values = NCONF_get_section(cnf, vsection);
148
149    if (values == NULL) {
150        if (!(flags & CONF_MFLAGS_SILENT)) {
151            ERR_clear_last_mark();
152            ERR_raise_data(ERR_LIB_CONF,
153                           CONF_R_OPENSSL_CONF_REFERENCES_MISSING_SECTION,
154                           "openssl_conf=%s", vsection);
155        } else {
156            ERR_pop_to_mark();
157        }
158        return 0;
159    }
160    ERR_pop_to_mark();
161
162    for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
163        vl = sk_CONF_VALUE_value(values, i);
164        ERR_set_mark();
165        ret = module_run(cnf, vl->name, vl->value, flags);
166        OSSL_TRACE3(CONF, "Running module %s (%s) returned %d\n",
167                    vl->name, vl->value, ret);
168        if (ret <= 0)
169            if (!(flags & CONF_MFLAGS_IGNORE_ERRORS)) {
170                ERR_clear_last_mark();
171                return ret;
172            }
173        ERR_pop_to_mark();
174    }
175
176    return 1;
177
178}
179
180int CONF_modules_load_file_ex(OSSL_LIB_CTX *libctx, const char *filename,
181                              const char *appname, unsigned long flags)
182{
183    char *file = NULL;
184    CONF *conf = NULL;
185    int ret = 0, diagnostics = 0;
186
187    ERR_set_mark();
188
189    if (filename == NULL) {
190        file = CONF_get1_default_config_file();
191        if (file == NULL)
192            goto err;
193        if (*file == '\0') {
194            /* Do not try to load an empty file name but do not error out */
195            ret = 1;
196            goto err;
197        }
198    } else {
199        file = (char *)filename;
200    }
201
202    conf = NCONF_new_ex(libctx, NULL);
203    if (conf == NULL)
204        goto err;
205
206    if (NCONF_load(conf, file, NULL) <= 0) {
207        if ((flags & CONF_MFLAGS_IGNORE_MISSING_FILE) &&
208            (ERR_GET_REASON(ERR_peek_last_error()) == CONF_R_NO_SUCH_FILE)) {
209            ret = 1;
210        }
211        goto err;
212    }
213
214    ret = CONF_modules_load(conf, appname, flags);
215    diagnostics = conf_diagnostics(conf);
216
217 err:
218    if (filename == NULL)
219        OPENSSL_free(file);
220    NCONF_free(conf);
221
222    if ((flags & CONF_MFLAGS_IGNORE_RETURN_CODES) != 0 && !diagnostics)
223        ret = 1;
224
225    if (ret > 0)
226        ERR_pop_to_mark();
227    else
228        ERR_clear_last_mark();
229
230    return ret;
231}
232
233int CONF_modules_load_file(const char *filename,
234                           const char *appname, unsigned long flags)
235{
236    return CONF_modules_load_file_ex(NULL, filename, appname, flags);
237}
238
239DEFINE_RUN_ONCE_STATIC(do_load_builtin_modules)
240{
241    OPENSSL_load_builtin_modules();
242#ifndef OPENSSL_NO_ENGINE
243    /* Need to load ENGINEs */
244    ENGINE_load_builtin_engines();
245#endif
246    return 1;
247}
248
249static int module_run(const CONF *cnf, const char *name, const char *value,
250                      unsigned long flags)
251{
252    CONF_MODULE *md;
253    int ret;
254
255    if (!RUN_ONCE(&load_builtin_modules, do_load_builtin_modules))
256        return -1;
257
258    md = module_find(name);
259
260    /* Module not found: try to load DSO */
261    if (!md && !(flags & CONF_MFLAGS_NO_DSO))
262        md = module_load_dso(cnf, name, value);
263
264    if (!md) {
265        if (!(flags & CONF_MFLAGS_SILENT)) {
266            ERR_raise_data(ERR_LIB_CONF, CONF_R_UNKNOWN_MODULE_NAME,
267                           "module=%s", name);
268        }
269        return -1;
270    }
271
272    ret = module_init(md, name, value, cnf);
273
274    if (ret <= 0) {
275        if (!(flags & CONF_MFLAGS_SILENT))
276            ERR_raise_data(ERR_LIB_CONF, CONF_R_MODULE_INITIALIZATION_ERROR,
277                           "module=%s, value=%s retcode=%-8d",
278                           name, value, ret);
279    }
280
281    return ret;
282}
283
284/* Load a module from a DSO */
285static CONF_MODULE *module_load_dso(const CONF *cnf,
286                                    const char *name, const char *value)
287{
288    DSO *dso = NULL;
289    conf_init_func *ifunc;
290    conf_finish_func *ffunc;
291    const char *path = NULL;
292    int errcode = 0;
293    CONF_MODULE *md;
294
295    /* Look for alternative path in module section */
296    path = _CONF_get_string(cnf, value, "path");
297    if (path == NULL) {
298        path = name;
299    }
300    dso = DSO_load(NULL, path, NULL, 0);
301    if (dso == NULL) {
302        errcode = CONF_R_ERROR_LOADING_DSO;
303        goto err;
304    }
305    ifunc = (conf_init_func *)DSO_bind_func(dso, DSO_mod_init_name);
306    if (ifunc == NULL) {
307        errcode = CONF_R_MISSING_INIT_FUNCTION;
308        goto err;
309    }
310    ffunc = (conf_finish_func *)DSO_bind_func(dso, DSO_mod_finish_name);
311    /* All OK, add module */
312    md = module_add(dso, name, ifunc, ffunc);
313
314    if (md == NULL)
315        goto err;
316
317    return md;
318
319 err:
320    DSO_free(dso);
321    ERR_raise_data(ERR_LIB_CONF, errcode, "module=%s, path=%s", name, path);
322    return NULL;
323}
324
325/* add module to list */
326static CONF_MODULE *module_add(DSO *dso, const char *name,
327                               conf_init_func *ifunc, conf_finish_func *ffunc)
328{
329    CONF_MODULE *tmod = NULL;
330
331    if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock))
332        return NULL;
333
334    if (!CRYPTO_THREAD_write_lock(module_list_lock))
335        return NULL;
336
337    if (supported_modules == NULL)
338        supported_modules = sk_CONF_MODULE_new_null();
339    if (supported_modules == NULL)
340        goto err;
341    if ((tmod = OPENSSL_zalloc(sizeof(*tmod))) == NULL) {
342        ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
343        goto err;
344    }
345
346    tmod->dso = dso;
347    tmod->name = OPENSSL_strdup(name);
348    tmod->init = ifunc;
349    tmod->finish = ffunc;
350    if (tmod->name == NULL)
351        goto err;
352
353    if (!sk_CONF_MODULE_push(supported_modules, tmod))
354        goto err;
355
356    CRYPTO_THREAD_unlock(module_list_lock);
357    return tmod;
358
359 err:
360    CRYPTO_THREAD_unlock(module_list_lock);
361    if (tmod != NULL) {
362        OPENSSL_free(tmod->name);
363        OPENSSL_free(tmod);
364    }
365    return NULL;
366}
367
368/*
369 * Find a module from the list. We allow module names of the form
370 * modname.XXXX to just search for modname to allow the same module to be
371 * initialized more than once.
372 */
373
374static CONF_MODULE *module_find(const char *name)
375{
376    CONF_MODULE *tmod;
377    int i, nchar;
378    char *p;
379    p = strrchr(name, '.');
380
381    if (p)
382        nchar = p - name;
383    else
384        nchar = strlen(name);
385
386    if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock))
387        return NULL;
388
389    if (!CRYPTO_THREAD_read_lock(module_list_lock))
390        return NULL;
391
392    for (i = 0; i < sk_CONF_MODULE_num(supported_modules); i++) {
393        tmod = sk_CONF_MODULE_value(supported_modules, i);
394        if (strncmp(tmod->name, name, nchar) == 0) {
395            CRYPTO_THREAD_unlock(module_list_lock);
396            return tmod;
397        }
398    }
399
400    CRYPTO_THREAD_unlock(module_list_lock);
401    return NULL;
402}
403
404/* initialize a module */
405static int module_init(CONF_MODULE *pmod, const char *name, const char *value,
406                       const CONF *cnf)
407{
408    int ret = 1;
409    int init_called = 0;
410    CONF_IMODULE *imod = NULL;
411
412    /* Otherwise add initialized module to list */
413    imod = OPENSSL_malloc(sizeof(*imod));
414    if (imod == NULL)
415        goto err;
416
417    imod->pmod = pmod;
418    imod->name = OPENSSL_strdup(name);
419    imod->value = OPENSSL_strdup(value);
420    imod->usr_data = NULL;
421
422    if (!imod->name || !imod->value)
423        goto memerr;
424
425    /* Try to initialize module */
426    if (pmod->init) {
427        ret = pmod->init(imod, cnf);
428        init_called = 1;
429        /* Error occurred, exit */
430        if (ret <= 0)
431            goto err;
432    }
433
434    if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock))
435        goto err;
436
437    if (!CRYPTO_THREAD_write_lock(module_list_lock))
438        goto err;
439
440    if (initialized_modules == NULL) {
441        initialized_modules = sk_CONF_IMODULE_new_null();
442        if (initialized_modules == NULL) {
443            CRYPTO_THREAD_unlock(module_list_lock);
444            ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
445            goto err;
446        }
447    }
448
449    if (!sk_CONF_IMODULE_push(initialized_modules, imod)) {
450        CRYPTO_THREAD_unlock(module_list_lock);
451        ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
452        goto err;
453    }
454
455    pmod->links++;
456
457    CRYPTO_THREAD_unlock(module_list_lock);
458    return ret;
459
460 err:
461
462    /* We've started the module so we'd better finish it */
463    if (pmod->finish && init_called)
464        pmod->finish(imod);
465
466 memerr:
467    if (imod) {
468        OPENSSL_free(imod->name);
469        OPENSSL_free(imod->value);
470        OPENSSL_free(imod);
471    }
472
473    return -1;
474
475}
476
477/*
478 * Unload any dynamic modules that have a link count of zero: i.e. have no
479 * active initialized modules. If 'all' is set then all modules are unloaded
480 * including static ones.
481 */
482
483void CONF_modules_unload(int all)
484{
485    int i;
486    CONF_MODULE *md;
487
488    if (!conf_modules_finish_int()) /* also inits module list lock */
489        return;
490
491    if (!CRYPTO_THREAD_write_lock(module_list_lock))
492        return;
493
494    /* unload modules in reverse order */
495    for (i = sk_CONF_MODULE_num(supported_modules) - 1; i >= 0; i--) {
496        md = sk_CONF_MODULE_value(supported_modules, i);
497        /* If static or in use and 'all' not set ignore it */
498        if (((md->links > 0) || !md->dso) && !all)
499            continue;
500        /* Since we're working in reverse this is OK */
501        (void)sk_CONF_MODULE_delete(supported_modules, i);
502        module_free(md);
503    }
504
505    if (sk_CONF_MODULE_num(supported_modules) == 0) {
506        sk_CONF_MODULE_free(supported_modules);
507        supported_modules = NULL;
508    }
509
510    CRYPTO_THREAD_unlock(module_list_lock);
511}
512
513/* unload a single module */
514static void module_free(CONF_MODULE *md)
515{
516    DSO_free(md->dso);
517    OPENSSL_free(md->name);
518    OPENSSL_free(md);
519}
520
521/* finish and free up all modules instances */
522
523static int conf_modules_finish_int(void)
524{
525    CONF_IMODULE *imod;
526
527    if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock))
528        return 0;
529
530    /* If module_list_lock is NULL here it means we were already unloaded */
531    if (module_list_lock == NULL
532        || !CRYPTO_THREAD_write_lock(module_list_lock))
533        return 0;
534
535    while (sk_CONF_IMODULE_num(initialized_modules) > 0) {
536        imod = sk_CONF_IMODULE_pop(initialized_modules);
537        module_finish(imod);
538    }
539    sk_CONF_IMODULE_free(initialized_modules);
540    initialized_modules = NULL;
541
542    CRYPTO_THREAD_unlock(module_list_lock);
543
544    return 1;
545}
546
547void CONF_modules_finish(void)
548{
549    conf_modules_finish_int();
550}
551
552/* finish a module instance */
553
554static void module_finish(CONF_IMODULE *imod)
555{
556    if (!imod)
557        return;
558    if (imod->pmod->finish)
559        imod->pmod->finish(imod);
560    imod->pmod->links--;
561    OPENSSL_free(imod->name);
562    OPENSSL_free(imod->value);
563    OPENSSL_free(imod);
564}
565
566/* Add a static module to OpenSSL */
567
568int CONF_module_add(const char *name, conf_init_func *ifunc,
569                    conf_finish_func *ffunc)
570{
571    if (module_add(NULL, name, ifunc, ffunc))
572        return 1;
573    else
574        return 0;
575}
576
577void ossl_config_modules_free(void)
578{
579    CONF_modules_unload(1); /* calls CONF_modules_finish */
580    module_lists_free();
581}
582
583/* Utility functions */
584
585const char *CONF_imodule_get_name(const CONF_IMODULE *md)
586{
587    return md->name;
588}
589
590const char *CONF_imodule_get_value(const CONF_IMODULE *md)
591{
592    return md->value;
593}
594
595void *CONF_imodule_get_usr_data(const CONF_IMODULE *md)
596{
597    return md->usr_data;
598}
599
600void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data)
601{
602    md->usr_data = usr_data;
603}
604
605CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md)
606{
607    return md->pmod;
608}
609
610unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md)
611{
612    return md->flags;
613}
614
615void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags)
616{
617    md->flags = flags;
618}
619
620void *CONF_module_get_usr_data(CONF_MODULE *pmod)
621{
622    return pmod->usr_data;
623}
624
625void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data)
626{
627    pmod->usr_data = usr_data;
628}
629
630/* Return default config file name */
631char *CONF_get1_default_config_file(void)
632{
633    const char *t;
634    char *file, *sep = "";
635    size_t size;
636
637    if ((file = ossl_safe_getenv("OPENSSL_CONF")) != NULL)
638        return OPENSSL_strdup(file);
639
640    t = X509_get_default_cert_area();
641#ifndef OPENSSL_SYS_VMS
642    sep = "/";
643#endif
644    size = strlen(t) + strlen(sep) + strlen(OPENSSL_CONF) + 1;
645    file = OPENSSL_malloc(size);
646
647    if (file == NULL)
648        return NULL;
649    BIO_snprintf(file, size, "%s%s%s", t, sep, OPENSSL_CONF);
650
651    return file;
652}
653
654/*
655 * This function takes a list separated by 'sep' and calls the callback
656 * function giving the start and length of each member optionally stripping
657 * leading and trailing whitespace. This can be used to parse comma separated
658 * lists for example.
659 */
660
661int CONF_parse_list(const char *list_, int sep, int nospc,
662                    int (*list_cb) (const char *elem, int len, void *usr),
663                    void *arg)
664{
665    int ret;
666    const char *lstart, *tmpend, *p;
667
668    if (list_ == NULL) {
669        ERR_raise(ERR_LIB_CONF, CONF_R_LIST_CANNOT_BE_NULL);
670        return 0;
671    }
672
673    lstart = list_;
674    for (;;) {
675        if (nospc) {
676            while (*lstart && isspace((unsigned char)*lstart))
677                lstart++;
678        }
679        p = strchr(lstart, sep);
680        if (p == lstart || *lstart == '\0')
681            ret = list_cb(NULL, 0, arg);
682        else {
683            if (p)
684                tmpend = p - 1;
685            else
686                tmpend = lstart + strlen(lstart) - 1;
687            if (nospc) {
688                while (isspace((unsigned char)*tmpend))
689                    tmpend--;
690            }
691            ret = list_cb(lstart, tmpend - lstart + 1, arg);
692        }
693        if (ret <= 0)
694            return ret;
695        if (p == NULL)
696            return 1;
697        lstart = p + 1;
698    }
699}
700