Coverage Report

Created: 2024-06-20 06:28

/src/gnutls/lib/x509/privkey_pkcs8.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (C) 2003-2016 Free Software Foundation, Inc.
3
 * Copyright (C) 2014-2017 Red Hat
4
 * Copyright (C) 2014-2016 Nikos Mavrogiannopoulos
5
 *
6
 * Author: Nikos Mavrogiannopoulos
7
 *
8
 * This file is part of GnuTLS.
9
 *
10
 * The GnuTLS is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public License
12
 * as published by the Free Software Foundation; either version 2.1 of
13
 * the License, or (at your option) any later version.
14
 *
15
 * This library is distributed in the hope that it will be useful, but
16
 * WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public License
21
 * along with this program.  If not, see <https://www.gnu.org/licenses/>
22
 *
23
 */
24
25
#include "gnutls_int.h"
26
27
#include "datum.h"
28
#include "global.h"
29
#include "errors.h"
30
#include "common.h"
31
#include "x509.h"
32
#include "x509_b64.h"
33
#include "x509_int.h"
34
#include "pkcs7_int.h"
35
#include "algorithms.h"
36
#include "num.h"
37
#include "random.h"
38
#include "pk.h"
39
#include "attributes.h"
40
#include "prov-seed.h"
41
42
static int _decode_pkcs8_ecc_key(asn1_node pkcs8_asn,
43
         gnutls_x509_privkey_t pkey);
44
static int pkcs8_key_info(const gnutls_datum_t *raw_key,
45
        const struct pkcs_cipher_schema_st **p,
46
        struct pbkdf2_params *kdf_params, char **oid);
47
48
static int decode_private_key_info(const gnutls_datum_t *der,
49
           gnutls_x509_privkey_t pkey);
50
51
0
#define PEM_PKCS8 "ENCRYPTED PRIVATE KEY"
52
0
#define PEM_UNENCRYPTED_PKCS8 "PRIVATE KEY"
53
54
/* Returns a negative error code if the encryption schema in
55
 * the OID is not supported. The schema ID is returned.
56
 */
57
/* Encodes a private key to the raw format PKCS #8 needs.
58
 * For RSA it is a PKCS #1 DER private key and for DSA it is
59
 * an ASN.1 INTEGER of the x value.
60
 */
61
inline static int _encode_privkey(gnutls_x509_privkey_t pkey,
62
          gnutls_datum_t *raw)
63
0
{
64
0
  int ret;
65
0
  asn1_node spk = NULL;
66
67
0
  switch (pkey->params.algo) {
68
0
  case GNUTLS_PK_EDDSA_ED25519:
69
0
  case GNUTLS_PK_EDDSA_ED448:
70
0
  case GNUTLS_PK_ECDH_X25519:
71
0
  case GNUTLS_PK_ECDH_X448:
72
    /* we encode as octet string (which is going to be stored inside
73
     * another octet string). No comments. */
74
0
    ret = _gnutls_x509_encode_string(ASN1_ETYPE_OCTET_STRING,
75
0
             pkey->params.raw_priv.data,
76
0
             pkey->params.raw_priv.size,
77
0
             raw);
78
0
    if (ret < 0)
79
0
      gnutls_assert();
80
0
    return ret;
81
82
0
  case GNUTLS_PK_GOST_01:
83
0
  case GNUTLS_PK_GOST_12_256:
84
0
  case GNUTLS_PK_GOST_12_512:
85
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
86
0
                 "GNUTLS.GOSTPrivateKey",
87
0
                 &spk)) != ASN1_SUCCESS) {
88
0
      gnutls_assert();
89
0
      ret = _gnutls_asn2err(ret);
90
0
      goto error;
91
0
    }
92
93
0
    ret = _gnutls_x509_write_key_int_le(
94
0
      spk, "", pkey->params.params[GOST_K]);
95
0
    if (ret < 0) {
96
0
      gnutls_assert();
97
0
      goto error;
98
0
    }
99
100
0
    ret = _gnutls_x509_der_encode(spk, "", raw, 0);
101
0
    if (ret < 0) {
102
0
      gnutls_assert();
103
0
      goto error;
104
0
    }
105
106
0
    asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
107
0
    break;
108
109
0
  case GNUTLS_PK_RSA:
110
0
  case GNUTLS_PK_RSA_PSS:
111
0
  case GNUTLS_PK_ECDSA:
112
0
    ret = _gnutls_x509_export_int2(pkey->key, GNUTLS_X509_FMT_DER,
113
0
                 "", raw);
114
0
    if (ret < 0) {
115
0
      gnutls_assert();
116
0
      goto error;
117
0
    }
118
119
0
    break;
120
0
  case GNUTLS_PK_DSA:
121
    /* DSAPublicKey == INTEGER */
122
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
123
0
                 "GNUTLS.DSAPublicKey", &spk)) !=
124
0
        ASN1_SUCCESS) {
125
0
      gnutls_assert();
126
0
      return _gnutls_asn2err(ret);
127
0
    }
128
129
0
    ret = _gnutls_x509_write_int(spk, "", pkey->params.params[4],
130
0
               1);
131
0
    if (ret < 0) {
132
0
      gnutls_assert();
133
0
      goto error;
134
0
    }
135
0
    ret = _gnutls_x509_der_encode(spk, "", raw, 0);
136
0
    if (ret < 0) {
137
0
      gnutls_assert();
138
0
      goto error;
139
0
    }
140
141
0
    asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
142
0
    break;
143
144
0
  default:
145
0
    gnutls_assert();
146
0
    return GNUTLS_E_INVALID_REQUEST;
147
0
  }
148
149
0
  return 0;
150
151
0
error:
152
0
  asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
153
0
  asn1_delete_structure(&spk);
154
0
  return ret;
155
0
}
156
157
/* 
158
 * Encodes a PKCS #1 private key to a PKCS #8 private key
159
 * info. The output will be allocated and stored into der. Also
160
 * the asn1_node of private key info will be returned.
161
 */
162
static int encode_to_private_key_info(gnutls_x509_privkey_t pkey,
163
              gnutls_datum_t *der, asn1_node *pkey_info)
164
0
{
165
0
  int result, len;
166
0
  uint8_t null = 0;
167
0
  const char *oid;
168
0
  gnutls_datum_t algo_params = { NULL, 0 };
169
0
  gnutls_datum_t algo_privkey = { NULL, 0 };
170
171
0
  oid = gnutls_pk_get_oid(pkey->params.algo);
172
0
  if (oid == NULL) {
173
0
    gnutls_assert();
174
0
    return GNUTLS_E_UNIMPLEMENTED_FEATURE;
175
0
  }
176
177
0
  result = _gnutls_x509_write_pubkey_params(&pkey->params, &algo_params);
178
0
  if (result < 0) {
179
0
    gnutls_assert();
180
0
    return result;
181
0
  }
182
183
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
184
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
185
0
            pkey_info)) != ASN1_SUCCESS) {
186
0
    gnutls_assert();
187
0
    result = _gnutls_asn2err(result);
188
0
    goto error;
189
0
  }
190
191
  /* Write the version.
192
   */
193
0
  result = asn1_write_value(*pkey_info, "version", &null, 1);
194
0
  if (result != ASN1_SUCCESS) {
195
0
    gnutls_assert();
196
0
    result = _gnutls_asn2err(result);
197
0
    goto error;
198
0
  }
199
200
  /* write the privateKeyAlgorithm
201
   * fields. (OID+NULL data)
202
   */
203
0
  result = asn1_write_value(*pkey_info, "privateKeyAlgorithm.algorithm",
204
0
          oid, 1);
205
0
  if (result != ASN1_SUCCESS) {
206
0
    gnutls_assert();
207
0
    result = _gnutls_asn2err(result);
208
0
    goto error;
209
0
  }
210
211
0
  result = asn1_write_value(*pkey_info, "privateKeyAlgorithm.parameters",
212
0
          algo_params.data, algo_params.size);
213
0
  _gnutls_free_key_datum(&algo_params);
