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