xref: /openssl/crypto/core_namemap.c (revision 7ed6de99)
1 /*
2  * Copyright 2019-2024 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 "internal/namemap.h"
11 #include "internal/tsan_assist.h"
12 #include "internal/hashtable.h"
13 #include "internal/sizes.h"
14 #include "crypto/context.h"
15 
16 #define NAMEMAP_HT_BUCKETS 2048
17 
18 HT_START_KEY_DEFN(namenum_key)
19 HT_DEF_KEY_FIELD_CHAR_ARRAY(name, 64)
20 HT_END_KEY_DEFN(NAMENUM_KEY)
21 
22 /*-
23  * The namemap itself
24  * ==================
25  */
26 
27 typedef char STRING;
28 typedef STACK_OF(STRING) NAMES;
29 
30 DEFINE_STACK_OF(STRING)
31 DEFINE_STACK_OF(NAMES)
32 
33 struct ossl_namemap_st {
34     /* Flags */
35     unsigned int stored:1; /* If 1, it's stored in a library context */
36 
37     HT *namenum_ht;        /* Name->number mapping */
38 
39     CRYPTO_RWLOCK *lock;
40     STACK_OF(NAMES) *numnames;
41 
42     TSAN_QUALIFIER int max_number;     /* Current max number */
43 };
44 
name_string_free(char * name)45 static void name_string_free(char *name)
46 {
47     OPENSSL_free(name);
48 }
49 
names_free(NAMES * n)50 static void names_free(NAMES *n)
51 {
52     sk_STRING_pop_free(n, name_string_free);
53 }
54 
55 /* OSSL_LIB_CTX_METHOD functions for a namemap stored in a library context */
56 
ossl_stored_namemap_new(OSSL_LIB_CTX * libctx)57 void *ossl_stored_namemap_new(OSSL_LIB_CTX *libctx)
58 {
59     OSSL_NAMEMAP *namemap = ossl_namemap_new(libctx);
60 
61     if (namemap != NULL)
62         namemap->stored = 1;
63 
64     return namemap;
65 }
66 
ossl_stored_namemap_free(void * vnamemap)67 void ossl_stored_namemap_free(void *vnamemap)
68 {
69     OSSL_NAMEMAP *namemap = vnamemap;
70 
71     if (namemap != NULL) {
72         /* Pretend it isn't stored, or ossl_namemap_free() will do nothing */
73         namemap->stored = 0;
74         ossl_namemap_free(namemap);
75     }
76 }
77 
78 /*-
79  * API functions
80  * =============
81  */
82 
ossl_namemap_empty(OSSL_NAMEMAP * namemap)83 int ossl_namemap_empty(OSSL_NAMEMAP *namemap)
84 {
85 #ifdef TSAN_REQUIRES_LOCKING
86     /* No TSAN support */
87     int rv;
88 
89     if (namemap == NULL)
90         return 1;
91 
92     if (!CRYPTO_THREAD_read_lock(namemap->lock))
93         return -1;
94     rv = namemap->max_number == 0;
95     CRYPTO_THREAD_unlock(namemap->lock);
96     return rv;
97 #else
98     /* Have TSAN support */
99     return namemap == NULL || tsan_load(&namemap->max_number) == 0;
100 #endif
101 }
102 
103 /*
104  * Call the callback for all names in the namemap with the given number.
105  * A return value 1 means that the callback was called for all names. A
106  * return value of 0 means that the callback was not called for any names.
107  */
ossl_namemap_doall_names(const OSSL_NAMEMAP * namemap,int number,void (* fn)(const char * name,void * data),void * data)108 int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number,
109                              void (*fn)(const char *name, void *data),
110                              void *data)
111 {
112     int i;
113     NAMES *names;
114 
115     if (namemap == NULL || number <= 0)
116         return 0;
117 
118     /*
119      * We duplicate the NAMES stack under a read lock. Subsequently we call
120      * the user function, so that we're not holding the read lock when in user
121      * code. This could lead to deadlocks.
122      */
123     if (!CRYPTO_THREAD_read_lock(namemap->lock))
124         return 0;
125 
126     names = sk_NAMES_value(namemap->numnames, number - 1);
127     if (names != NULL)
128         names = sk_STRING_dup(names);
129 
130     CRYPTO_THREAD_unlock(namemap->lock);
131 
132     if (names == NULL)
133         return 0;
134 
135     for (i = 0; i < sk_STRING_num(names); i++)
136         fn(sk_STRING_value(names, i), data);
137 
138     sk_STRING_free(names);
139     return i > 0;
140 }
141 
ossl_namemap_name2num(const OSSL_NAMEMAP * namemap,const char * name)142 int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name)
143 {
144     int number = 0;
145     HT_VALUE *val;
146     NAMENUM_KEY key;
147 
148 #ifndef FIPS_MODULE
149     if (namemap == NULL)
150         namemap = ossl_namemap_stored(NULL);
151 #endif
152 
153     if (namemap == NULL)
154         return 0;
155 
156     HT_INIT_KEY(&key);
157     HT_SET_KEY_STRING_CASE(&key, name, name);
158 
159     val = ossl_ht_get(namemap->namenum_ht, TO_HT_KEY(&key));
160 
161     if (val != NULL)
162         /* We store a (small) int directly instead of a pointer to it. */
163         number = (int)(intptr_t)val->value;
164 
165     return number;
166 }
167 
168 /* TODO: Optimize to avoid strndup() */
ossl_namemap_name2num_n(const OSSL_NAMEMAP * namemap,const char * name,size_t name_len)169 int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
170                             const char *name, size_t name_len)
171 {
172     char *tmp;
173     int ret;
174 
175     if (name == NULL || (tmp = OPENSSL_strndup(name, name_len)) == NULL)
176         return 0;
177 
178     ret = ossl_namemap_name2num(namemap, tmp);
179     OPENSSL_free(tmp);
180     return ret;
181 }
182 
ossl_namemap_num2name(const OSSL_NAMEMAP * namemap,int number,size_t idx)183 const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
184                                   size_t idx)
185 {
186     NAMES *names;
187     const char *ret = NULL;
188 
189     if (namemap == NULL || number <= 0)
190         return NULL;
191 
192     if (!CRYPTO_THREAD_read_lock(namemap->lock))
193         return NULL;
194 
195     names = sk_NAMES_value(namemap->numnames, number - 1);
196     if (names != NULL)
197         ret = sk_STRING_value(names, idx);
198 
199     CRYPTO_THREAD_unlock(namemap->lock);
200 
201     return ret;
202 }
203 
204 /* This function is not thread safe, the namemap must be locked */
numname_insert(OSSL_NAMEMAP * namemap,int number,const char * name)205 static int numname_insert(OSSL_NAMEMAP *namemap, int number,
206                           const char *name)
207 {
208     NAMES *names;
209     char *tmpname;
210 
211     if (number > 0) {
212         names = sk_NAMES_value(namemap->numnames, number - 1);
213         if (!ossl_assert(names != NULL)) {
214             /* cannot happen */
215             return 0;
216         }
217     } else {
218         /* a completely new entry */
219         names = sk_STRING_new_null();
220         if (names == NULL)
221             return 0;
222     }
223 
224     if ((tmpname = OPENSSL_strdup(name)) == NULL)
225         goto err;
226 
227     if (!sk_STRING_push(names, tmpname))
228         goto err;
229 
230     if (number <= 0) {
231         if (!sk_NAMES_push(namemap->numnames, names))
232             goto err;
233         number = sk_NAMES_num(namemap->numnames);
234     }
235     return number;
236 
237  err:
238     if (number <= 0)
239         sk_STRING_free(names);
240     OPENSSL_free(tmpname);
241     return 0;
242 }
243 
244 /* This function is not thread safe, the namemap must be locked */
namemap_add_name(OSSL_NAMEMAP * namemap,int number,const char * name)245 static int namemap_add_name(OSSL_NAMEMAP *namemap, int number,
246                             const char *name)
247 {
248     int ret;
249     HT_VALUE val = { 0 };
250     NAMENUM_KEY key;
251 
252     /* If it already exists, we don't add it */
253     if ((ret = ossl_namemap_name2num(namemap, name)) != 0)
254         return ret;
255 
256     if ((number = numname_insert(namemap, number, name)) == 0)
257         return 0;
258 
259     /* Using tsan_store alone here is safe since we're under lock */
260     tsan_store(&namemap->max_number, number);
261 
262     HT_INIT_KEY(&key);
263     HT_SET_KEY_STRING_CASE(&key, name, name);
264     val.value = (void *)(intptr_t)number;
265     ret = ossl_ht_insert(namemap->namenum_ht, TO_HT_KEY(&key), &val, NULL);
266     if (!ossl_assert(ret != 0)) /* cannot happen as we are under write lock */
267         return 0;
268     if (ret < 1) {
269         /* unable to insert due to too many collisions */
270         ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_NAMES);
271         return 0;
272     }
273     return number;
274 }
275 
ossl_namemap_add_name(OSSL_NAMEMAP * namemap,int number,const char * name)276 int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number,
277                           const char *name)
278 {
279     int tmp_number;
280 
281 #ifndef FIPS_MODULE
282     if (namemap == NULL)
283         namemap = ossl_namemap_stored(NULL);
284 #endif
285 
286     if (name == NULL || *name == 0 || namemap == NULL)
287         return 0;
288 
289     if (!CRYPTO_THREAD_write_lock(namemap->lock))
290         return 0;
291     tmp_number = namemap_add_name(namemap, number, name);
292     CRYPTO_THREAD_unlock(namemap->lock);
293     return tmp_number;
294 }
295 
ossl_namemap_add_names(OSSL_NAMEMAP * namemap,int number,const char * names,const char separator)296 int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number,
297                            const char *names, const char separator)
298 {
299     char *tmp, *p, *q, *endp;
300 
301     /* Check that we have a namemap */
302     if (!ossl_assert(namemap != NULL)) {
303         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
304         return 0;
305     }
306 
307     if ((tmp = OPENSSL_strdup(names)) == NULL)
308         return 0;
309 
310     if (!CRYPTO_THREAD_write_lock(namemap->lock)) {
311         OPENSSL_free(tmp);
312         return 0;
313     }
314     /*
315      * Check that no name is an empty string, and that all names have at
316      * most one numeric identity together.
317      */
318     for (p = tmp; *p != '\0'; p = q) {
319         int this_number;
320         size_t l;
321 
322         if ((q = strchr(p, separator)) == NULL) {
323             l = strlen(p);       /* offset to \0 */
324             q = p + l;
325         } else {
326             l = q - p;           /* offset to the next separator */
327             *q++ = '\0';
328         }
329 
330         if (*p == '\0') {
331             ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_BAD_ALGORITHM_NAME);
332             number = 0;
333             goto end;
334         }
335 
336         this_number = ossl_namemap_name2num(namemap, p);
337 
338         if (number == 0) {
339             number = this_number;
340         } else if (this_number != 0 && this_number != number) {
341             ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_CONFLICTING_NAMES,
342                            "\"%s\" has an existing different identity %d (from \"%s\")",
343                            p, this_number, names);
344             number = 0;
345             goto end;
346         }
347     }
348     endp = p;
349 
350     /* Now that we have checked, register all names */
351     for (p = tmp; p < endp; p = q) {
352         int this_number;
353 
354         q = p + strlen(p) + 1;
355 
356         this_number = namemap_add_name(namemap, number, p);
357         if (number == 0) {
358             number = this_number;
359         } else if (this_number != number) {
360             ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
361                            "Got number %d when expecting %d",
362                            this_number, number);
363             number = 0;
364             goto end;
365         }
366     }
367 
368  end:
369     CRYPTO_THREAD_unlock(namemap->lock);
370     OPENSSL_free(tmp);
371     return number;
372 }
373 
374 /*-
375  * Pre-population
376  * ==============
377  */
378 
379 #ifndef FIPS_MODULE
380 #include <openssl/evp.h>
381 
382 /* Creates an initial namemap with names found in the legacy method db */
get_legacy_evp_names(int base_nid,int nid,const char * pem_name,void * arg)383 static void get_legacy_evp_names(int base_nid, int nid, const char *pem_name,
384                                  void *arg)
385 {
386     int num = 0;
387     ASN1_OBJECT *obj;
388 
389     if (base_nid != NID_undef) {
390         num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(base_nid));
391         num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(base_nid));
392     }
393 
394     if (nid != NID_undef) {
395         num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(nid));
396         num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(nid));
397         if ((obj = OBJ_nid2obj(nid)) != NULL) {
398             char txtoid[OSSL_MAX_NAME_SIZE];
399 
400             if (OBJ_obj2txt(txtoid, sizeof(txtoid), obj, 1) > 0)
401                 num = ossl_namemap_add_name(arg, num, txtoid);
402         }
403     }
404     if (pem_name != NULL)
405         num = ossl_namemap_add_name(arg, num, pem_name);
406 }
407 
get_legacy_cipher_names(const OBJ_NAME * on,void * arg)408 static void get_legacy_cipher_names(const OBJ_NAME *on, void *arg)
409 {
410     const EVP_CIPHER *cipher = (void *)OBJ_NAME_get(on->name, on->type);
411 
412     if (cipher != NULL)
413         get_legacy_evp_names(NID_undef, EVP_CIPHER_get_type(cipher), NULL, arg);
414 }
415 
get_legacy_md_names(const OBJ_NAME * on,void * arg)416 static void get_legacy_md_names(const OBJ_NAME *on, void *arg)
417 {
418     const EVP_MD *md = (void *)OBJ_NAME_get(on->name, on->type);
419 
420     if (md != NULL)
421         get_legacy_evp_names(0, EVP_MD_get_type(md), NULL, arg);
422 }
423 
get_legacy_pkey_meth_names(const EVP_PKEY_ASN1_METHOD * ameth,void * arg)424 static void get_legacy_pkey_meth_names(const EVP_PKEY_ASN1_METHOD *ameth,
425                                        void *arg)
426 {
427     int nid = 0, base_nid = 0, flags = 0;
428     const char *pem_name = NULL;
429 
430     EVP_PKEY_asn1_get0_info(&nid, &base_nid, &flags, NULL, &pem_name, ameth);
431     if (nid != NID_undef) {
432         if ((flags & ASN1_PKEY_ALIAS) == 0) {
433             switch (nid) {
434             case EVP_PKEY_DHX:
435                 /* We know that the name "DHX" is used too */
436                 get_legacy_evp_names(0, nid, "DHX", arg);
437                 /* FALLTHRU */
438             default:
439                 get_legacy_evp_names(0, nid, pem_name, arg);
440             }
441         } else {
442             /*
443              * Treat aliases carefully, some of them are undesirable, or
444              * should not be treated as such for providers.
445              */
446 
447             switch (nid) {
448             case EVP_PKEY_SM2:
449                 /*
450                  * SM2 is a separate keytype with providers, not an alias for
451                  * EC.
452                  */
453                 get_legacy_evp_names(0, nid, pem_name, arg);
454                 break;
455             default:
456                 /* Use the short name of the base nid as the common reference */
457                 get_legacy_evp_names(base_nid, nid, pem_name, arg);
458             }
459         }
460     }
461 }
462 #endif
463 
464 /*-
465  * Constructors / destructors
466  * ==========================
467  */
468 
ossl_namemap_stored(OSSL_LIB_CTX * libctx)469 OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx)
470 {
471 #ifndef FIPS_MODULE
472     int nms;
473 #endif
474     OSSL_NAMEMAP *namemap =
475         ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_NAMEMAP_INDEX);
476 
477     if (namemap == NULL)
478         return NULL;
479 
480 #ifndef FIPS_MODULE
481     nms = ossl_namemap_empty(namemap);
482     if (nms < 0) {
483         /*
484          * Could not get lock to make the count, so maybe internal objects
485          * weren't added. This seems safest.
486          */
487         return NULL;
488     }
489     if (nms == 1) {
490         int i, end;
491 
492         /* Before pilfering, we make sure the legacy database is populated */
493         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
494                             | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
495 
496         OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH,
497                         get_legacy_cipher_names, namemap);
498         OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH,
499                         get_legacy_md_names, namemap);
500 
501         /* We also pilfer data from the legacy EVP_PKEY_ASN1_METHODs */
502         for (i = 0, end = EVP_PKEY_asn1_get_count(); i < end; i++)
503             get_legacy_pkey_meth_names(EVP_PKEY_asn1_get0(i), namemap);
504     }
505 #endif
506 
507     return namemap;
508 }
509 
ossl_namemap_new(OSSL_LIB_CTX * libctx)510 OSSL_NAMEMAP *ossl_namemap_new(OSSL_LIB_CTX *libctx)
511 {
512     OSSL_NAMEMAP *namemap;
513     HT_CONFIG htconf = { NULL, NULL, NULL, NAMEMAP_HT_BUCKETS, 1, 1 };
514 
515     htconf.ctx = libctx;
516 
517     if ((namemap = OPENSSL_zalloc(sizeof(*namemap))) == NULL)
518         goto err;
519 
520     if ((namemap->lock = CRYPTO_THREAD_lock_new()) == NULL)
521         goto err;
522 
523     if ((namemap->namenum_ht = ossl_ht_new(&htconf)) == NULL)
524         goto err;
525 
526     if ((namemap->numnames = sk_NAMES_new_null()) == NULL)
527         goto err;
528 
529     return namemap;
530 
531  err:
532     ossl_namemap_free(namemap);
533     return NULL;
534 }
535 
ossl_namemap_free(OSSL_NAMEMAP * namemap)536 void ossl_namemap_free(OSSL_NAMEMAP *namemap)
537 {
538     if (namemap == NULL || namemap->stored)
539         return;
540 
541     sk_NAMES_pop_free(namemap->numnames, names_free);
542 
543     ossl_ht_free(namemap->namenum_ht);
544 
545     CRYPTO_THREAD_lock_free(namemap->lock);
546     OPENSSL_free(namemap);
547 }
548