214
215
0
  if (result != ASN1_SUCCESS) {
216
0
    gnutls_assert();
217
0
    result = _gnutls_asn2err(result);
218
0
    goto error;
219
0
  }
220
221
  /* Write the raw private key
222
   */
223
0
  result = _encode_privkey(pkey, &algo_privkey);
224
0
  if (result < 0) {
225
0
    gnutls_assert();
226
0
    goto error;
227
0
  }
228
229
0
  result = asn1_write_value(*pkey_info, "privateKey", algo_privkey.data,
230
0
          algo_privkey.size);
231
0
  _gnutls_free_key_datum(&algo_privkey);
232
233
0
  if (result != ASN1_SUCCESS) {
234
0
    gnutls_assert();
235
0
    result = _gnutls_asn2err(result);
236
0
    goto error;
237
0
  }
238
239
0
  if ((pkey->params.pkflags & GNUTLS_PK_FLAG_PROVABLE) &&
240
0
      pkey->params.seed_size > 0) {
241
0
    gnutls_datum_t seed_info;
242
    /* rfc8479 attribute encoding */
243
244
0
    result = _x509_encode_provable_seed(pkey, &seed_info);
245
0
    if (result < 0) {
246
0
      gnutls_assert();
247
0
      goto error;
248
0
    }
249
250
0
    result = _x509_set_attribute(*pkey_info, "attributes",
251
0
               OID_ATTR_PROV_SEED, &seed_info);
252
0
    gnutls_free(seed_info.data);
253
0
    if (result < 0) {
254
0
      gnutls_assert();
255
0
      goto error;
256
0
    }
257
0
  } else {
258
    /* Append an empty Attributes field.
259
     */
260
0
    result = asn1_write_value(*pkey_info, "attributes", NULL, 0);
261
0
    if (result != ASN1_SUCCESS) {
262
0
      gnutls_assert();
263
0
      result = _gnutls_asn2err(result);
264
0
      goto error;
265
0
    }
266
0
  }
267
268
  /* DER Encode the generated private key info.
269
   */
270
0
  len = 0;
271
0
  result = asn1_der_coding(*pkey_info, "", NULL, &len, NULL);
272
0
  if (result != ASN1_MEM_ERROR) {
273
0
    gnutls_assert();
274
0
    result = _gnutls_asn2err(result);
275
0
    goto error;
276
0
  }
277
278
  /* allocate data for the der
279
   */
280
0
  der->size = len;
281
0
  der->data = gnutls_malloc(len);
282
0
  if (der->data == NULL) {
283
0
    gnutls_assert();
284
0
    return GNUTLS_E_MEMORY_ERROR;
285
0
  }
286
287
0
  result = asn1_der_coding(*pkey_info, "", der->data, &len, NULL);
288
0
  if (result != ASN1_SUCCESS) {
289
0
    gnutls_assert();
290
0
    result = _gnutls_asn2err(result);
291
0
    goto error;
292
0
  }
293
294
0
  return 0;
295
296
0
error:
297
0
  asn1_delete_structure2(pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
298
0
  _gnutls_free_datum(&algo_params);
299
0
  _gnutls_free_key_datum(&algo_privkey);
300
0
  return result;
301
0
}
302
303
/* Converts a PKCS #8 private key info to
304
 * a PKCS #8 EncryptedPrivateKeyInfo.
305
 */
306
static int encode_to_pkcs8_key(schema_id schema, const gnutls_datum_t *der_key,
307
             const char *password, asn1_node *out)
