fix x509_PUBKEY propq so that it uses a copy
[openssl.git] / crypto / x509 / x_pubkey.c
1 /*
2  * Copyright 1995-2020 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 /*
11  * DSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include <openssl/asn1t.h>
19 #include <openssl/x509.h>
20 #include "crypto/asn1.h"
21 #include "crypto/evp.h"
22 #include "crypto/x509.h"
23 #include <openssl/rsa.h>
24 #include <openssl/dsa.h>
25 #include <openssl/encoder.h>
26 #include "internal/provider.h"
27
28 struct X509_pubkey_st {
29     X509_ALGOR *algor;
30     ASN1_BIT_STRING *public_key;
31     EVP_PKEY *pkey;
32
33     /* extra data for the callback, used by d2i_PUBKEY_ex */
34     OSSL_LIB_CTX *libctx;
35     char *propq;
36 };
37
38 static int x509_pubkey_decode(EVP_PKEY **pk, const X509_PUBKEY *key);
39
40 static int x509_pubkey_set0_libctx(X509_PUBKEY *x, OSSL_LIB_CTX *libctx,
41                                    const char *propq)
42 {
43     if (x != NULL) {
44         x->libctx = libctx;
45         OPENSSL_free(x->propq);
46         x->propq = NULL;
47         if (propq != NULL) {
48             x->propq = OPENSSL_strdup(propq);
49             if (x->propq == NULL)
50                 return 0;
51         }
52     }
53     return 1;
54 }
55
56 /* Minor tweak to operation: free up EVP_PKEY */
57 static int pubkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
58                      void *exarg)
59 {
60     X509_PUBKEY *pubkey = (X509_PUBKEY *)*pval;
61
62     if (operation == ASN1_OP_FREE_POST) {
63         OPENSSL_free(pubkey->propq);
64         EVP_PKEY_free(pubkey->pkey);
65     } else if (operation == ASN1_OP_D2I_POST) {
66         /* Attempt to decode public key and cache in pubkey structure. */
67         EVP_PKEY_free(pubkey->pkey);
68         pubkey->pkey = NULL;
69         /*
70          * Opportunistically decode the key but remove any non fatal errors
71          * from the queue. Subsequent explicit attempts to decode/use the key
72          * will return an appropriate error.
73          */
74         ERR_set_mark();
75         if (x509_pubkey_decode(&pubkey->pkey, pubkey) == -1) {
76             ERR_clear_last_mark();
77             return 0;
78         }
79         ERR_pop_to_mark();
80     } else if (operation == ASN1_OP_DUP_POST) {
81         X509_PUBKEY *old = exarg;
82
83         if (!x509_pubkey_set0_libctx(pubkey, old->libctx, old->propq))
84             return 0;
85     }
86     return 1;
87 }
88
89 ASN1_SEQUENCE_cb(X509_PUBKEY, pubkey_cb) = {
90         ASN1_SIMPLE(X509_PUBKEY, algor, X509_ALGOR),
91         ASN1_SIMPLE(X509_PUBKEY, public_key, ASN1_BIT_STRING)
92 } ASN1_SEQUENCE_END_cb(X509_PUBKEY, X509_PUBKEY)
93
94 IMPLEMENT_ASN1_FUNCTIONS(X509_PUBKEY)
95 IMPLEMENT_ASN1_DUP_FUNCTION(X509_PUBKEY)
96
97 /* TODO should better be called X509_PUBKEY_set1 */
98 int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey)
99 {
100     X509_PUBKEY *pk = NULL;
101
102     if (x == NULL)
103         return 0;
104
105     if (pkey == NULL)
106         goto unsupported;
107
108     if (pkey->ameth != NULL) {
109         if ((pk = X509_PUBKEY_new()) == NULL) {
110             ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
111             goto error;
112         }
113         if (pkey->ameth->pub_encode != NULL) {
114             if (!pkey->ameth->pub_encode(pk, pkey)) {
115                 ERR_raise(ERR_LIB_X509, X509_R_PUBLIC_KEY_ENCODE_ERROR);
116                 goto error;
117             }
118         } else {
119             ERR_raise(ERR_LIB_X509, X509_R_METHOD_NOT_SUPPORTED);
120             goto error;
121         }
122     } else if (evp_pkey_is_provided(pkey)) {
123         unsigned char *der = NULL;
124         size_t derlen = 0;
125         OSSL_ENCODER_CTX *ectx =
126             OSSL_ENCODER_CTX_new_by_EVP_PKEY(pkey, EVP_PKEY_PUBLIC_KEY,
127                                              "DER", "SubjectPublicKeyInfo",
128                                              NULL);
129
130         if (OSSL_ENCODER_to_data(ectx, &der, &derlen)) {
131             const unsigned char *pder = der;
132
133             pk = d2i_X509_PUBKEY(NULL, &pder, (long)derlen);
134         }
135
136         OSSL_ENCODER_CTX_free(ectx);
137         OPENSSL_free(der);
138     }
139
140     if (pk == NULL)
141         goto unsupported;
142
143     X509_PUBKEY_free(*x);
144     if (!EVP_PKEY_up_ref(pkey)) {
145         ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
146         goto error;
147     }
148     *x = pk;
149
150     /*
151      * pk->pkey is NULL when using the legacy routine, but is non-NULL when
152      * going through the encoder, and for all intents and purposes, it's
153      * a perfect copy of |pkey|, just not the same instance.  In that case,
154      * we could simply return early, right here.
155      * However, in the interest of being cautious leaning on paranoia, some
156      * application might very well depend on the passed |pkey| being used
157      * and none other, so we spend a few more cycles throwing away the newly
158      * created |pk->pkey| and replace it with |pkey|.
159      * TODO(3.0) Investigate if it's safe to change to simply return here
160      * if |pk->pkey != NULL|.
161      */
162     if (pk->pkey != NULL)
163         EVP_PKEY_free(pk->pkey);
164
165     pk->pkey = pkey;
166     return 1;
167
168  unsupported:
169     ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
170
171  error:
172     X509_PUBKEY_free(pk);
173     return 0;
174 }
175
176 /*
177  * Attempt to decode a public key.
178  * Returns 1 on success, 0 for a decode failure and -1 for a fatal
179  * error e.g. malloc failure.
180  */
181
182
183 static int x509_pubkey_decode(EVP_PKEY **ppkey, const X509_PUBKEY *key)
184 {
185     EVP_PKEY *pkey = EVP_PKEY_new();
186
187     if (pkey == NULL) {
188         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
189         return -1;
190     }
191
192     if (!EVP_PKEY_set_type(pkey, OBJ_obj2nid(key->algor->algorithm))) {
193         ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
194         goto error;
195     }
196
197     if (pkey->ameth->pub_decode) {
198         /*
199          * Treat any failure of pub_decode as a decode error. In
200          * future we could have different return codes for decode
201          * errors and fatal errors such as malloc failure.
202          */
203         if (!pkey->ameth->pub_decode(pkey, key))
204             goto error;
205     } else {
206         ERR_raise(ERR_LIB_X509, X509_R_METHOD_NOT_SUPPORTED);
207         goto error;
208     }
209
210     *ppkey = pkey;
211     return 1;
212
213  error:
214     EVP_PKEY_free(pkey);
215     return 0;
216 }
217
218 EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key)
219 {
220     EVP_PKEY *ret = NULL;
221
222     if (key == NULL || key->public_key == NULL)
223         return NULL;
224
225     if (key->pkey != NULL)
226         return key->pkey;
227
228     /*
229      * When the key ASN.1 is initially parsed an attempt is made to
230      * decode the public key and cache the EVP_PKEY structure. If this
231      * operation fails the cached value will be NULL. Parsing continues
232      * to allow parsing of unknown key types or unsupported forms.
233      * We repeat the decode operation so the appropriate errors are left
234      * in the queue.
235      */
236     x509_pubkey_decode(&ret, key);
237     /* If decode doesn't fail something bad happened */
238     if (ret != NULL) {
239         ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
240         EVP_PKEY_free(ret);
241     }
242
243     return NULL;
244 }
245
246 EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key)
247 {
248     EVP_PKEY *ret = X509_PUBKEY_get0(key);
249
250     if (ret != NULL && !EVP_PKEY_up_ref(ret)) {
251         ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
252         ret = NULL;
253     }
254     return ret;
255 }
256
257 /*
258  * Now three pseudo ASN1 routines that take an EVP_PKEY structure and encode
259  * or decode as X509_PUBKEY
260  */
261
262 EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
263                         OSSL_LIB_CTX *libctx, const char *propq)
264 {
265     X509_PUBKEY *xpk, *xpk2 = NULL, **pxpk = NULL;
266     EVP_PKEY *pktmp = NULL;
267     const unsigned char *q;
268
269     q = *pp;
270
271     /*
272      * If libctx or propq are non-NULL, we take advantage of the reuse
273      * feature.  It's not generally recommended, but is safe enough for
274      * newly created structures.
275      */
276     if (libctx != NULL || propq != NULL) {
277         xpk2 = OPENSSL_zalloc(sizeof(*xpk2));
278         if (xpk2 == NULL) {
279             ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
280             return NULL;
281         }
282         if (!x509_pubkey_set0_libctx(xpk2, libctx, propq))
283             goto end;
284         pxpk = &xpk2;
285     }
286     xpk = d2i_X509_PUBKEY(pxpk, &q, length);
287     if (xpk == NULL)
288         goto end;
289     pktmp = X509_PUBKEY_get(xpk);
290     X509_PUBKEY_free(xpk);
291     xpk2 = NULL;                 /* We know that xpk == xpk2 */
292     if (pktmp == NULL)
293         goto end;
294     *pp = q;
295     if (a != NULL) {
296         EVP_PKEY_free(*a);
297         *a = pktmp;
298     }
299  end:
300     X509_PUBKEY_free(xpk2);
301     return pktmp;
302 }
303
304 EVP_PKEY *d2i_PUBKEY(EVP_PKEY **a, const unsigned char **pp, long length)
305 {
306     return d2i_PUBKEY_ex(a, pp, length, NULL, NULL);
307 }
308
309 int i2d_PUBKEY(const EVP_PKEY *a, unsigned char **pp)
310 {
311     int ret = -1;
312
313     if (a == NULL)
314         return 0;
315     if (a->ameth != NULL) {
316         X509_PUBKEY *xpk = NULL;
317
318         if ((xpk = X509_PUBKEY_new()) == NULL)
319             return -1;
320
321         /* pub_encode() only encode parameters, not the key itself */
322         if (a->ameth->pub_encode != NULL && a->ameth->pub_encode(xpk, a)) {
323             xpk->pkey = (EVP_PKEY *)a;
324             ret = i2d_X509_PUBKEY(xpk, pp);
325             xpk->pkey = NULL;
326         }
327         X509_PUBKEY_free(xpk);
328     } else if (a->keymgmt != NULL) {
329         OSSL_ENCODER_CTX *ctx =
330             OSSL_ENCODER_CTX_new_by_EVP_PKEY(a, EVP_PKEY_PUBLIC_KEY,
331                                              "DER", "SubjectPublicKeyInfo",
332                                              NULL);
333         BIO *out = BIO_new(BIO_s_mem());
334         BUF_MEM *buf = NULL;
335
336         if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0
337             && out != NULL
338             && OSSL_ENCODER_to_bio(ctx, out)
339             && BIO_get_mem_ptr(out, &buf) > 0) {
340             ret = buf->length;
341
342             if (pp != NULL) {
343                 if (*pp == NULL) {
344                     *pp = (unsigned char *)buf->data;
345                     buf->length = 0;
346                     buf->data = NULL;
347                 } else {
348                     memcpy(*pp, buf->data, ret);
349                     *pp += ret;
350                 }
351             }
352         }
353         BIO_free(out);
354         OSSL_ENCODER_CTX_free(ctx);
355     }
356
357     return ret;
358 }
359
360 /*
361  * The following are equivalents but which return RSA and DSA keys
362  */
363 #ifndef OPENSSL_NO_RSA
364 RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length)
365 {
366     EVP_PKEY *pkey;
367     RSA *key;
368     const unsigned char *q;
369
370     q = *pp;
371     pkey = d2i_PUBKEY(NULL, &q, length);
372     if (pkey == NULL)
373         return NULL;
374     key = EVP_PKEY_get1_RSA(pkey);
375     EVP_PKEY_free(pkey);
376     if (key == NULL)
377         return NULL;
378     *pp = q;
379     if (a != NULL) {
380         RSA_free(*a);
381         *a = key;
382     }
383     return key;
384 }
385
386 int i2d_RSA_PUBKEY(const RSA *a, unsigned char **pp)
387 {
388     EVP_PKEY *pktmp;
389     int ret;
390     if (!a)
391         return 0;
392     pktmp = EVP_PKEY_new();
393     if (pktmp == NULL) {
394         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
395         return -1;
396     }
397     (void)EVP_PKEY_assign_RSA(pktmp, (RSA *)a);
398     ret = i2d_PUBKEY(pktmp, pp);
399     pktmp->pkey.ptr = NULL;
400     EVP_PKEY_free(pktmp);
401     return ret;
402 }
403 #endif
404
405 #ifndef OPENSSL_NO_DSA
406 DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length)
407 {
408     EVP_PKEY *pkey;
409     DSA *key;
410     const unsigned char *q;
411
412     q = *pp;
413     pkey = d2i_PUBKEY(NULL, &q, length);
414     if (pkey == NULL)
415         return NULL;
416     key = EVP_PKEY_get1_DSA(pkey);
417     EVP_PKEY_free(pkey);
418     if (key == NULL)
419         return NULL;
420     *pp = q;
421     if (a != NULL) {
422         DSA_free(*a);
423         *a = key;
424     }
425     return key;
426 }
427
428 int i2d_DSA_PUBKEY(const DSA *a, unsigned char **pp)
429 {
430     EVP_PKEY *pktmp;
431     int ret;
432     if (!a)
433         return 0;
434     pktmp = EVP_PKEY_new();
435     if (pktmp == NULL) {
436         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
437         return -1;
438     }
439     (void)EVP_PKEY_assign_DSA(pktmp, (DSA *)a);
440     ret = i2d_PUBKEY(pktmp, pp);
441     pktmp->pkey.ptr = NULL;
442     EVP_PKEY_free(pktmp);
443     return ret;
444 }
445 #endif
446
447 #ifndef OPENSSL_NO_EC
448 EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length)
449 {
450     EVP_PKEY *pkey;
451     EC_KEY *key;
452     const unsigned char *q;
453
454     q = *pp;
455     pkey = d2i_PUBKEY(NULL, &q, length);
456     if (pkey == NULL)
457         return NULL;
458     key = EVP_PKEY_get1_EC_KEY(pkey);
459     EVP_PKEY_free(pkey);
460     if (key == NULL)
461         return NULL;
462     *pp = q;
463     if (a != NULL) {
464         EC_KEY_free(*a);
465         *a = key;
466     }
467     return key;
468 }
469
470 int i2d_EC_PUBKEY(const EC_KEY *a, unsigned char **pp)
471 {
472     EVP_PKEY *pktmp;
473     int ret;
474
475     if (a == NULL)
476         return 0;
477     if ((pktmp = EVP_PKEY_new()) == NULL) {
478         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
479         return -1;
480     }
481     (void)EVP_PKEY_assign_EC_KEY(pktmp, (EC_KEY *)a);
482     ret = i2d_PUBKEY(pktmp, pp);
483     pktmp->pkey.ptr = NULL;
484     EVP_PKEY_free(pktmp);
485     return ret;
486 }
487 #endif
488
489 int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
490                            int ptype, void *pval,
491                            unsigned char *penc, int penclen)
492 {
493     if (!X509_ALGOR_set0(pub->algor, aobj, ptype, pval))
494         return 0;
495     if (penc) {
496         OPENSSL_free(pub->public_key->data);
497         pub->public_key->data = penc;
498         pub->public_key->length = penclen;
499         /* Set number of unused bits to zero */
500         pub->public_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
501         pub->public_key->flags |= ASN1_STRING_FLAG_BITS_LEFT;
502     }
503     return 1;
504 }
505
506 int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
507                            const unsigned char **pk, int *ppklen,
508                            X509_ALGOR **pa, const X509_PUBKEY *pub)
509 {
510     if (ppkalg)
511         *ppkalg = pub->algor->algorithm;
512     if (pk) {
513         *pk = pub->public_key->data;
514         *ppklen = pub->public_key->length;
515     }
516     if (pa)
517         *pa = pub->algor;
518     return 1;
519 }
520
521 ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x)
522 {
523     if (x == NULL)
524         return NULL;
525     return x->cert_info.key->public_key;
526 }
527
528 /* Returns 1 for equal, 0, for non-equal, < 0 on error */
529 int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b)
530 {
531     X509_ALGOR *algA, *algB;
532     EVP_PKEY *pA, *pB;
533
534     if (a == b)
535         return 1;
536     if (a == NULL || b == NULL)
537         return 0;
538     if (!X509_PUBKEY_get0_param(NULL, NULL, NULL, &algA, a) || algA == NULL
539         || !X509_PUBKEY_get0_param(NULL, NULL, NULL, &algB, b) || algB == NULL)
540         return -2;
541     if (X509_ALGOR_cmp(algA, algB) != 0)
542         return 0;
543     if ((pA = X509_PUBKEY_get0(a)) == NULL
544         || (pB = X509_PUBKEY_get0(b)) == NULL)
545         return -2;
546     return EVP_PKEY_eq(pA, pB);
547 }
548
549 int X509_PUBKEY_get0_libctx(OSSL_LIB_CTX **plibctx, const char **ppropq,
550                             const X509_PUBKEY *key)
551 {
552     if (plibctx)
553         *plibctx = key->libctx;
554     if (ppropq)
555         *ppropq = key->propq;
556     return 1;
557 }