Always check CRYPTO_LOCK_{read,write}_lock
[openssl.git] / crypto / core_namemap.c
1 /*
2  * Copyright 2019-2021 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 "e_os.h"                /* strcasecmp */
11 #include "internal/namemap.h"
12 #include <openssl/lhash.h>
13 #include "crypto/lhash.h"      /* openssl_lh_strcasehash */
14 #include "internal/tsan_assist.h"
15
16 /*-
17  * The namenum entry
18  * =================
19  */
20 typedef struct {
21     char *name;
22     int number;
23 } NAMENUM_ENTRY;
24
25 DEFINE_LHASH_OF(NAMENUM_ENTRY);
26
27 /*-
28  * The namemap itself
29  * ==================
30  */
31
32 struct ossl_namemap_st {
33     /* Flags */
34     unsigned int stored:1; /* If 1, it's stored in a library context */
35
36     CRYPTO_RWLOCK *lock;
37     LHASH_OF(NAMENUM_ENTRY) *namenum;  /* Name->number mapping */
38
39 #ifdef tsan_ld_acq
40     TSAN_QUALIFIER int max_number;     /* Current max number TSAN version */
41 #else
42     int max_number;                    /* Current max number plain version */
43 #endif
44 };
45
46 /* LHASH callbacks */
47
48 static unsigned long namenum_hash(const NAMENUM_ENTRY *n)
49 {
50     return openssl_lh_strcasehash(n->name);
51 }
52
53 static int namenum_cmp(const NAMENUM_ENTRY *a, const NAMENUM_ENTRY *b)
54 {
55     return strcasecmp(a->name, b->name);
56 }
57
58 static void namenum_free(NAMENUM_ENTRY *n)
59 {
60     if (n != NULL)
61         OPENSSL_free(n->name);
62     OPENSSL_free(n);
63 }
64
65 /* OSSL_LIB_CTX_METHOD functions for a namemap stored in a library context */
66
67 static void *stored_namemap_new(OSSL_LIB_CTX *libctx)
68 {
69     OSSL_NAMEMAP *namemap = ossl_namemap_new();
70
71     if (namemap != NULL)
72         namemap->stored = 1;
73
74     return namemap;
75 }
76
77 static void stored_namemap_free(void *vnamemap)
78 {
79     OSSL_NAMEMAP *namemap = vnamemap;
80
81     if (namemap != NULL) {
82         /* Pretend it isn't stored, or ossl_namemap_free() will do nothing */
83         namemap->stored = 0;
84         ossl_namemap_free(namemap);
85     }
86 }
87
88 static const OSSL_LIB_CTX_METHOD stored_namemap_method = {
89     stored_namemap_new,
90     stored_namemap_free,
91 };
92
93 /*-
94  * API functions
95  * =============
96  */
97
98 int ossl_namemap_empty(OSSL_NAMEMAP *namemap)
99 {
100 #ifdef tsan_ld_acq
101     /* Have TSAN support */
102     return namemap == NULL || tsan_load(&namemap->max_number) == 0;
103 #else
104     /* No TSAN support */
105     int rv;
106
107     if (namemap == NULL)
108         return 1;
109
110     if (!CRYPTO_THREAD_read_lock(namemap->lock))
111         return -1;
112     rv = namemap->max_number == 0;
113     CRYPTO_THREAD_unlock(namemap->lock);
114     return rv;
115 #endif
116 }
117
118 typedef struct doall_names_data_st {
119     int number;
120     const char **names;
121     int found;
122 } DOALL_NAMES_DATA;
123
124 static void do_name(const NAMENUM_ENTRY *namenum, DOALL_NAMES_DATA *data)
125 {
126     if (namenum->number == data->number)
127         data->names[data->found++] = namenum->name;
128 }
129
130 IMPLEMENT_LHASH_DOALL_ARG_CONST(NAMENUM_ENTRY, DOALL_NAMES_DATA);
131
132 /*
133  * Call the callback for all names in the namemap with the given number.
134  * A return value 1 means that the callback was called for all names. A
135  * return value of 0 means that the callback was not called for any names.
136  */
137 int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number,
138                              void (*fn)(const char *name, void *data),
139                              void *data)
140 {
141     DOALL_NAMES_DATA cbdata;
142     size_t num_names;
143     int i;
144
145     cbdata.number = number;
146     cbdata.found = 0;
147
148     /*
149      * We collect all the names first under a read lock. Subsequently we call
150      * the user function, so that we're not holding the read lock when in user
151      * code. This could lead to deadlocks.
152      */
153     if (!CRYPTO_THREAD_read_lock(namemap->lock))
154         return 0;
155
156     num_names = lh_NAMENUM_ENTRY_num_items(namemap->namenum);
157     if (num_names == 0) {
158         CRYPTO_THREAD_unlock(namemap->lock);
159         return 0;
160     }
161     cbdata.names = OPENSSL_malloc(sizeof(*cbdata.names) * num_names);
162     if (cbdata.names == NULL) {
163         CRYPTO_THREAD_unlock(namemap->lock);
164         return 0;
165     }
166     lh_NAMENUM_ENTRY_doall_DOALL_NAMES_DATA(namemap->namenum, do_name,
167                                             &cbdata);
168     CRYPTO_THREAD_unlock(namemap->lock);
169
170     for (i = 0; i < cbdata.found; i++)
171         fn(cbdata.names[i], data);
172
173     OPENSSL_free(cbdata.names);
174     return 1;
175 }
176
177 static int namemap_name2num_n(const OSSL_NAMEMAP *namemap,
178                               const char *name, size_t name_len)
179 {
180     NAMENUM_ENTRY *namenum_entry, namenum_tmpl;
181
182     if ((namenum_tmpl.name = OPENSSL_strndup(name, name_len)) == NULL)
183         return 0;
184     namenum_tmpl.number = 0;
185     namenum_entry =
186         lh_NAMENUM_ENTRY_retrieve(namemap->namenum, &namenum_tmpl);
187     OPENSSL_free(namenum_tmpl.name);
188     return namenum_entry != NULL ? namenum_entry->number : 0;
189 }
190
191 int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
192                             const char *name, size_t name_len)
193 {
194     int number;
195
196 #ifndef FIPS_MODULE
197     if (namemap == NULL)
198         namemap = ossl_namemap_stored(NULL);
199 #endif
200
201     if (namemap == NULL)
202         return 0;
203
204     if (!CRYPTO_THREAD_read_lock(namemap->lock))
205         return 0;
206     number = namemap_name2num_n(namemap, name, name_len);
207     CRYPTO_THREAD_unlock(namemap->lock);
208
209     return number;
210 }
211
212 int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name)
213 {
214     if (name == NULL)
215         return 0;
216
217     return ossl_namemap_name2num_n(namemap, name, strlen(name));
218 }
219
220 struct num2name_data_st {
221     size_t idx;                  /* Countdown */
222     const char *name;            /* Result */
223 };
224
225 static void do_num2name(const char *name, void *vdata)
226 {
227     struct num2name_data_st *data = vdata;
228
229     if (data->idx > 0)
230         data->idx--;
231     else if (data->name == NULL)
232         data->name = name;
233 }
234
235 const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
236                                   size_t idx)
237 {
238     struct num2name_data_st data;
239
240     data.idx = idx;
241     data.name = NULL;
242     if (!ossl_namemap_doall_names(namemap, number, do_num2name, &data))
243         return NULL;
244     return data.name;
245 }
246
247 static int namemap_add_name_n(OSSL_NAMEMAP *namemap, int number,
248                               const char *name, size_t name_len)
249 {
250     NAMENUM_ENTRY *namenum = NULL;
251     int tmp_number;
252
253     /* If it already exists, we don't add it */
254     if ((tmp_number = namemap_name2num_n(namemap, name, name_len)) != 0)
255         return tmp_number;
256
257     if ((namenum = OPENSSL_zalloc(sizeof(*namenum))) == NULL
258         || (namenum->name = OPENSSL_strndup(name, name_len)) == NULL)
259         goto err;
260
261     namenum->number =
262         number != 0 ? number : 1 + tsan_counter(&namemap->max_number);
263     (void)lh_NAMENUM_ENTRY_insert(namemap->namenum, namenum);
264
265     if (lh_NAMENUM_ENTRY_error(namemap->namenum))
266         goto err;
267     return namenum->number;
268
269  err:
270     namenum_free(namenum);
271     return 0;
272 }
273
274 int ossl_namemap_add_name_n(OSSL_NAMEMAP *namemap, int number,
275                             const char *name, size_t name_len)
276 {
277     int tmp_number;
278
279 #ifndef FIPS_MODULE
280     if (namemap == NULL)
281         namemap = ossl_namemap_stored(NULL);
282 #endif
283
284     if (name == NULL || name_len == 0 || namemap == NULL)
285         return 0;
286
287     if (!CRYPTO_THREAD_write_lock(namemap->lock))
288         return 0;
289     tmp_number = namemap_add_name_n(namemap, number, name, name_len);
290     CRYPTO_THREAD_unlock(namemap->lock);
291     return tmp_number;
292 }
293
294 int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number, const char *name)
295 {
296     if (name == NULL)
297         return 0;
298
299     return ossl_namemap_add_name_n(namemap, number, name, strlen(name));
300 }
301
302 int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number,
303                            const char *names, const char separator)
304 {
305     const char *p, *q;
306     size_t l;
307
308     /* Check that we have a namemap */
309     if (!ossl_assert(namemap != NULL)) {
310         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
311         return 0;
312     }
313
314     if (!CRYPTO_THREAD_write_lock(namemap->lock))
315         return 0;
316     /*
317      * Check that no name is an empty string, and that all names have at
318      * most one numeric identity together.
319      */
320     for (p = names; *p != '\0'; p = (q == NULL ? p + l : q + 1)) {
321         int this_number;
322
323         if ((q = strchr(p, separator)) == NULL)
324             l = strlen(p);       /* offset to \0 */
325         else
326             l = q - p;           /* offset to the next separator */
327
328         this_number = namemap_name2num_n(namemap, p, l);
329
330         if (*p == '\0' || *p == separator) {
331             ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_BAD_ALGORITHM_NAME);
332             goto err;
333         }
334         if (number == 0) {
335             number = this_number;
336         } else if (this_number != 0 && this_number != number) {
337             ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_CONFLICTING_NAMES,
338                            "\"%.*s\" has an existing different identity %d (from \"%s\")",
339                            l, p, this_number, names);
340             goto err;
341         }
342     }
343
344     /* Now that we have checked, register all names */
345     for (p = names; *p != '\0'; p = (q == NULL ? p + l : q + 1)) {
346         int this_number;
347
348         if ((q = strchr(p, separator)) == NULL)
349             l = strlen(p);       /* offset to \0 */
350         else
351             l = q - p;           /* offset to the next separator */
352
353         this_number = namemap_add_name_n(namemap, number, p, l);
354         if (number == 0) {
355             number = this_number;
356         } else if (this_number != number) {
357             ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
358                            "Got number %d when expecting %d",
359                            this_number, number);
360             goto err;
361         }
362     }
363
364     CRYPTO_THREAD_unlock(namemap->lock);
365     return number;
366
367  err:
368     CRYPTO_THREAD_unlock(namemap->lock);
369     return 0;
370 }
371
372 /*-
373  * Pre-population
374  * ==============
375  */
376
377 #ifndef FIPS_MODULE
378 #include <openssl/evp.h>
379
380 /* Creates an initial namemap with names found in the legacy method db */
381 static void get_legacy_evp_names(const char *main_name, const char *alias,
382                                  void *arg)
383 {
384     int main_id = ossl_namemap_add_name(arg, 0, main_name);
385
386     /*
387      * We could check that the returned value is the same as main_id,
388      * but since this is a void function, there's no sane way to report
389      * the error.  The best we can do is trust ourselve to keep the legacy
390      * method database conflict free.
391      *
392      * This registers any alias with the same number as the main name.
393      * Should it be that the current |on| *has* the main name, this is
394      * simply a no-op.
395      */
396     if (alias != NULL) {
397         (void)ossl_namemap_add_name(arg, main_id, alias);
398     }
399 }
400
401 static void get_legacy_cipher_names(const OBJ_NAME *on, void *arg)
402 {
403     const EVP_CIPHER *cipher = (void *)OBJ_NAME_get(on->name, on->type);
404
405     get_legacy_evp_names(EVP_CIPHER_name(cipher), on->name, arg);
406 }
407
408 static void get_legacy_md_names(const OBJ_NAME *on, void *arg)
409 {
410     const EVP_MD *md = (void *)OBJ_NAME_get(on->name, on->type);
411     /* We don't want the pkey_type names, so we need some extra care */
412     int snid, lnid;
413
414     snid = OBJ_sn2nid(on->name);
415     lnid = OBJ_ln2nid(on->name);
416     if (snid != EVP_MD_pkey_type(md) && lnid != EVP_MD_pkey_type(md))
417         get_legacy_evp_names(EVP_MD_name(md), on->name, arg);
418     else
419         get_legacy_evp_names(EVP_MD_name(md), NULL, arg);
420 }
421 #endif
422
423 /*-
424  * Constructors / destructors
425  * ==========================
426  */
427
428 OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx)
429 {
430 #ifndef FIPS_MODULE
431     int nms;
432 #endif
433     OSSL_NAMEMAP *namemap =
434         ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_NAMEMAP_INDEX,
435                               &stored_namemap_method);
436
437     if (namemap == NULL)
438         return NULL;
439
440 #ifndef FIPS_MODULE
441     nms = ossl_namemap_empty(namemap);
442     if (nms < 0) {
443         /*
444          * Could not get lock to make the count, so maybe internal objects
445          * weren't added. This seems safest.
446          */
447         return NULL;
448     }
449     if (nms == 1) {
450         /* Before pilfering, we make sure the legacy database is populated */
451         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
452                             | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
453
454         OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH,
455                         get_legacy_cipher_names, namemap);
456         OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH,
457                         get_legacy_md_names, namemap);
458     }
459 #endif
460
461     return namemap;
462 }
463
464 OSSL_NAMEMAP *ossl_namemap_new(void)
465 {
466     OSSL_NAMEMAP *namemap;
467
468     if ((namemap = OPENSSL_zalloc(sizeof(*namemap))) != NULL
469         && (namemap->lock = CRYPTO_THREAD_lock_new()) != NULL
470         && (namemap->namenum =
471             lh_NAMENUM_ENTRY_new(namenum_hash, namenum_cmp)) != NULL)
472         return namemap;
473
474     ossl_namemap_free(namemap);
475     return NULL;
476 }
477
478 void ossl_namemap_free(OSSL_NAMEMAP *namemap)
479 {
480     if (namemap == NULL || namemap->stored)
481         return;
482
483     lh_NAMENUM_ENTRY_doall(namemap->namenum, namenum_free);
484     lh_NAMENUM_ENTRY_free(namemap->namenum);
485
486     CRYPTO_THREAD_lock_free(namemap->lock);
487     OPENSSL_free(namemap);
488 }