308
0
{
309
0
  int result;
310
0
  gnutls_datum_t key = { NULL, 0 };
311
0
  gnutls_datum_t tmp = { NULL, 0 };
312
0
  asn1_node pkcs8_asn = NULL;
313
0
  struct pbkdf2_params kdf_params;
314
0
  struct pbe_enc_params enc_params;
315
0
  const struct pkcs_cipher_schema_st *s;
316
317
0
  s = _gnutls_pkcs_schema_get(schema);
318
0
  if (s == NULL || s->decrypt_only) {
319
0
    return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
320
0
  }
321
322
0
  if ((result = asn1_create_element(
323
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
324
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
325
0
    gnutls_assert();
326
0
    return _gnutls_asn2err(result);
327
0
  }
328
329
  /* Write the encryption schema OID
330
   */
331
0
  result = asn1_write_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
332
0
          s->write_oid, 1);
333
334
0
  if (result != ASN1_SUCCESS) {
335
0
    gnutls_assert();
336
0
    result = _gnutls_asn2err(result);
337
0
    goto error;
338
0
  }
339
340
  /* Generate a symmetric key.
341
   */
342
343
0
  result = _gnutls_pkcs_generate_key(schema, password, &kdf_params,
344
0
             &enc_params, &key);
345
0
  if (result < 0) {
346
0
    gnutls_assert();
347
0
    goto error;
348
0
  }
349
350
0
  result = _gnutls_pkcs_write_schema_params(
351
0
    schema, pkcs8_asn, "encryptionAlgorithm.parameters",
352
0
    &kdf_params, &enc_params);
353
0
  if (result < 0) {
354
0
    gnutls_assert();
355
0
    goto error;
356
0
  }
357
358
  /* Parameters have been encoded. Now
359
   * encrypt the Data.
360
   */
361
0
  result =
362
0
    _gnutls_pkcs_raw_encrypt_data(der_key, &enc_params, &key, &tmp);
363
0
  if (result < 0) {
364
0
    gnutls_assert();
365
0
    goto error;
366
0
  }
367
368
  /* write the encrypted data.
369
   */
370
0
  result = asn1_write_value(pkcs8_asn, "encryptedData", tmp.data,
371
0
          tmp.size);
372
0
  if (result != ASN1_SUCCESS) {
373
0
    gnutls_assert();
374
0
    result = _gnutls_asn2err(result);
375
0
    goto error;
376
0
  }
377
378
0
  _gnutls_free_datum(&tmp);
379
0
  _gnutls_free_key_datum(&key);
380
381
0
  *out = pkcs8_asn;
382
383
0
  return 0;
384
385
0
error:
386
0
  _gnutls_free_key_datum(&key);
387
0
  _gnutls_free_datum(&tmp);
388
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
389
0
  return result;
390
0
}
391
392
/**
393
 * gnutls_x509_privkey_export_pkcs8:
394
 * @key: Holds the key
395
 * @format: the format of output params. One of PEM or DER.
396
 * @password: the password that will be used to encrypt the key.
397
 * @flags: an ORed sequence of gnutls_pkcs_encrypt_flags_t
398
 * @output_data: will contain a private key PEM or DER encoded
399
 * @output_data_size: holds the size of output_data (and will be
400
 *   replaced by the actual size of parameters)
401
 *
402
 * This function will export the private key to a PKCS8 structure.
403
 * Both RSA and DSA keys can be exported. For DSA keys we use
404
 * PKCS #11 definitions. If the flags do not specify the encryption
405
 * cipher, then the default 3DES (PBES2) will be used.
406
 *
407
 * The @password can be either ASCII or UTF-8 in the default PBES2
408
 * encryption schemas, or ASCII for the PKCS12 schemas.
409
 *
410
 * If the buffer provided is not long enough to hold the output, then
411
 * *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
412
 * be returned.
413
 *
414
 * If the structure is PEM encoded, it will have a header
415
 * of "BEGIN ENCRYPTED PRIVATE KEY" or "BEGIN PRIVATE KEY" if
416
 * encryption is not used.
417
 *
418
 * Returns: In case of failure a negative error code will be
419
 *   returned, and 0 on success.
420
 **/
421
int gnutls_x509_privkey_export_pkcs8(gnutls_x509_privkey_t key,
422
             gnutls_x509_crt_fmt_t format,
423
             const char *password, unsigned int flags,
424
             void *output_data,
425
             size_t *output_data_size)
426
0
{
427
0
  asn1_node pkcs8_asn = NULL, pkey_info;
428
0
  int ret;
429
0
  gnutls_datum_t tmp = { NULL, 0 };
430
0
  schema_id schema;
431
432
0
  if (key == NULL) {
433
0
    gnutls_assert();
434
0
    return GNUTLS_E_INVALID_REQUEST;
435
0
  }
436
437
  /* Get the private key info
438
   * tmp holds the DER encoding.
439
   */
440
0
  ret = encode_to_private_key_info(key, &tmp, &pkey_info);
441
0
  if (ret < 0) {
442
0
    gnutls_assert();
443
0
    return ret;
444
0
  }
445
446
0
  schema = _gnutls_pkcs_flags_to_schema(flags);
447
448
0
  if (((flags & GNUTLS_PKCS_PLAIN) || password == NULL) &&
449
0
      !(flags & GNUTLS_PKCS_NULL_PASSWORD)) {
450
0
    _gnutls_free_datum(&tmp);
451
452
0
    ret = _gnutls_x509_export_int(pkey_info, format,
453
0
                PEM_UNENCRYPTED_PKCS8,
454
0
                output_data, output_data_size);
455
456
0
    asn1_delete_structure2(&pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
457
0
  } else {
458
0
    asn1_delete_structure2(
459
0
      &pkey_info,
460
0
      ASN1_DELETE_FLAG_ZEROIZE); /* we don't need it */
461
462
0
    ret = encode_to_pkcs8_key(schema, &tmp, password, &pkcs8_asn);
463
0
    _gnutls_free_key_datum(&tmp);
464
465
0
    if (ret < 0) {
466
0
      gnutls_assert();
467
0
      return ret;
468
0
    }
469
470
0
    ret = _gnutls_x509_export_int(pkcs8_asn, format, PEM_PKCS8,
471
0
                output_data, output_data_size);
472
473
0
    asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
474
0
  }
475
476
0
  return ret;
477
0
}
478
479
/**
480
 * gnutls_pkcs8_info:
481
 * @data: Holds the PKCS #8 data
482
 * @format: the format of the PKCS #8 data
483
 * @schema: indicate the schema as one of %gnutls_pkcs_encrypt_flags_t
484
 * @cipher: the cipher used as %gnutls_cipher_algorithm_t
485
 * @salt: PBKDF2 salt (if non-NULL then @salt_size initially holds its size)
486
 * @salt_size: PBKDF2 salt size
487
 * @iter_count: PBKDF2 iteration count
488
 * @oid: if non-NULL it will contain an allocated null-terminated variable with the OID
489
 *
490
 * This function will provide information on the algorithms used
491
 * in a particular PKCS #8 structure. If the structure algorithms
492
 * are unknown the code %GNUTLS_E_UNKNOWN_CIPHER_TYPE will be returned,
493
 * and only @oid, will be set. That is, @oid will be set on encrypted PKCS #8
494
 * structures whether supported or not. It must be deinitialized using gnutls_free().
495
 * The other variables are only set on supported structures.
496
 *
497
 * Returns: %GNUTLS_E_INVALID_REQUEST if the provided structure isn't an encrypted key,
498
 *  %GNUTLS_E_UNKNOWN_CIPHER_TYPE if the structure's encryption isn't supported, or
499
 *  another negative error code in case of a failure. Zero on success.
500
 *
501
 * Since: 3.4.0
502
 **/
503
int gnutls_pkcs8_info(const gnutls_datum_t *data, gnutls_x509_crt_fmt_t format,
504
          unsigned int *schema, unsigned int *cipher, void *salt,
505
          unsigned int *salt_size, unsigned int *iter_count,
506
          char **oid)
507
0
{
508
0
  int ret = 0, need_free = 0;
509
0
  gnutls_datum_t _data;
510
0
  const struct pkcs_cipher_schema_st *p = NULL;
511
0
  struct pbkdf2_params kdf;
512
513
0
  memset(&kdf, 0, sizeof(kdf));
514
515
0
  if (oid)
516
0
    *oid = NULL;
517
518
0
  _data.data = data->data;
519
0
  _data.size = data->size;
520
521
  /* If the Certificate is in PEM format then decode it
522
   */
523
0
  if (format == GNUTLS_X509_FMT_PEM) {
524
    /* Try the first header 
525
     */
526
0
    ret = _gnutls_fbase64_decode(PEM_UNENCRYPTED_PKCS8, data->data,
527
0
               data->size, &_data);
528
529
0
    if (ret < 0) { /* Try the encrypted header 
530
         */
531
0
      ret = _gnutls_fbase64_decode(PEM_PKCS8, data->data,
532
0
                 data->size, &_data);
533
534
0
      if (ret < 0) {
535
0
        gnutls_assert();
536
0
        return ret;
537
0
      }
538
0
    }
539
540
0
    need_free = 1;
541
0
  }
542
543
0
  ret = pkcs8_key_info(&_data, &p, &kdf, oid);
544
0
  if (ret == GNUTLS_E_DECRYPTION_FAILED)
545
0
    ret = GNUTLS_E_INVALID_REQUEST;
546
0
  if (ret < 0) {
547
0
    gnutls_assert();
548
0
    goto cleanup;
549
0
  }
550
551
0
  assert(p != NULL);
552
553
0
  if (need_free)
554
0
    _gnutls_free_datum(&_data);
555
556
0
  if (schema)
557
0
    *schema = p->flag;
558
559
0
  if (cipher)
560
0
    *cipher = p->cipher;
561
562
0
  if (iter_count)
563
0
    *iter_count = kdf.iter_count;
564
565
0
  if (salt) {
566
0
    if (*salt_size >= (unsigned)kdf.salt_size) {
567
0
      memcpy(salt, kdf.salt, kdf.salt_size);
568
0
    } else {
569
0
      *salt_size = kdf.salt_size;
570
0
      ret = gnutls_assert_val(GNUTLS_E_SHORT_MEMORY_BUFFER);
571
0
      goto cleanup;
572
0
    }
573
0
  }
574
575
0
  if (salt_size)
576
0
    *salt_size = kdf.salt_size;
577
578
0
  return 0;
579
580
0
cleanup:
581
0
  if (ret != GNUTLS_E_UNKNOWN_CIPHER_TYPE && oid) {
582
0
    gnutls_free(*oid);
583
0
  }
584
0
  if (need_free)
585
0
    _gnutls_free_datum(&_data);
586
0
  return ret;
587
0
}
588
589
/**
590
 * gnutls_x509_privkey_export2_pkcs8:
591
 * @key: Holds the key
592
 * @format: the format of output params. One of PEM or DER.
593
 * @password: the password that will be used to encrypt the key.
594
 * @flags: an ORed sequence of gnutls_pkcs_encrypt_flags_t
595
 * @out: will contain a private key PEM or DER encoded
596
 *
597
 * This function will export the private key to a PKCS8 structure.
598
 * Both RSA and DSA keys can be exported. For DSA keys we use
599
 * PKCS #11 definitions. If the flags do not specify the encryption
600
 * cipher, then the default 3DES (PBES2) will be used.
601
 *
602
 * The @password can be either ASCII or UTF-8 in the default PBES2
603
 * encryption schemas, or ASCII for the PKCS12 schemas.
604
 *
605
 * The output buffer is allocated using gnutls_malloc().
606
 *
607
 * If the structure is PEM encoded, it will have a header
608
 * of "BEGIN ENCRYPTED PRIVATE KEY" or "BEGIN PRIVATE KEY" if
609
 * encryption is not used.
610
 *
611
 * Returns: In case of failure a negative error code will be
612
 *   returned, and 0 on success.
613
 *
614
 * Since 3.1.3
615
 **/
616
int gnutls_x509_privkey_export2_pkcs8(gnutls_x509_privkey_t key,
617
              gnutls_x509_crt_fmt_t format,
618
              const char *password, unsigned int flags,
619
              gnutls_datum_t *out)
620
0
{
621
0
  asn1_node pkcs8_asn = NULL, pkey_info;
622
0
  int ret;
623
0
  gnutls_datum_t tmp = { NULL, 0 };
624
0
  schema_id schema;
625
626
0
  if (key == NULL) {
627
0
    gnutls_assert();
628
0
    return GNUTLS_E_INVALID_REQUEST;
629
0
  }
630
631
  /* Get the private key info
632
   * tmp holds the DER encoding.
633
   */
634
0
  ret = encode_to_private_key_info(key, &tmp, &pkey_info);
635
0
  if (ret < 0) {
636
0
    gnutls_assert();
637
0
    return ret;
638
0
  }
639
640
0
  schema = _gnutls_pkcs_flags_to_schema(flags);
641
642
0
  if (((flags & GNUTLS_PKCS_PLAIN) || password == NULL) &&
643
0
      !(flags & GNUTLS_PKCS_NULL_PASSWORD)) {
644
0
    _gnutls_free_key_datum(&tmp);
645
646
0
    ret = _gnutls_x509_export_int2(pkey_info, format,
647
0
                 PEM_UNENCRYPTED_PKCS8, out);
648
649
0
    asn1_delete_structure2(&pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
650
0
  } else {
651
0
    asn1_delete_structure2(
652
0
      &pkey_info,
653
0
      ASN1_DELETE_FLAG_ZEROIZE); /* we don't need it */
654
655
0
    ret = encode_to_pkcs8_key(schema, &tmp, password, &pkcs8_asn);
656
0
    _gnutls_free_key_datum(&tmp);
657
658
0
    if (ret < 0) {
659
0
      gnutls_assert();
660
0
      return ret;
661
0
    }
662
663
0
    ret = _gnutls_x509_export_int2(pkcs8_asn, format, PEM_PKCS8,
664
0
                 out);
665
666
0
    asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
667
0
  }
668
669
0
  return ret;
670
0
}
671
672
/* We've gotten this far. In the real world it's almost certain
673
   * that we're dealing with a good file, but wrong password.
674
   * Sadly like 90% of random data is somehow valid DER for the
675
   * a first small number of bytes, so no easy way to guarantee. */
676
#define CHECK_ERR_FOR_ENCRYPTED(result)                     \
677
0
  if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND ||    \
678
0
      result == GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND || \
679
0
      result == GNUTLS_E_ASN1_DER_ERROR ||            \
680
0
      result == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||      \
681
0
      result == GNUTLS_E_ASN1_GENERIC_ERROR ||        \
682
0
      result == GNUTLS_E_ASN1_VALUE_NOT_VALID ||      \
683
0
      result == GNUTLS_E_ASN1_TAG_ERROR ||            \
684
0
      result == GNUTLS_E_ASN1_TAG_IMPLICIT ||         \
685
0
      result == GNUTLS_E_ASN1_TYPE_ANY_ERROR ||       \
686
0
      result == GNUTLS_E_ASN1_SYNTAX_ERROR ||         \
687
0
      result == GNUTLS_E_ASN1_DER_OVERFLOW) {         \
688
0
    result = GNUTLS_E_DECRYPTION_FAILED;        \
689
0
  }
690
691
static int pkcs8_key_decrypt(const gnutls_datum_t *raw_key, asn1_node pkcs8_asn,
692
           const char *password, gnutls_x509_privkey_t pkey)
693
0
{
694
0
  int result, len;
695
0
  char enc_oid[MAX_OID_SIZE];
696
0
  gnutls_datum_t tmp = { NULL, 0 };
697
0
  int params_start, params_end, params_len;
698
0
  struct pbkdf2_params kdf_params;
699
0
  struct pbe_enc_params enc_params;
700
0
  schema_id schema;
701
702
  /* Check the encryption schema OID
703
   */
704
0
  len = sizeof(enc_oid);
705
0
  result = asn1_read_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
706
0
         enc_oid, &len);
707
0
  if (result != ASN1_SUCCESS) {
708
0
    gnutls_assert();
709
0
    goto error;
710
0
  }
711
712
0
  if ((result = _gnutls_check_pkcs_cipher_schema(enc_oid)) < 0) {
713
0
    gnutls_assert();
714
0
    goto error;
715
0
  }
716
717
0
  schema = result;
718
719
  /* Get the DER encoding of the parameters.
720
   */
721
0
  result = asn1_der_decoding_startEnd(pkcs8_asn, raw_key->data,
722
0
              raw_key->size,
723
0
              "encryptionAlgorithm.parameters",
724
0
              &params_start, &params_end);
725
0
  if (result != ASN1_SUCCESS) {
726
0
    gnutls_assert();
727
0
    result = _gnutls_asn2err(result);
728
0
    goto error;
729
0
  }
730
0
  params_len = params_end - params_start + 1;
731
732
0
  result = _gnutls_read_pkcs_schema_params(&schema, password,
733
0
             &raw_key->data[params_start],
734
0
             params_len, &kdf_params,
735
0
             &enc_params);
736
737
0
  if (result < 0) {
738
0
    gnutls_assert();
739
0
    goto error;
740
0
  }
741
742
  /* Parameters have been decoded. Now
743
   * decrypt the EncryptedData.
744
   */
745
0
  result = _gnutls_pkcs_raw_decrypt_data(schema, pkcs8_asn,
746
0
                 "encryptedData", password,
747
0
                 &kdf_params, &enc_params, &tmp);
748
0
  if (result < 0) {
749
0
    gnutls_assert();
750
0
    result = GNUTLS_E_DECRYPTION_FAILED;
751
0
    goto error;
752
0
  }
753
754
0
  result = decode_private_key_info(&tmp, pkey);
755
0
  _gnutls_free_key_datum(&tmp);
756
757
0
  CHECK_ERR_FOR_ENCRYPTED(result);
758
0
  if (result < 0) {
759
0
    gnutls_assert();
760
0
    goto error;
761
0
  }
762
763
0
  return 0;
764
765
0
error:
766
0
  return result;
767
0
}
768
769
static int check_for_decrypted(const gnutls_datum_t *der)
770
0
{
771
0
  int result;
772
0
  asn1_node pkcs8_asn = NULL;
773
774
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
775
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
776
0
            &pkcs8_asn)) != ASN1_SUCCESS) {
777
0
    gnutls_assert();
778
0
    return _gnutls_asn2err(result);
779
0
  }
