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