2dbbe6b37c17022a7a9ea3e4920d41c04361aa09
[openssl.git] / providers / implementations / serializers / serializer_common.c
1 /*
2  * Copyright 2019-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 #include <openssl/opensslconf.h> /* SIXTY_FOUR_BIT_LONG, ... */
11 #include <openssl/err.h>
12 #include <openssl/pem.h>         /* PEM_BUFSIZE */
13 #include <openssl/pkcs12.h>      /* PKCS8_encrypt() */
14 #include <openssl/types.h>
15 #include <openssl/x509.h>        /* i2d_X509_PUBKEY_bio() */
16 #include "crypto/bn.h"           /* bn_get_words() */
17 #include "crypto/ctype.h"
18 #include "crypto/ecx.h"
19 #include "prov/bio.h"            /* ossl_prov_bio_printf() */
20 #include "prov/implementations.h"
21 #include "prov/providercommonerr.h" /* PROV_R_READ_KEY */
22 #include "serializer_local.h"
23
24 static PKCS8_PRIV_KEY_INFO *
25 ossl_prov_p8info_from_obj(const void *obj, int obj_nid,
26                           void *params,
27                           int params_type,
28                           int (*k2d)(const void *obj,
29                                      unsigned char **pder))
30 {
31     /* der, derlen store the key DER output and its length */
32     unsigned char *der = NULL;
33     int derlen;
34     /* The final PKCS#8 info */
35     PKCS8_PRIV_KEY_INFO *p8info = NULL;
36
37
38     if ((p8info = PKCS8_PRIV_KEY_INFO_new()) == NULL
39         || (derlen = k2d(obj, &der)) <= 0
40         || !PKCS8_pkey_set0(p8info, OBJ_nid2obj(obj_nid), 0,
41                             params_type, params, der, derlen)) {
42         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
43         PKCS8_PRIV_KEY_INFO_free(p8info);
44         OPENSSL_free(der);
45         p8info = NULL;
46     }
47
48     return p8info;
49 }
50
51 static X509_SIG *ossl_prov_encp8_from_p8info(PKCS8_PRIV_KEY_INFO *p8info,
52                                              struct pkcs8_encrypt_ctx_st *ctx)
53 {
54     X509_SIG *p8 = NULL;
55     char buf[PEM_BUFSIZE];
56     const void *kstr = ctx->cipher_pass;
57     size_t klen = ctx->cipher_pass_length;
58
59     if (ctx->cipher == NULL)
60         return NULL;
61
62     if (kstr == NULL) {
63         if (!ctx->cb(buf, sizeof(buf), &klen, NULL, ctx->cbarg)) {
64             ERR_raise(ERR_LIB_PROV, PROV_R_READ_KEY);
65             return NULL;
66         }
67         kstr = buf;
68     }
69     /* NID == -1 means "standard" */
70     p8 = PKCS8_encrypt(-1, ctx->cipher, kstr, klen, NULL, 0, 0, p8info);
71     if (kstr == buf)
72         OPENSSL_cleanse(buf, klen);
73     return p8;
74 }
75
76 static X509_SIG *ossl_prov_encp8_from_obj(const void *obj, int obj_nid,
77                                           void *params,
78                                           int params_type,
79                                           int (*k2d)(const void *obj,
80                                                      unsigned char **pder),
81                                           struct pkcs8_encrypt_ctx_st *ctx)
82 {
83     PKCS8_PRIV_KEY_INFO *p8info =
84         ossl_prov_p8info_from_obj(obj, obj_nid, params, params_type, k2d);
85     X509_SIG *p8 = ossl_prov_encp8_from_p8info(p8info, ctx);
86
87     PKCS8_PRIV_KEY_INFO_free(p8info);
88     return p8;
89 }
90
91 static X509_PUBKEY *ossl_prov_pubkey_from_obj(const void *obj, int obj_nid,
92                                               void *params,
93                                               int params_type,
94                                               int (*k2d)(const void *obj,
95                                                          unsigned char **pder))
96 {
97     /* der, derlen store the key DER output and its length */
98     unsigned char *der = NULL;
99     int derlen;
100     /* The final X509_PUBKEY */
101     X509_PUBKEY *xpk = NULL;
102
103
104     if ((xpk = X509_PUBKEY_new()) == NULL
105         || (derlen = k2d(obj, &der)) <= 0
106         || !X509_PUBKEY_set0_param(xpk, OBJ_nid2obj(obj_nid),
107                                    params_type, params, der, derlen)) {
108         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
109         X509_PUBKEY_free(xpk);
110         OPENSSL_free(der);
111         xpk = NULL;
112     }
113
114     return xpk;
115 }
116
117 OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_new(const OSSL_DISPATCH *fns)
118 {
119     /* Pilfer the keymgmt dispatch table */
120     for (; fns->function_id != 0; fns++)
121         if (fns->function_id == OSSL_FUNC_KEYMGMT_NEW)
122             return OSSL_get_OP_keymgmt_new(fns);
123
124     return NULL;
125 }
126
127 OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_free(const OSSL_DISPATCH *fns)
128 {
129     /* Pilfer the keymgmt dispatch table */
130     for (; fns->function_id != 0; fns++)
131         if (fns->function_id == OSSL_FUNC_KEYMGMT_FREE)
132             return OSSL_get_OP_keymgmt_free(fns);
133
134     return NULL;
135 }
136
137 OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_import(const OSSL_DISPATCH *fns)
138 {
139     /* Pilfer the keymgmt dispatch table */
140     for (; fns->function_id != 0; fns++)
141         if (fns->function_id == OSSL_FUNC_KEYMGMT_IMPORT)
142             return OSSL_get_OP_keymgmt_import(fns);
143
144     return NULL;
145 }
146
147 # ifdef SIXTY_FOUR_BIT_LONG
148 #  define BN_FMTu "%lu"
149 #  define BN_FMTx "%lx"
150 # endif
151
152 # ifdef SIXTY_FOUR_BIT
153 #  define BN_FMTu "%llu"
154 #  define BN_FMTx "%llx"
155 # endif
156
157 # ifdef THIRTY_TWO_BIT
158 #  define BN_FMTu "%u"
159 #  define BN_FMTx "%x"
160 # endif
161
162 int ossl_prov_print_labeled_bignum(BIO *out, const char *label,
163                                    const BIGNUM *bn)
164 {
165     int ret = 0, use_sep = 0;
166     char *hex_str = NULL, *p;
167     const char spaces[] = "    ";
168     const char *post_label_spc = " ";
169
170     const char *neg = "";
171     int bytes;
172
173     if (bn == NULL)
174         return 0;
175     if (label == NULL) {
176         label = "";
177         post_label_spc = "";
178     }
179
180     if (BN_is_zero(bn))
181         return ossl_prov_bio_printf(out, "%s%s0\n", label, post_label_spc);
182
183     if (BN_num_bytes(bn) <= BN_BYTES) {
184         BN_ULONG *words = bn_get_words(bn);
185
186         if (BN_is_negative(bn))
187             neg = "-";
188
189         return ossl_prov_bio_printf(out,
190                                     "%s%s%s" BN_FMTu " (%s0x" BN_FMTx ")\n",
191                                     label, post_label_spc, neg, words[0],
192                                     neg, words[0]);
193     }
194
195     hex_str = BN_bn2hex(bn);
196     p = hex_str;
197     if (*p == '-') {
198         ++p;
199         neg = " (Negative)";
200     }
201     if (ossl_prov_bio_printf(out, "%s%s\n", label, neg) <= 0)
202         goto err;
203
204     /* Keep track of how many bytes we have printed out so far */
205     bytes = 0;
206
207     if (ossl_prov_bio_printf(out, "%s", spaces) <= 0)
208         goto err;
209
210     /* Add a leading 00 if the top bit is set */
211     if (*p >= '8') {
212         if (ossl_prov_bio_printf(out, "%02x", 0) <= 0)
213             goto err;
214         ++bytes;
215         use_sep = 1;
216     }
217     while (*p != '\0') {
218         /* Do a newline after every 15 hex bytes + add the space indent */
219         if ((bytes % 15) == 0 && bytes > 0) {
220             if (ossl_prov_bio_printf(out, ":\n%s", spaces) <= 0)
221                 goto err;
222             use_sep = 0; /* The first byte on the next line doesnt have a : */
223         }
224         if (ossl_prov_bio_printf(out, "%s%c%c", use_sep ? ":" : "",
225                                  ossl_tolower(p[0]), ossl_tolower(p[1])) <= 0)
226             goto err;
227         ++bytes;
228         p += 2;
229         use_sep = 1;
230     }
231     if (ossl_prov_bio_printf(out, "\n") <= 0)
232         goto err;
233     ret = 1;
234 err:
235     OPENSSL_free(hex_str);
236     return ret;
237 }
238
239 /* Number of octets per line */
240 #define LABELED_BUF_PRINT_WIDTH    15
241
242 int ossl_prov_print_labeled_buf(BIO *out, const char *label,
243                                 const unsigned char *buf, size_t buflen)
244 {
245     size_t i;
246
247     if (ossl_prov_bio_printf(out, "%s\n", label) <= 0)
248         return 0;
249
250     for (i = 0; i < buflen; i++) {
251         if ((i % LABELED_BUF_PRINT_WIDTH) == 0) {
252             if (i > 0 && ossl_prov_bio_printf(out, "\n") <= 0)
253                 return 0;
254             if (ossl_prov_bio_printf(out, "    ") <= 0)
255                 return 0;
256         }
257
258         if (ossl_prov_bio_printf(out, "%02x%s", buf[i],
259                                  (i == buflen - 1) ? "" : ":") <= 0)
260             return 0;
261     }
262     if (ossl_prov_bio_printf(out, "\n") <= 0)
263         return 0;
264
265     return 1;
266 }
267
268 /* p2s = param to asn1, k2d = key to der */
269 int ossl_prov_write_priv_der_from_obj(BIO *out, const void *obj, int obj_nid,
270                                       int (*p2s)(const void *obj, int nid,
271                                                  void **str,
272                                                  int *strtype),
273                                       int (*k2d)(const void *obj,
274                                                  unsigned char **pder),
275                                       struct pkcs8_encrypt_ctx_st *ctx)
276 {
277     int ret = 0;
278     void *str = NULL;
279     int strtype = V_ASN1_UNDEF;
280
281     if (p2s != NULL && !p2s(obj, obj_nid, &str, &strtype))
282         return 0;
283
284     if (ctx->cipher_intent) {
285         X509_SIG *p8 =
286             ossl_prov_encp8_from_obj(obj, obj_nid, str, strtype, k2d, ctx);
287
288         if (p8 != NULL)
289             ret = i2d_PKCS8_bio(out, p8);
290
291         X509_SIG_free(p8);
292     } else {
293         PKCS8_PRIV_KEY_INFO *p8info =
294             ossl_prov_p8info_from_obj(obj, obj_nid, str, strtype, k2d);
295
296         if (p8info != NULL)
297             ret = i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8info);
298
299         PKCS8_PRIV_KEY_INFO_free(p8info);
300     }
301
302     return ret;
303 }
304
305 int ossl_prov_write_priv_pem_from_obj(BIO *out, const void *obj, int obj_nid,
306                                       int (*p2s)(const void *obj, int nid,
307                                                  void **str,
308                                                  int *strtype),
309                                       int (*k2d)(const void *obj,
310                                                  unsigned char **pder),
311                                       struct pkcs8_encrypt_ctx_st *ctx)
312 {
313     int ret = 0;
314     void *str = NULL;
315     int strtype = V_ASN1_UNDEF;
316
317     if (p2s != NULL && !p2s(obj, obj_nid, &str, &strtype))
318         return 0;
319
320     if (ctx->cipher_intent) {
321         X509_SIG *p8 = ossl_prov_encp8_from_obj(obj, obj_nid, str, strtype,
322                                                 k2d, ctx);
323
324         if (p8 != NULL)
325             ret = PEM_write_bio_PKCS8(out, p8);
326
327         X509_SIG_free(p8);
328     } else {
329         PKCS8_PRIV_KEY_INFO *p8info =
330             ossl_prov_p8info_from_obj(obj, obj_nid, str, strtype, k2d);
331
332         if (p8info != NULL)
333             ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8info);
334
335         PKCS8_PRIV_KEY_INFO_free(p8info);
336     }
337
338     return ret;
339 }
340
341 int ossl_prov_write_pub_der_from_obj(BIO *out, const void *obj, int obj_nid,
342                                      int (*p2s)(const void *obj, int nid,
343                                                 void **str,
344                                                 int *strtype),
345                                      int (*k2d)(const void *obj,
346                                                 unsigned char **pder))
347 {
348     int ret = 0;
349     void *str = NULL;
350     int strtype = V_ASN1_UNDEF;
351     X509_PUBKEY *xpk = NULL;
352
353     if (p2s != NULL && !p2s(obj, obj_nid, &str, &strtype))
354         return 0;
355
356     xpk = ossl_prov_pubkey_from_obj(obj, obj_nid, str, strtype, k2d);
357
358     if (xpk != NULL)
359         ret = i2d_X509_PUBKEY_bio(out, xpk);
360
361     /* Also frees |str| */
362     X509_PUBKEY_free(xpk);
363     return ret;
364 }
365
366 int ossl_prov_write_pub_pem_from_obj(BIO *out, const void *obj, int obj_nid,
367                                      int (*p2s)(const void *obj, int nid,
368                                                 void **str,
369                                                 int *strtype),
370                                      int (*k2d)(const void *obj,
371                                                 unsigned char **pder))
372 {
373     int ret = 0;
374     void *str = NULL;
375     int strtype = V_ASN1_UNDEF;
376     X509_PUBKEY *xpk = NULL;
377
378     if (p2s != NULL && !p2s(obj, obj_nid, &str, &strtype))
379         return 0;
380
381     xpk = ossl_prov_pubkey_from_obj(obj, obj_nid, str, strtype, k2d);
382
383     if (xpk != NULL)
384         ret = PEM_write_bio_X509_PUBKEY(out, xpk);
385
386     /* Also frees |str| */
387     X509_PUBKEY_free(xpk);
388     return ret;
389 }