780
781
0
  result =
782
0
    _asn1_strict_der_decode(&pkcs8_asn, der->data, der->size, NULL);
783
0
  if (result != ASN1_SUCCESS) {
784
0
    gnutls_assert();
785
0
    result = _gnutls_asn2err(result);
786
0
    goto error;
787
0
  }
788
789
0
  result = 0;
790
0
error:
791
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
792
0
  return result;
793
0
}
794
795
static int pkcs8_key_info(const gnutls_datum_t *raw_key,
796
        const struct pkcs_cipher_schema_st **p,
797
        struct pbkdf2_params *kdf_params, char **oid)
798
0
{
799
0
  int result, len;
800
0
  char enc_oid[MAX_OID_SIZE * 2];
801
0
  int params_start, params_end, params_len;
802
0
  struct pbe_enc_params enc_params;
803
0
  schema_id schema;
804
0
  asn1_node pkcs8_asn = NULL;
805
806
0
  memset(&enc_params, 0, sizeof(enc_params));
807
808
0
  result = check_for_decrypted(raw_key);
809
0
  if (result == 0)
810
0
    return GNUTLS_E_INVALID_REQUEST;
811
812
0
  if ((result = asn1_create_element(
813
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
814
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
815
0
    gnutls_assert();
816
0
    result = _gnutls_asn2err(result);
817
0
    goto error;
818
0
  }
819
820
0
  result = _asn1_strict_der_decode(&pkcs8_asn, raw_key->data,
821
0
           raw_key->size, NULL);
822
0
  if (result != ASN1_SUCCESS) {
823
0
    gnutls_assert();
824
0
    result = _gnutls_asn2err(result);
825
0
    goto error;
826
0
  }
827
828
  /* Check the encryption schema OID
829
   */
830
0
  len = sizeof(enc_oid);
831
0
  result = asn1_read_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
832
0
         enc_oid, &len);
833
0
  if (result != ASN1_SUCCESS) {
834
0
    gnutls_assert();
835
0
    goto error;
836
0
  }
837
838
0
  if (oid) {
839
0
    *oid = gnutls_strdup(enc_oid);
840
0
  }
841
842
0
  if ((result = _gnutls_check_pkcs_cipher_schema(enc_oid)) < 0) {
843
0
    gnutls_assert();
844
0
    goto error;
845
0
  }
846
847
0
  schema = result;
848
849
  /* Get the DER encoding of the parameters.
850
   */
851
0
  result = asn1_der_decoding_startEnd(pkcs8_asn, raw_key->data,
852
0
              raw_key->size,
853
0
              "encryptionAlgorithm.parameters",
854
0
              &params_start, &params_end);
855
0
  if (result != ASN1_SUCCESS) {
856
0
    gnutls_assert();
857
0
    result = _gnutls_asn2err(result);
858
0
    goto error;
859
0
  }
860
0
  params_len = params_end - params_start + 1;
861
862
0
  result = _gnutls_read_pkcs_schema_params(&schema, NULL,
863
0
             &raw_key->data[params_start],
864
0
             params_len, kdf_params,
865
0
             &enc_params);
866
867
0
  if (result < 0) {
868
0
    gnutls_assert();
869
0
    if (oid && enc_params.pbes2_oid[0] != 0) {
870
0
      snprintf(enc_oid, sizeof(enc_oid), "%s/%s", *oid,
871
0
         enc_params.pbes2_oid);
872
0
      gnutls_free(*oid);
873
0
      *oid = gnutls_strdup(enc_oid);
874
0
    }
875
0
    goto error;
876
0
  }
877
878
0
  *p = _gnutls_pkcs_schema_get(schema);
879
0
  if (*p == NULL) {
880
0
    gnutls_assert();
881
0
    result = GNUTLS_E_UNKNOWN_CIPHER_TYPE;
882
0
    goto error;
883
0
  }
884
885
0
  result = 0;
886
887
0
error:
888
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
889
0
  return result;
890
0
}
891
892
/* Converts a PKCS #8 key to
893
 * an internal structure (gnutls_private_key)
894
 * (normally a PKCS #1 encoded RSA key)
895
 */
896
static int pkcs8_key_decode(const gnutls_datum_t *raw_key, const char *password,
897
          gnutls_x509_privkey_t pkey, unsigned int decrypt)
898
0
{
899
0
  int result;
900
0
  asn1_node pkcs8_asn = NULL;
901
902
0
  if ((result = asn1_create_element(
903
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
904
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
905
0
    gnutls_assert();
906
0
    result = _gnutls_asn2err(result);
907
0
    goto error;
908
0
  }
909
910
0
  result = _asn1_strict_der_decode(&pkcs8_asn, raw_key->data,
911
0
           raw_key->size, NULL);
912
0
  if (result != ASN1_SUCCESS) {
913
0
    gnutls_assert();
914
0
    result = _gnutls_asn2err(result);
915
0
    goto error;
916
0
  }
917
918
0
  if (decrypt)
919
0
    result = pkcs8_key_decrypt(raw_key, pkcs8_asn, password, pkey);
920
0
  else
921
0
    result = 0;
922
923
0
error:
924
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
925
0
  return result;
926
0
}
927
928
/* Decodes an RSA privateKey from a PKCS8 structure.
929
 */
930
static int _decode_pkcs8_rsa_key(asn1_node pkcs8_asn,
931
         gnutls_x509_privkey_t pkey)
932
0
{
933
0
  int ret;
934
0
  gnutls_datum_t tmp = { NULL, 0 };
935
936
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
937
0
  if (ret < 0) {
938
0
    gnutls_assert();
939
0
    goto error;
940
0
  }
941
942
0
  pkey->key = _gnutls_privkey_decode_pkcs1_rsa_key(&tmp, pkey);
943
0
  _gnutls_free_key_datum(&tmp);
944
945
0
  if (pkey->key == NULL) {
946
0
    ret = GNUTLS_E_PK_INVALID_PRIVKEY;
947
0
    gnutls_assert();
948
0
    goto error;
949
0
  }
950
951
0
  ret = 0;
952
953
0
error:
954
0
  return ret;
955
0
}
956
957
/* Decodes an RSA-PSS privateKey from a PKCS8 structure.
958
 */
959
static int _decode_pkcs8_rsa_pss_key(asn1_node pkcs8_asn,
960
             gnutls_x509_privkey_t pkey)
961
0
{
962
0
  int ret;
963
0
  gnutls_datum_t tmp = { NULL, 0 };
964
0
  gnutls_x509_spki_st params;
965
966
0
  memset(&params, 0, sizeof(params));
967
968
0
  ret = _gnutls_x509_read_value(pkcs8_asn,
969
0
              "privateKeyAlgorithm.parameters", &tmp);
970
0
  if (ret < 0) {
971
0
    if (ret == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||
972
0
        ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
973
0
      goto skip_params;
974
975
0
    gnutls_assert();
976
0
    goto error;
977
0
  }
978
979
0
  ret = _gnutls_x509_read_rsa_pss_params(tmp.data, tmp.size, &params);
980
0
  _gnutls_free_key_datum(&tmp);
981
982
0
  if (ret < 0) {
983
0
    gnutls_assert();
984
0
    goto error;
985
0
  }
986
987
0
skip_params:
988
0
  ret = _decode_pkcs8_rsa_key(pkcs8_asn, pkey);
989
0
  if (ret < 0) {
990
0
    gnutls_assert();
991
0
    goto error;
992
0
  }
993
994
0
  pkey->params.algo = GNUTLS_PK_RSA_PSS;
995
0
  memcpy(&pkey->params.spki, &params, sizeof(gnutls_x509_spki_st));
996
997
0
  ret = 0;
998
999
0
error:
1000
0
  return ret;
1001
0
}
1002
1003
/* Decodes an ECC privateKey from a PKCS8 structure.
1004
 */
1005
static int _decode_pkcs8_ecc_key(asn1_node pkcs8_asn,
1006
         gnutls_x509_privkey_t pkey)
1007
0
{
1008
0
  int ret;
1009
0
  gnutls_datum_t tmp = { NULL, 0 };
1010
0
  unsigned char oid[MAX_OID_SIZE];
1011
0
  unsigned curve = GNUTLS_ECC_CURVE_INVALID;
1012
0
  int len, result;
1013
1014
  /* openssl PKCS #8 files with ECC keys place the curve in
1015
   * privateKeyAlgorithm.parameters instead of the ECPrivateKey.parameters.
1016
   */
1017
0
  len = sizeof(oid);
1018
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.parameters",
1019
0
         oid, &len);
1020
0
  if (result == ASN1_SUCCESS) {
1021
0
    ret = _gnutls_x509_read_ecc_params(oid, len, &curve);
1022
0
    if (ret < 0) {
1023
0
      _gnutls_debug_log("PKCS#8: unknown curve OID %s\n",
1024
0
            oid);
1025
0
      curve = GNUTLS_ECC_CURVE_INVALID;
1026
0
    }
1027
0
  }
1028
1029
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1030
0
  if (ret < 0) {
1031
0
    gnutls_assert();
1032
0
    goto error;
1033
0
  }
1034
1035
0
  ret = _gnutls_privkey_decode_ecc_key(&pkey->key, &tmp, pkey, curve);
1036
0
  _gnutls_free_key_datum(&tmp);
1037
1038
0
  if (ret < 0) {
1039
0
    gnutls_assert();
1040
0
    goto error;
1041
0
  }
1042
1043
0
  ret = 0;
1044
1045
0
error:
1046
0
  return ret;
1047
0
}
1048
1049
static int _decode_pkcs8_eddsa_key(asn1_node pkcs8_asn,
1050
           gnutls_x509_privkey_t pkey, const char *oid)
1051
0
{
1052
0
  int ret;
1053
0
  gnutls_datum_t tmp;
1054
0
  gnutls_ecc_curve_t curve = GNUTLS_ECC_CURVE_INVALID;
1055
0
  const gnutls_ecc_curve_entry_st *ce;
1056
1057
0
  gnutls_pk_params_init(&pkey->params);
1058
1059
0
  curve = gnutls_oid_to_ecc_curve(oid);
1060
0
  if (curve == GNUTLS_ECC_CURVE_INVALID) {
1061
0
    _gnutls_debug_log("PKCS#8: unknown curve OID %s\n", oid);
1062
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1063
0
  }
1064
1065
0
  ce = _gnutls_ecc_curve_get_params(curve);
1066
0
  if (_curve_is_eddsa(ce)) {
1067
0
    ret = _gnutls_x509_read_string(pkcs8_asn, "privateKey", &tmp,
1068
0
                 ASN1_ETYPE_OCTET_STRING, 1);
1069
0
    if (ret < 0) {
1070
0
      gnutls_assert();
1071
0
      return gnutls_assert_val(ret);
1072
0
    }
1073
1074
0
    if (tmp.size != ce->size) {
1075
0
      gnutls_free(tmp.data);
1076
0
      return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
1077
0
    }
1078
0
    gnutls_free(pkey->params.raw_priv.data);
1079
0
    switch (curve) {
1080
0
    case GNUTLS_ECC_CURVE_ED25519:
1081
0
      pkey->params.algo = GNUTLS_PK_EDDSA_ED25519;
1082
0
      break;
1083
0
    case GNUTLS_ECC_CURVE_ED448:
1084
0
      pkey->params.algo = GNUTLS_PK_EDDSA_ED448;
1085
0
      break;
1086
0
    default:
1087
0
      return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1088
0
    }
1089
0
    pkey->params.raw_priv.data = tmp.data;
1090
0
    pkey->params.raw_priv.size = tmp.size;
1091
0
    pkey->params.curve = curve;
1092
1093
0
    tmp.data = NULL;
1094
0
    return 0;
1095
0
  } else {
1096
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1097
0
  }
1098
0
}
1099
1100
static int _decode_pkcs8_modern_ecdh_key(asn1_node pkcs8_asn,
1101
           gnutls_x509_privkey_t pkey,
1102
           const char *oid)
1103
0
{
1104
0
  int ret;
1105
0
  gnutls_datum_t tmp;
1106
0
  gnutls_ecc_curve_t curve = GNUTLS_ECC_CURVE_INVALID;
1107
0
  const gnutls_ecc_curve_entry_st *ce;
1108
1109
0
  gnutls_pk_params_init(&pkey->params);
1110
1111
0
  curve = gnutls_oid_to_ecc_curve(oid);
1112
0
  if (curve == GNUTLS_ECC_CURVE_INVALID) {
1113
0
    _gnutls_debug_log("PKCS#8: unknown curve OID %s\n", oid);
1114
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1115
0
  }
1116
1117
0
  ce = _gnutls_ecc_curve_get_params(curve);
1118
0
  if (_curve_is_modern_ecdh(ce)) {
1119
0
    ret = _gnutls_x509_read_string(pkcs8_asn, "privateKey", &tmp,
1120
0
                 ASN1_ETYPE_OCTET_STRING, 1);
1121
0
    if (ret < 0) {
1122
0
      gnutls_assert();
1123
0
      return gnutls_assert_val(ret);
1124
0
    }
1125
1126
0
    if (tmp.size != ce->size) {
1127
0
      gnutls_free(tmp.data);
1128
0
      return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
1129
0
    }
1130
0
    gnutls_free(pkey->params.raw_priv.data);
1131
0
    switch (curve) {
1132
0
    case GNUTLS_ECC_CURVE_X25519:
1133
0
      pkey->params.algo = GNUTLS_PK_ECDH_X25519;
1134
0
      break;
1135
0
    case GNUTLS_ECC_CURVE_X448:
1136
0
      pkey->params.algo = GNUTLS_PK_ECDH_X448;
1137
0
      break;
1138
0
    default:
1139
0
      return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1140
0
    }
1141
0
    pkey->params.raw_priv.data = tmp.data;
1142
0
    pkey->params.raw_priv.size = tmp.size;
1143
0
    pkey->params.curve = curve;
1144
1145
0
    tmp.data = NULL;
1146
0
    return 0;
1147
0
  } else {
1148
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1149
0
  }
1150
0
}
1151
1152
/* Converts a GOST key to
1153
 * an internal structure (gnutls_private_key)
1154
 */
1155
static int _privkey_decode_gost_key(const gnutls_datum_t *raw_key,
1156
            gnutls_x509_privkey_t pkey)
1157
0
{
1158
0
  int ret;
1159
0
  int ecc_size = gnutls_ecc_curve_get_size(pkey->params.curve);
1160
1161
  /* Just to be sure here */
1162
0
  if (ecc_size <= 0) {
1163
0
    gnutls_assert();
1164
0
    ret = GNUTLS_E_ECC_UNSUPPORTED_CURVE;
1165
0
    goto error;
1166
0
  }
1167
1168
  /* Private key form described in R 50.1.112-2016.
1169
   * Private key can come up as masked value concatenated with several masks.
1170
   * each part is of ecc_size bytes. Key will be unmasked in pk_fixup */
1171
0
  if (raw_key->size % ecc_size == 0) {
1172
0
    ret = _gnutls_mpi_init_scan_le(&pkey->params.params[GOST_K],
1173
0
                 raw_key->data, raw_key->size);
1174
0
    if (ret < 0) {
1175
0
      gnutls_assert();
1176
0
      goto error;
1177
0
    }
1178
0
  } else if (raw_key->data[0] == ASN1_TAG_INTEGER) {
1179
0
    asn1_node pkey_asn;
1180
1181
    /* Very old format: INTEGER packed in OCTET STRING */
1182
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
1183
0
                 "GNUTLS.GOSTPrivateKeyOld",
1184
0
                 &pkey_asn)) != ASN1_SUCCESS) {
1185
0
      gnutls_assert();
1186
0
      ret = _gnutls_asn2err(ret);
1187
0
      goto error;
1188
0
    }
1189
1190
0
    ret = _asn1_strict_der_decode(&pkey_asn, raw_key->data,
1191
0
                raw_key->size, NULL);
1192
0
    if (ret != ASN1_SUCCESS) {
1193
0
      gnutls_assert();
1194
0
      ret = _gnutls_asn2err(ret);
1195
0
      asn1_delete_structure2(&pkey_asn,
1196
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1197
0
      goto error;
1198
0
    }
1199
1200
0
    ret = _gnutls_x509_read_key_int(pkey_asn, "",
1201
0
            &pkey->params.params[GOST_K]);
1202
0
    if (ret < 0) {
1203
0
      gnutls_assert();
1204
0
      asn1_delete_structure2(&pkey_asn,
1205
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1206
0
      goto error;
1207
0
    }
1208
0
    asn1_delete_structure2(&pkey_asn, ASN1_DELETE_FLAG_ZEROIZE);
1209
0
  } else if (raw_key->data[0] == ASN1_TAG_OCTET_STRING) {
1210
0
    asn1_node pkey_asn;
1211
1212
    /* format: OCTET STRING packed in OCTET STRING */
1213
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
1214
0
                 "GNUTLS.GOSTPrivateKey",
1215
0
                 &pkey_asn)) != ASN1_SUCCESS) {
1216
0
      gnutls_assert();
1217
0
      ret = _gnutls_asn2err(ret);
1218
0
      goto error;
1219
0
    }
1220
1221
0
    ret = _asn1_strict_der_decode(&pkey_asn, raw_key->data,
1222
0
                raw_key->size, NULL);
1223
0
    if (ret != ASN1_SUCCESS) {
1224
0
      gnutls_assert();
1225
0
      ret = _gnutls_asn2err(ret);
1226
0
      asn1_delete_structure2(&pkey_asn,
1227
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1228
0
      goto error;
1229
0
    }
1230
1231
0
    ret = _gnutls_x509_read_key_int_le(
1232
0
      pkey_asn, "", &pkey->params.params[GOST_K]);
1233
0
    if (ret < 0) {
1234
0
      gnutls_assert();
1235
0
      asn1_delete_structure2(&pkey_asn,
1236
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1237
0
      goto error;
1238
0
    }
1239
0
    asn1_delete_structure2(&pkey_asn, ASN1_DELETE_FLAG_ZEROIZE);
1240
0
  } else {
1241
0
    gnutls_assert();
1242
0
    ret = GNUTLS_E_PARSING_ERROR;
1243
0
    goto error;
1244
0
  }
1245
1246
0
  pkey->params.params_nr++;
1247
1248
0
  return 0;
1249
1250
0
error:
1251
0
  return ret;
1252
0
}
1253
1254
/* Decodes a GOST privateKey from a PKCS8 structure.
1255
 */
1256
static int _decode_pkcs8_gost_key(asn1_node pkcs8_asn,
1257
          gnutls_x509_privkey_t pkey,
1258
          gnutls_pk_algorithm_t algo)
1259
0
{
1260
0
  int ret;
1261
0
  gnutls_datum_t tmp;
1262
0
  unsigned char
1263
0
    oid[3 *
1264
0
        MAX_OID_SIZE]; /* GOST parameters can have 3 OIDs at most */
1265
0
  int len, result;
1266
1267
0
  gnutls_pk_params_init(&pkey->params);
1268
1269
0
  len = sizeof(oid);
1270
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.parameters",
1271
0
         oid, &len);
1272
0
  if (result != ASN1_SUCCESS) {
1273
0
    gnutls_assert();
1274
0
    ret = GNUTLS_E_PARSING_ERROR;
1275
0
    goto error;
1276
0
  } else {
1277
0
    ret = _gnutls_x509_read_gost_params(oid, len, &pkey->params,
1278
0
                algo);
1279
0
    if (ret < 0) {
1280
0
      gnutls_assert();
1281
0
      goto error;
1282
0
    }
1283
0
  }
1284
1285
  /* Will be fixed later by pk_fixup */
1286
0
  ret = _gnutls_mpi_init(&pkey->params.params[GOST_X]);
1287
0
  if (ret < 0) {
1288
0
    gnutls_assert();
1289
0
    goto error;
1290
0
  }
1291
0
  pkey->params.params_nr++;
1292
1293
0
  ret = _gnutls_mpi_init(&pkey->params.params[GOST_Y]);
1294
0
  if (ret < 0) {
1295
0
    gnutls_assert();
1296
0
    goto error;
1297
0
  }
1298
0
  pkey->params.params_nr++;
1299
1300
0
  _gnutls_mpi_set_ui(pkey->params.params[GOST_X], 0);
1301
0
  _gnutls_mpi_set_ui(pkey->params.params[GOST_Y], 0);
1302
1303
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1304
0
  if (ret < 0) {
1305
0
    gnutls_assert();
1306
0
    goto error;
1307
0
  }
1308
1309
0
  ret = _privkey_decode_gost_key(&tmp, pkey);
1310
0
  _gnutls_free_key_datum(&tmp);
1311
1312
0
  if (ret < 0) {
1313
0
    gnutls_assert();
1314
0
    goto error;
1315
0
  }
1316
1317
0
  pkey->params.algo = algo;
1318
1319
0
  return 0;
1320
1321
0
error:
1322
0
  gnutls_pk_params_clear(&pkey->params);
1323
0
  gnutls_pk_params_release(&pkey->params);
1324
1325
0
  return ret;
1326
0
}
1327
1328
/* Decodes an DSA privateKey and params from a PKCS8 structure.
1329
 */
