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