1330
static int _decode_pkcs8_dsa_key(asn1_node pkcs8_asn,
1331
         gnutls_x509_privkey_t pkey)
1332
0
{
1333
0
  int ret;
1334
0
  gnutls_datum_t tmp = { NULL, 0 };
1335
1336
0
  gnutls_pk_params_init(&pkey->params);
1337
1338
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1339
0
  if (ret < 0) {
1340
0
    gnutls_assert();
1341
0
    goto error;
1342
0
  }
1343
1344
0
  ret = _gnutls_x509_read_der_int(tmp.data, tmp.size,
1345
0
          &pkey->params.params[4]);
1346
0
  _gnutls_free_key_datum(&tmp);
1347
1348
0
  if (ret < 0) {
1349
0
    gnutls_assert();
1350
0
    goto error;
1351
0
  }
1352
1353
0
  ret = _gnutls_x509_read_value(pkcs8_asn,
1354
0
              "privateKeyAlgorithm.parameters", &tmp);
1355
0
  if (ret < 0) {
1356
0
    gnutls_assert();
1357
0
    goto error;
1358
0
  }
1359
1360
0
  ret = _gnutls_x509_read_pubkey_params(GNUTLS_PK_DSA, tmp.data, tmp.size,
1361
0
                &pkey->params);
1362
0
  _gnutls_free_datum(&tmp);
1363
0
  if (ret < 0) {
1364
0
    gnutls_assert();
1365
0
    goto error;
1366
0
  }
1367
1368
0
  if (_gnutls_mpi_cmp_ui(pkey->params.params[0], 0) == 0) {
1369
0
    gnutls_assert();
1370
0
    ret = GNUTLS_E_ILLEGAL_PARAMETER;
1371
0
    goto error;
1372
0
  }
1373
1374
  /* the public key can be generated as g^x mod p */
1375
0
  ret = _gnutls_mpi_init(&pkey->params.params[3]);
1376
0
  if (ret < 0) {
1377
0
    gnutls_assert();
1378
0
    goto error;
1379
0
  }
1380
1381
0
  ret = _gnutls_mpi_powm(pkey->params.params[3], pkey->params.params[2],
1382
0
             pkey->params.params[4], pkey->params.params[0]);
1383
0
  if (ret < 0) {
1384
0
    gnutls_assert();
1385
0
    goto error;
1386
0
  }
1387
1388
0
  pkey->params.algo = GNUTLS_PK_DSA;
1389
0
  pkey->params.params_nr = DSA_PRIVATE_PARAMS;
1390
1391
0
  ret = _gnutls_asn1_encode_privkey(&pkey->key, &pkey->params);
1392
0
  if (ret < 0) {
1393
0
    gnutls_assert();
1394
0
    goto error;
1395
0
  }
1396
1397
0
  return 0;
1398
1399
0
error:
1400
0
  if (pkey->params.params_nr != DSA_PRIVATE_PARAMS)
1401
0
    _gnutls_mpi_release(&pkey->params.params[4]);
1402
0
  return ret;
1403
0
}
1404
1405
static int decode_private_key_info(const gnutls_datum_t *der,
1406
           gnutls_x509_privkey_t pkey)
1407
0
{
1408
0
  int result, len;
1409
0
  char oid[MAX_OID_SIZE];
1410
0
  asn1_node pkcs8_asn = NULL;
1411
0
  gnutls_datum_t sder;
1412
0
  int ret;
1413
1414
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
1415
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
1416
0
            &pkcs8_asn)) != ASN1_SUCCESS) {
1417
0
    gnutls_assert();
1418
0
    result = _gnutls_asn2err(result);
1419
0
    goto error;
1420
0
  }
1421
1422
0
  result =
1423
0
    _asn1_strict_der_decode(&pkcs8_asn, der->data, der->size, NULL);
1424
0
  if (result != ASN1_SUCCESS) {
1425
0
    gnutls_assert();
1426
0
    result = _gnutls_asn2err(result);
1427
0
    goto error;
1428
0
  }
1429
1430
  /* Check the private key algorithm OID
1431
   */
1432
0
  len = sizeof(oid);
1433
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.algorithm",
1434
0
         oid, &len);
1435
0
  if (result != ASN1_SUCCESS) {
1436
0
    gnutls_assert();
1437
0
    result = _gnutls_asn2err(result);
1438
0
    goto error;
1439
0
  }
1440
1441
0
  pkey->params.algo = gnutls_oid_to_pk(oid);
1442
0
  if (pkey->params.algo == GNUTLS_PK_UNKNOWN) {
1443
0
    gnutls_assert();
1444
0
    _gnutls_debug_log(
1445
0
      "PKCS #8 private key OID '%s' is unsupported.\n", oid);
1446
0
    result = GNUTLS_E_UNKNOWN_PK_ALGORITHM;
1447
0
    goto error;
1448
0
  }
1449
1450
  /* Get the DER encoding of the actual private key.
1451
   */
1452
1453
0
  switch (pkey->params.algo) {
1454
0
  case GNUTLS_PK_RSA:
1455
0
    result = _decode_pkcs8_rsa_key(pkcs8_asn, pkey);
1456
0
    break;
1457
0
  case GNUTLS_PK_RSA_PSS:
1458
0
    result = _decode_pkcs8_rsa_pss_key(pkcs8_asn, pkey);
1459
0
    break;
1460
0
  case GNUTLS_PK_DSA:
1461
0
    result = _decode_pkcs8_dsa_key(pkcs8_asn, pkey);
1462
0
    break;
1463
0
  case GNUTLS_PK_ECDSA:
1464
0
    result = _decode_pkcs8_ecc_key(pkcs8_asn, pkey);
1465
0
    break;
1466
0
  case GNUTLS_PK_EDDSA_ED25519:
1467
0
  case GNUTLS_PK_EDDSA_ED448:
1468
0
    result = _decode_pkcs8_eddsa_key(pkcs8_asn, pkey, oid);
1469
0
    break;
1470
0
  case GNUTLS_PK_ECDH_X25519:
1471
0
  case GNUTLS_PK_ECDH_X448:
1472
0
    result = _decode_pkcs8_modern_ecdh_key(pkcs8_asn, pkey, oid);
1473
0
    break;
1474
0
  case GNUTLS_PK_GOST_01:
1475
0
  case GNUTLS_PK_GOST_12_256:
1476
0
  case GNUTLS_PK_GOST_12_512:
1477
0
    result = _decode_pkcs8_gost_key(pkcs8_asn, pkey,
1478
0
            pkey->params.algo);
1479
0
    break;
1480
0
  default:
1481
0
    result = gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);
1482
0
    goto error;
1483
0
  }
1484
1485
0
  if (result < 0) {
1486
0
    gnutls_assert();
1487
0
    goto error;
1488
0
  }
1489
1490
  /* check for provable parameters attribute */
1491
0
  ret = _x509_parse_attribute(pkcs8_asn, "attributes", OID_ATTR_PROV_SEED,
1492
0
            0, 1, &sder);
1493
0
  if (ret >= 0) { /* ignore it when not being present */
1494
0
    ret = _x509_decode_provable_seed(pkey, &sder);
1495
0
    gnutls_free(sder.data);
1496
0
    if (ret < 0) {
1497
0
      gnutls_assert();
1498
0
    }
1499
0
  }
1500
1501
0
  result = 0;
1502
1503
0
error:
1504
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
1505
0
  return result;
1506
0
}
1507
1508
/**
1509
 * gnutls_x509_privkey_import_pkcs8:
1510
 * @key: The data to store the parsed key
1511
 * @data: The DER or PEM encoded key.
1512
 * @format: One of DER or PEM
1513
 * @password: the password to decrypt the key (if it is encrypted).
1514
 * @flags: 0 if encrypted or GNUTLS_PKCS_PLAIN if not encrypted.
1515
 *
1516
 * This function will convert the given DER or PEM encoded PKCS8 2.0
1517
 * encrypted key to the native gnutls_x509_privkey_t format. The
1518
 * output will be stored in @key.  Both RSA and DSA keys can be
1519
 * imported, and flags can only be used to indicate an unencrypted
1520
 * key.
1521
 *
1522
 * The @password can be either ASCII or UTF-8 in the default PBES2
1523
 * encryption schemas, or ASCII for the PKCS12 schemas.
1524
 *
1525
 * If the Certificate is PEM encoded it should have a header of
1526
 * "ENCRYPTED PRIVATE KEY", or "PRIVATE KEY". You only need to
1527
 * specify the flags if the key is DER encoded, since in that case
1528
 * the encryption status cannot be auto-detected.
1529
 *
1530
 * If the %GNUTLS_PKCS_PLAIN flag is specified and the supplied data
1531
 * are encrypted then %GNUTLS_E_DECRYPTION_FAILED is returned.
1532
 *
1533
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
1534
 *   negative error value.
1535
 **/
1536
int gnutls_x509_privkey_import_pkcs8(gnutls_x509_privkey_t key,
1537
             const gnutls_datum_t *data,
1538
             gnutls_x509_crt_fmt_t format,
1539
             const char *password, unsigned int flags)
1540
0
{
1541
0
  int result = 0, need_free = 0;
1542
0
  gnutls_datum_t _data;
1543
1544
0
  if (key == NULL) {
1545
0
    gnutls_assert();
1546
0
    return GNUTLS_E_INVALID_REQUEST;
1547
0
  }
1548
1549
0
  _data.data = data->data;
1550
0
  _data.size = data->size;
1551
1552
0
  key->params.algo = GNUTLS_PK_UNKNOWN;
1553
1554
  /* If the Certificate is in PEM format then decode it
1555
   */
1556
0
  if (format == GNUTLS_X509_FMT_PEM) {
1557
    /* Try the first header 
1558
     */
1559
0
    result = _gnutls_fbase64_decode(PEM_UNENCRYPTED_PKCS8,
1560
0
            data->data, data->size, &_data);
1561
1562
0
    if (result < 0) { /* Try the encrypted header 
1563
           */
1564
0
      result = _gnutls_fbase64_decode(PEM_PKCS8, data->data,
1565
0
              data->size, &_data);
1566
1567
0
      if (result < 0) {
1568
0
        gnutls_assert();
1569
0
        return result;
1570
0
      }
1571
0
    } else if (flags == 0)
1572
0
      flags |= GNUTLS_PKCS_PLAIN;
1573
1574
0
    need_free = 1;
1575
0
  }
1576
1577
0
  if (key->expanded) {
1578
0
    _gnutls_x509_privkey_reinit(key);
1579
0
  }
1580
0
  key->expanded = 1;
1581
1582
  /* Here we don't check for password == NULL to maintain a backwards
1583
   * compatibility behavior, with old versions that were encrypting using
1584
   * a NULL password.
1585
   */
1586
0
  if (flags & GNUTLS_PKCS_PLAIN) {
1587
0
    result = decode_private_key_info(&_data, key);
1588
0
    if (result < 0) { /* check if it is encrypted */
1589
0
      if (pkcs8_key_decode(&_data, "", key, 0) == 0)
1590
0
        result = GNUTLS_E_DECRYPTION_FAILED;
1591
0
    }
1592
0
  } else { /* encrypted. */
1593
0
    result = pkcs8_key_decode(&_data, password, key, 1);
1594
0
  }
1595
1596
0
  if (result < 0) {
1597
0
    gnutls_assert();
1598
0
    goto cleanup;
1599
0
  }
1600
1601
  /* This part is necessary to get the public key on certain algorithms.
1602
   * In the import above we only get the private key. */
1603
0
  result =
1604
0
    _gnutls_pk_fixup(key->params.algo, GNUTLS_IMPORT, &key->params);
1605
0
  if (result < 0) {
1606
0
    gnutls_assert();
1607
0
    goto cleanup;
1608
0
  }
1609
1610
0
  if (need_free)
1611
0
    _gnutls_free_datum(&_data);
1612
1613
  /* The key has now been decoded.
1614
   */
1615
0
  return 0;
1616
1617
0
cleanup:
1618
0
  asn1_delete_structure2(&key->key, ASN1_DELETE_FLAG_ZEROIZE);
1619
0
  key->params.algo = GNUTLS_PK_UNKNOWN;
1620
0
  if (need_free) {
1621
0
    zeroize_temp_key(_data.data, _data.size);
1622
0
    _gnutls_free_datum(&_data);
1623
0
  }
1624
0
  return result;
1625
0
}