Coverage Report

Created: 2025-11-16 07:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnutls/lib/x509/privkey_pkcs8.c
Line
Count
Source
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
typedef enum ml_dsa_privkey_format_flags_t {
55
  ML_DSA_PRIVKEY_FORMAT_NONE = 0,
56
  ML_DSA_PRIVKEY_FORMAT_SEED = 1 << 0,
57
  ML_DSA_PRIVKEY_FORMAT_EXPANDED = 1 << 1,
58
  ML_DSA_PRIVKEY_FORMAT_BOTH = ML_DSA_PRIVKEY_FORMAT_SEED |
59
             ML_DSA_PRIVKEY_FORMAT_EXPANDED,
60
} ml_dsa_privkey_format_flags_t;
61
62
static inline ml_dsa_privkey_format_flags_t
63
flags_to_ml_dsa_privkey_format(gnutls_pkcs_encrypt_flags_t flags)
64
0
{
65
0
  ml_dsa_privkey_format_flags_t format = ML_DSA_PRIVKEY_FORMAT_NONE;
66
67
0
  if (flags & GNUTLS_PKCS_MLDSA_SEED)
68
0
    format |= ML_DSA_PRIVKEY_FORMAT_SEED;
69
0
  if (flags & GNUTLS_PKCS_MLDSA_EXPANDED)
70
0
    format |= ML_DSA_PRIVKEY_FORMAT_EXPANDED;
71
72
0
  return format;
73
0
}
74
75
static int encode_ml_dsa_inner_private_key(const gnutls_x509_privkey_t pkey,
76
             gnutls_datum_t *raw_key,
77
             ml_dsa_privkey_format_flags_t format)
78
0
{
79
0
  int ret = 0;
80
0
  asn1_node inner_asn = NULL;
81
82
  /* The default is the "both" format if seed is available;
83
   * otherwise, "expanded" */
84
0
  if (format == ML_DSA_PRIVKEY_FORMAT_NONE) {
85
0
    format = pkey->params.raw_seed.data ?
86
0
         ML_DSA_PRIVKEY_FORMAT_BOTH :
87
0
         ML_DSA_PRIVKEY_FORMAT_EXPANDED;
88
0
  }
89
90
  /* libtasn1 doesn't support encoding instructions in CHOICE,
91
   * format it manually */
92
0
  if (format == ML_DSA_PRIVKEY_FORMAT_SEED) {
93
0
    raw_key->data = gnutls_malloc(34);
94
0
    if (!raw_key->data)
95
0
      return GNUTLS_E_MEMORY_ERROR;
96
97
0
    raw_key->data[0] = 0x80;
98
0
    raw_key->data[1] = 0x20;
99
0
    memcpy(&raw_key->data[2], pkey->params.raw_seed.data, 32);
100
0
    raw_key->size = 34;
101
0
  } else {
102
0
    int result;
103
104
0
    result = asn1_create_element(_gnutls_get_gnutls_asn(),
105
0
               "GNUTLS.MLDSAInnerPrivateKey",
106
0
               &inner_asn);
107
0
    if (result != ASN1_SUCCESS)
108
0
      return gnutls_assert_val(_gnutls_asn2err(result));
109
110
0
    switch (format) {
111
0
    case ML_DSA_PRIVKEY_FORMAT_EXPANDED:
112
0
      result = asn1_write_value(inner_asn, "", "expandedKey",
113
0
              1);
114
0
      if (result != ASN1_SUCCESS) {
115
0
        gnutls_assert();
116
0
        ret = _gnutls_asn2err(result);
117
0
        goto cleanup;
118
0
      }
119
0
      result = asn1_write_value(inner_asn, "expandedKey",
120
0
              pkey->params.raw_priv.data,
121
0
              pkey->params.raw_priv.size);
122
0
      if (result != ASN1_SUCCESS) {
123
0
        gnutls_assert();
124
0
        ret = _gnutls_asn2err(result);
125
0
        goto cleanup;
126
0
      }
127
0
      break;
128
0
    case ML_DSA_PRIVKEY_FORMAT_BOTH:
129
0
      result = asn1_write_value(inner_asn, "", "both", 1);
130
0
      if (result != ASN1_SUCCESS) {
131
0
        gnutls_assert();
132
0
        ret = _gnutls_asn2err(result);
133
0
        goto cleanup;
134
0
      }
135
0
      result = asn1_write_value(inner_asn, "both.seed",
136
0
              pkey->params.raw_seed.data,
137
0
              pkey->params.raw_seed.size);
138
0
      if (result != ASN1_SUCCESS) {
139
0
        gnutls_assert();
140
0
        ret = _gnutls_asn2err(result);
141
0
        goto cleanup;
142
0
      }
143
0
      result = asn1_write_value(inner_asn, "both.expandedKey",
144
0
              pkey->params.raw_priv.data,
145
0
              pkey->params.raw_priv.size);
146
0
      if (result != ASN1_SUCCESS) {
147
0
        gnutls_assert();
148
0
        ret = _gnutls_asn2err(result);
149
0
        goto cleanup;
150
0
      }
151
0
      break;
152
0
    default:
153
0
      ret = gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
154
0
      goto cleanup;
155
0
    }
156
157
0
    ret = _gnutls_x509_der_encode(inner_asn, "", raw_key, 0);
158
0
    if (ret < 0) {
159
0
      gnutls_assert();
160
0
      goto cleanup;
161
0
    }
162
0
  }
163
164
0
cleanup:
165
0
  asn1_delete_structure2(&inner_asn, ASN1_DELETE_FLAG_ZEROIZE);
166
0
  return ret;
167
0
}
168
169
/* Encodes a private key to the raw format PKCS #8 needs.
170
 * For RSA it is a PKCS #1 DER private key and for DSA it is
171
 * an ASN.1 INTEGER of the x value.
172
 */
173
inline static int _encode_privkey(gnutls_x509_privkey_t pkey,
174
          gnutls_datum_t *raw,
175
          gnutls_pkcs_encrypt_flags_t flags)
176
0
{
177
0
  int ret;
178
0
  asn1_node spk = NULL;
179
180
0
  switch (pkey->params.algo) {
181
0
  case GNUTLS_PK_EDDSA_ED25519:
182
0
  case GNUTLS_PK_EDDSA_ED448:
183
0
  case GNUTLS_PK_ECDH_X25519:
184
0
  case GNUTLS_PK_ECDH_X448:
185
    /* we encode as octet string (which is going to be stored inside
186
     * another octet string). No comments. */
187
0
    ret = _gnutls_x509_encode_string(ASN1_ETYPE_OCTET_STRING,
188
0
             pkey->params.raw_priv.data,
189
0
             pkey->params.raw_priv.size,
190
0
             raw);
191
0
    if (ret < 0)
192
0
      gnutls_assert();
193
0
    return ret;
194
0
  case GNUTLS_PK_MLDSA44:
195
0
  case GNUTLS_PK_MLDSA65:
196
0
  case GNUTLS_PK_MLDSA87:
197
0
    ret = encode_ml_dsa_inner_private_key(
198
0
      pkey, raw, flags_to_ml_dsa_privkey_format(flags));
199
0
    if (ret < 0)
200
0
      gnutls_assert();
201
0
    break;
202
0
  case GNUTLS_PK_GOST_01:
203
0
  case GNUTLS_PK_GOST_12_256:
204
0
  case GNUTLS_PK_GOST_12_512:
205
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
206
0
                 "GNUTLS.GOSTPrivateKey",
207
0
                 &spk)) != ASN1_SUCCESS) {
208
0
      gnutls_assert();
209
0
      ret = _gnutls_asn2err(ret);
210
0
      goto error;
211
0
    }
212
213
0
    ret = _gnutls_x509_write_key_int_le(
214
0
      spk, "", pkey->params.params[GOST_K]);
215
0
    if (ret < 0) {
216
0
      gnutls_assert();
217
0
      goto error;
218
0
    }
219
220
0
    ret = _gnutls_x509_der_encode(spk, "", raw, 0);
221
0
    if (ret < 0) {
222
0
      gnutls_assert();
223
0
      goto error;
224
0
    }
225
226
0
    asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
227
0
    break;
228
229
0
  case GNUTLS_PK_RSA:
230
0
  case GNUTLS_PK_RSA_PSS:
231
0
  case GNUTLS_PK_RSA_OAEP:
232
0
  case GNUTLS_PK_ECDSA:
233
0
    ret = _gnutls_x509_export_int2(pkey->key, GNUTLS_X509_FMT_DER,
234
0
                 "", raw);
235
0
    if (ret < 0) {
236
0
      gnutls_assert();
237
0
      goto error;
238
0
    }
239
240
0
    break;
241
0
  case GNUTLS_PK_DSA:
242
    /* DSAPublicKey == INTEGER */
243
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
244
0
                 "GNUTLS.DSAPublicKey", &spk)) !=
245
0
        ASN1_SUCCESS) {
246
0
      gnutls_assert();
247
0
      return _gnutls_asn2err(ret);
248
0
    }
249
250
0
    ret = _gnutls_x509_write_int(spk, "", pkey->params.params[4],
251
0
               1);
252
0
    if (ret < 0) {
253
0
      gnutls_assert();
254
0
      goto error;
255
0
    }
256
0
    ret = _gnutls_x509_der_encode(spk, "", raw, 0);
257
0
    if (ret < 0) {
258
0
      gnutls_assert();
259
0
      goto error;
260
0
    }
261
262
0
    asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
263
0
    break;
264
265
0
  default:
266
0
    gnutls_assert();
267
0
    return GNUTLS_E_INVALID_REQUEST;
268
0
  }
269
270
0
  return 0;
271
272
0
error:
273
0
  asn1_delete_structure2(&spk, ASN1_DELETE_FLAG_ZEROIZE);
274
0
  return ret;
275
0
}
276
277
/* 
278
 * Encodes a PKCS #1 private key to a PKCS #8 private key
279
 * info. The output will be allocated and stored into der. Also
280
 * the asn1_node of private key info will be returned.
281
 */
282
static int encode_to_private_key_info(gnutls_x509_privkey_t pkey,
283
              gnutls_datum_t *der, asn1_node *pkey_info,
284
              gnutls_pkcs_encrypt_flags_t flags)
285
0
{
286
0
  int result, len;
287
0
  uint8_t null = 0;
288
0
  const char *oid;
289
0
  gnutls_datum_t algo_params = { NULL, 0 };
290
0
  gnutls_datum_t algo_privkey = { NULL, 0 };
291
292
0
  oid = gnutls_pk_get_oid(pkey->params.algo);
293
0
  if (oid == NULL) {
294
0
    gnutls_assert();
295
0
    return GNUTLS_E_UNIMPLEMENTED_FEATURE;
296
0
  }
297
298
0
  result = _gnutls_x509_write_pubkey_params(&pkey->params, &algo_params);
299
0
  if (result < 0) {
300
0
    gnutls_assert();
301
0
    return result;
302
0
  }
303
304
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
305
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
306
0
            pkey_info)) != ASN1_SUCCESS) {
307
0
    gnutls_assert();
308
0
    result = _gnutls_asn2err(result);
309
0
    goto error;
310
0
  }
311
312
  /* Write the version.
313
   */
314
0
  result = asn1_write_value(*pkey_info, "version", &null, 1);
315
0
  if (result != ASN1_SUCCESS) {
316
0
    gnutls_assert();
317
0
    result = _gnutls_asn2err(result);
318
0
    goto error;
319
0
  }
320
321
  /* write the privateKeyAlgorithm
322
   * fields. (OID+NULL data)
323
   */
324
0
  result = asn1_write_value(*pkey_info, "privateKeyAlgorithm.algorithm",
325
0
          oid, 1);
326
0
  if (result != ASN1_SUCCESS) {
327
0
    gnutls_assert();
328
0
    result = _gnutls_asn2err(result);
329
0
    goto error;
330
0
  }
331
332
0
  result = asn1_write_value(*pkey_info, "privateKeyAlgorithm.parameters",
333
0
          algo_params.data, algo_params.size);
334
0
  _gnutls_free_key_datum(&algo_params);
335
336
0
  if (result != ASN1_SUCCESS) {
337
0
    gnutls_assert();
338
0
    result = _gnutls_asn2err(result);
339
0
    goto error;
340
0
  }
341
342
  /* Write the raw private key
343
   */
344
0
  result = _encode_privkey(pkey, &algo_privkey, flags);
345
0
  if (result < 0) {
346
0
    gnutls_assert();
347
0
    goto error;
348
0
  }
349
350
0
  result = asn1_write_value(*pkey_info, "privateKey", algo_privkey.data,
351
0
          algo_privkey.size);
352
0
  _gnutls_free_key_datum(&algo_privkey);
353
354
0
  if (result != ASN1_SUCCESS) {
355
0
    gnutls_assert();
356
0
    result = _gnutls_asn2err(result);
357
0
    goto error;
358
0
  }
359
360
0
  if ((pkey->params.pkflags & GNUTLS_PK_FLAG_PROVABLE) &&
361
0
      pkey->params.seed_size > 0) {
362
0
    gnutls_datum_t seed_info;
363
    /* rfc8479 attribute encoding */
364
365
0
    result = _x509_encode_provable_seed(pkey, &seed_info);
366
0
    if (result < 0) {
367
0
      gnutls_assert();
368
0
      goto error;
369
0
    }
370
371
0
    result = _x509_set_attribute(*pkey_info, "attributes",
372
0
               OID_ATTR_PROV_SEED, &seed_info);
373
0
    gnutls_free(seed_info.data);
374
0
    if (result < 0) {
375
0
      gnutls_assert();
376
0
      goto error;
377
0
    }
378
0
  } else {
379
    /* Append an empty attributes field.
380
     */
381
0
    result = asn1_write_value(*pkey_info, "attributes", NULL, 0);
382
0
    if (result != ASN1_SUCCESS) {
383
0
      gnutls_assert();
384
0
      result = _gnutls_asn2err(result);
385
0
      goto error;
386
0
    }
387
0
  }
388
389
  /* Append an empty publicKey field.
390
   */
391
0
  result = asn1_write_value(*pkey_info, "publicKey", NULL, 0);
392
0
  if (result != ASN1_SUCCESS) {
393
0
    gnutls_assert();
394
0
    result = _gnutls_asn2err(result);
395
0
    goto error;
396
0
  }
397
398
  /* DER Encode the generated private key info.
399
   */
400
0
  len = 0;
401
0
  result = asn1_der_coding(*pkey_info, "", NULL, &len, NULL);
402
0
  if (result != ASN1_MEM_ERROR) {
403
0
    gnutls_assert();
404
0
    result = _gnutls_asn2err(result);
405
0
    goto error;
406
0
  }
407
408
  /* allocate data for the der
409
   */
410
0
  der->size = len;
411
0
  der->data = gnutls_malloc(len);
412
0
  if (der->data == NULL) {
413
0
    gnutls_assert();
414
0
    return GNUTLS_E_MEMORY_ERROR;
415
0
  }
416
417
0
  result = asn1_der_coding(*pkey_info, "", der->data, &len, NULL);
418
0
  if (result != ASN1_SUCCESS) {
419
0
    gnutls_assert();
420
0
    result = _gnutls_asn2err(result);
421
0
    goto error;
422
0
  }
423
424
0
  return 0;
425
426
0
error:
427
0
  asn1_delete_structure2(pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
428
0
  _gnutls_free_datum(&algo_params);
429
0
  _gnutls_free_key_datum(&algo_privkey);
430
0
  return result;
431
0
}
432
433
/* Converts a PKCS #8 private key info to
434
 * a PKCS #8 EncryptedPrivateKeyInfo.
435
 */
436
static int encode_to_pkcs8_key(schema_id schema, const gnutls_datum_t *der_key,
437
             const char *password, asn1_node *out)
438
0
{
439
0
  int result;
440
0
  gnutls_datum_t key = { NULL, 0 };
441
0
  gnutls_datum_t tmp = { NULL, 0 };
442
0
  asn1_node pkcs8_asn = NULL;
443
0
  struct pbkdf2_params kdf_params;
444
0
  struct pbe_enc_params enc_params;
445
0
  const struct pkcs_cipher_schema_st *s;
446
447
0
  s = _gnutls_pkcs_schema_get(schema);
448
0
  if (s == NULL || s->decrypt_only) {
449
0
    return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
450
0
  }
451
452
0
  if ((result = asn1_create_element(
453
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
454
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
455
0
    gnutls_assert();
456
0
    return _gnutls_asn2err(result);
457
0
  }
458
459
  /* Write the encryption schema OID
460
   */
461
0
  result = asn1_write_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
462
0
          s->write_oid, 1);
463
464
0
  if (result != ASN1_SUCCESS) {
465
0
    gnutls_assert();
466
0
    result = _gnutls_asn2err(result);
467
0
    goto error;
468
0
  }
469
470
  /* Generate a symmetric key.
471
   */
472
473
0
  result = _gnutls_pkcs_generate_key(schema, password, &kdf_params,
474
0
             &enc_params, &key);
475
0
  if (result < 0) {
476
0
    gnutls_assert();
477
0
    goto error;
478
0
  }
479
480
0
  result = _gnutls_pkcs_write_schema_params(
481
0
    schema, pkcs8_asn, "encryptionAlgorithm.parameters",
482
0
    &kdf_params, &enc_params);
483
0
  if (result < 0) {
484
0
    gnutls_assert();
485
0
    goto error;
486
0
  }
487
488
  /* Parameters have been encoded. Now
489
   * encrypt the Data.
490
   */
491
0
  result =
492
0
    _gnutls_pkcs_raw_encrypt_data(der_key, &enc_params, &key, &tmp);
493
0
  if (result < 0) {
494
0
    gnutls_assert();
495
0
    goto error;
496
0
  }
497
498
  /* write the encrypted data.
499
   */
500
0
  result = asn1_write_value(pkcs8_asn, "encryptedData", tmp.data,
501
0
          tmp.size);
502
0
  if (result != ASN1_SUCCESS) {
503
0
    gnutls_assert();
504
0
    result = _gnutls_asn2err(result);
505
0
    goto error;
506
0
  }
507
508
0
  _gnutls_free_datum(&tmp);
509
0
  _gnutls_free_key_datum(&key);
510
511
0
  *out = pkcs8_asn;
512
513
0
  return 0;
514
515
0
error:
516
0
  _gnutls_free_key_datum(&key);
517
0
  _gnutls_free_datum(&tmp);
518
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
519
0
  return result;
520
0
}
521
522
/**
523
 * gnutls_x509_privkey_export_pkcs8:
524
 * @key: Holds the key
525
 * @format: the format of output params. One of PEM or DER.
526
 * @password: the password that will be used to encrypt the key.
527
 * @flags: an ORed sequence of gnutls_pkcs_encrypt_flags_t
528
 * @output_data: will contain a private key PEM or DER encoded
529
 * @output_data_size: holds the size of output_data (and will be
530
 *   replaced by the actual size of parameters)
531
 *
532
 * This function will export the private key to a PKCS8 structure.
533
 * Both RSA and DSA keys can be exported. For DSA keys we use
534
 * PKCS #11 definitions. If the flags do not specify the encryption
535
 * cipher, then the default 3DES (PBES2) will be used.
536
 *
537
 * The @password can be either ASCII or UTF-8 in the default PBES2
538
 * encryption schemas, or ASCII for the PKCS12 schemas.
539
 *
540
 * If the buffer provided is not long enough to hold the output, then
541
 * *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
542
 * be returned.
543
 *
544
 * If the structure is PEM encoded, it will have a header
545
 * of "BEGIN ENCRYPTED PRIVATE KEY" or "BEGIN PRIVATE KEY" if
546
 * encryption is not used.
547
 *
548
 * Returns: In case of failure a negative error code will be
549
 *   returned, and 0 on success.
550
 **/
551
int gnutls_x509_privkey_export_pkcs8(gnutls_x509_privkey_t key,
552
             gnutls_x509_crt_fmt_t format,
553
             const char *password, unsigned int flags,
554
             void *output_data,
555
             size_t *output_data_size)
556
0
{
557
0
  asn1_node pkcs8_asn = NULL, pkey_info;
558
0
  int ret;
559
0
  gnutls_datum_t tmp = { NULL, 0 };
560
0
  schema_id schema;
561
562
0
  if (key == NULL) {
563
0
    gnutls_assert();
564
0
    return GNUTLS_E_INVALID_REQUEST;
565
0
  }
566
567
  /* Get the private key info
568
   * tmp holds the DER encoding.
569
   */
570
0
  ret = encode_to_private_key_info(key, &tmp, &pkey_info, flags);
571
0
  if (ret < 0) {
572
0
    gnutls_assert();
573
0
    return ret;
574
0
  }
575
576
0
  schema = _gnutls_pkcs_flags_to_schema(flags);
577
578
0
  if (((flags & GNUTLS_PKCS_PLAIN) || password == NULL) &&
579
0
      !(flags & GNUTLS_PKCS_NULL_PASSWORD)) {
580
0
    _gnutls_free_datum(&tmp);
581
582
0
    ret = _gnutls_x509_export_int(pkey_info, format,
583
0
                PEM_UNENCRYPTED_PKCS8,
584
0
                output_data, output_data_size);
585
586
0
    asn1_delete_structure2(&pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
587
0
  } else {
588
0
    asn1_delete_structure2(
589
0
      &pkey_info,
590
0
      ASN1_DELETE_FLAG_ZEROIZE); /* we don't need it */
591
592
0
    ret = encode_to_pkcs8_key(schema, &tmp, password, &pkcs8_asn);
593
0
    _gnutls_free_key_datum(&tmp);
594
595
0
    if (ret < 0) {
596
0
      gnutls_assert();
597
0
      return ret;
598
0
    }
599
600
0
    ret = _gnutls_x509_export_int(pkcs8_asn, format, PEM_PKCS8,
601
0
                output_data, output_data_size);
602
603
0
    asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
604
0
  }
605
606
0
  return ret;
607
0
}
608
609
/**
610
 * gnutls_pkcs8_info:
611
 * @data: Holds the PKCS #8 data
612
 * @format: the format of the PKCS #8 data
613
 * @schema: indicate the schema as one of %gnutls_pkcs_encrypt_flags_t
614
 * @cipher: the cipher used as %gnutls_cipher_algorithm_t
615
 * @salt: PBKDF2 salt (if non-NULL then @salt_size initially holds its size)
616
 * @salt_size: PBKDF2 salt size
617
 * @iter_count: PBKDF2 iteration count
618
 * @oid: if non-NULL it will contain an allocated null-terminated variable with the OID
619
 *
620
 * This function will provide information on the algorithms used
621
 * in a particular PKCS #8 structure. If the structure algorithms
622
 * are unknown the code %GNUTLS_E_UNKNOWN_CIPHER_TYPE will be returned,
623
 * and only @oid, will be set. That is, @oid will be set on encrypted PKCS #8
624
 * structures whether supported or not. It must be deinitialized using gnutls_free().
625
 * The other variables are only set on supported structures.
626
 *
627
 * Returns: %GNUTLS_E_INVALID_REQUEST if the provided structure isn't an encrypted key,
628
 *  %GNUTLS_E_UNKNOWN_CIPHER_TYPE if the structure's encryption isn't supported, or
629
 *  another negative error code in case of a failure. Zero on success.
630
 *
631
 * Since: 3.4.0
632
 **/
633
int gnutls_pkcs8_info(const gnutls_datum_t *data, gnutls_x509_crt_fmt_t format,
634
          unsigned int *schema, unsigned int *cipher, void *salt,
635
          unsigned int *salt_size, unsigned int *iter_count,
636
          char **oid)
637
0
{
638
0
  int ret = 0, need_free = 0;
639
0
  gnutls_datum_t _data;
640
0
  const struct pkcs_cipher_schema_st *p = NULL;
641
0
  struct pbkdf2_params kdf;
642
643
0
  memset(&kdf, 0, sizeof(kdf));
644
645
0
  if (oid)
646
0
    *oid = NULL;
647
648
0
  _data.data = data->data;
649
0
  _data.size = data->size;
650
651
  /* If the Certificate is in PEM format then decode it
652
   */
653
0
  if (format == GNUTLS_X509_FMT_PEM) {
654
    /* Try the first header 
655
     */
656
0
    ret = _gnutls_fbase64_decode(PEM_UNENCRYPTED_PKCS8, data->data,
657
0
               data->size, &_data);
658
659
0
    if (ret < 0) { /* Try the encrypted header 
660
         */
661
0
      ret = _gnutls_fbase64_decode(PEM_PKCS8, data->data,
662
0
                 data->size, &_data);
663
664
0
      if (ret < 0) {
665
0
        gnutls_assert();
666
0
        return ret;
667
0
      }
668
0
    }
669
670
0
    need_free = 1;
671
0
  }
672
673
0
  ret = pkcs8_key_info(&_data, &p, &kdf, oid);
674
0
  if (ret == GNUTLS_E_DECRYPTION_FAILED)
675
0
    ret = GNUTLS_E_INVALID_REQUEST;
676
0
  if (ret < 0) {
677
0
    gnutls_assert();
678
0
    goto cleanup;
679
0
  }
680
681
0
  assert(p != NULL);
682
683
0
  if (need_free)
684
0
    _gnutls_free_datum(&_data);
685
686
0
  if (schema)
687
0
    *schema = p->flag;
688
689
0
  if (cipher)
690
0
    *cipher = p->cipher;
691
692
0
  if (iter_count)
693
0
    *iter_count = kdf.iter_count;
694
695
0
  if (salt) {
696
0
    if (*salt_size >= (unsigned)kdf.salt_size) {
697
0
      memcpy(salt, kdf.salt, kdf.salt_size);
698
0
    } else {
699
0
      *salt_size = kdf.salt_size;
700
0
      ret = gnutls_assert_val(GNUTLS_E_SHORT_MEMORY_BUFFER);
701
0
      goto cleanup;
702
0
    }
703
0
  }
704
705
0
  if (salt_size)
706
0
    *salt_size = kdf.salt_size;
707
708
0
  return 0;
709
710
0
cleanup:
711
0
  if (ret != GNUTLS_E_UNKNOWN_CIPHER_TYPE && oid) {
712
0
    gnutls_free(*oid);
713
0
  }
714
0
  if (need_free)
715
0
    _gnutls_free_datum(&_data);
716
0
  return ret;
717
0
}
718
719
/**
720
 * gnutls_x509_privkey_export2_pkcs8:
721
 * @key: Holds the key
722
 * @format: the format of output params. One of PEM or DER.
723
 * @password: the password that will be used to encrypt the key.
724
 * @flags: an ORed sequence of gnutls_pkcs_encrypt_flags_t
725
 * @out: will contain a private key PEM or DER encoded
726
 *
727
 * This function will export the private key to a PKCS8 structure.
728
 * Both RSA and DSA keys can be exported. For DSA keys we use
729
 * PKCS #11 definitions. If the flags do not specify the encryption
730
 * cipher, then the default 3DES (PBES2) will be used.
731
 *
732
 * The @password can be either ASCII or UTF-8 in the default PBES2
733
 * encryption schemas, or ASCII for the PKCS12 schemas.
734
 *
735
 * The output buffer is allocated using gnutls_malloc().
736
 *
737
 * If the structure is PEM encoded, it will have a header
738
 * of "BEGIN ENCRYPTED PRIVATE KEY" or "BEGIN PRIVATE KEY" if
739
 * encryption is not used.
740
 *
741
 * Returns: In case of failure a negative error code will be
742
 *   returned, and 0 on success.
743
 *
744
 * Since 3.1.3
745
 **/
746
int gnutls_x509_privkey_export2_pkcs8(gnutls_x509_privkey_t key,
747
              gnutls_x509_crt_fmt_t format,
748
              const char *password, unsigned int flags,
749
              gnutls_datum_t *out)
750
0
{
751
0
  asn1_node pkcs8_asn = NULL, pkey_info;
752
0
  int ret;
753
0
  gnutls_datum_t tmp = { NULL, 0 };
754
0
  schema_id schema;
755
756
0
  if (key == NULL) {
757
0
    gnutls_assert();
758
0
    return GNUTLS_E_INVALID_REQUEST;
759
0
  }
760
761
  /* Get the private key info
762
   * tmp holds the DER encoding.
763
   */
764
0
  ret = encode_to_private_key_info(key, &tmp, &pkey_info, flags);
765
0
  if (ret < 0) {
766
0
    gnutls_assert();
767
0
    return ret;
768
0
  }
769
770
0
  schema = _gnutls_pkcs_flags_to_schema(flags);
771
772
0
  if (((flags & GNUTLS_PKCS_PLAIN) || password == NULL) &&
773
0
      !(flags & GNUTLS_PKCS_NULL_PASSWORD)) {
774
0
    _gnutls_free_key_datum(&tmp);
775
776
0
    ret = _gnutls_x509_export_int2(pkey_info, format,
777
0
                 PEM_UNENCRYPTED_PKCS8, out);
778
779
0
    asn1_delete_structure2(&pkey_info, ASN1_DELETE_FLAG_ZEROIZE);
780
0
  } else {
781
0
    asn1_delete_structure2(
782
0
      &pkey_info,
783
0
      ASN1_DELETE_FLAG_ZEROIZE); /* we don't need it */
784
785
0
    ret = encode_to_pkcs8_key(schema, &tmp, password, &pkcs8_asn);
786
0
    _gnutls_free_key_datum(&tmp);
787
788
0
    if (ret < 0) {
789
0
      gnutls_assert();
790
0
      return ret;
791
0
    }
792
793
0
    ret = _gnutls_x509_export_int2(pkcs8_asn, format, PEM_PKCS8,
794
0
                 out);
795
796
0
    asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
797
0
  }
798
799
0
  return ret;
800
0
}
801
802
/* We've gotten this far. In the real world it's almost certain
803
   * that we're dealing with a good file, but wrong password.
804
   * Sadly like 90% of random data is somehow valid DER for the
805
   * a first small number of bytes, so no easy way to guarantee. */
806
#define CHECK_ERR_FOR_ENCRYPTED(result)                     \
807
0
  if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND ||    \
808
0
      result == GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND || \
809
0
      result == GNUTLS_E_ASN1_DER_ERROR ||            \
810
0
      result == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||      \
811
0
      result == GNUTLS_E_ASN1_GENERIC_ERROR ||        \
812
0
      result == GNUTLS_E_ASN1_VALUE_NOT_VALID ||      \
813
0
      result == GNUTLS_E_ASN1_TAG_ERROR ||            \
814
0
      result == GNUTLS_E_ASN1_TAG_IMPLICIT ||         \
815
0
      result == GNUTLS_E_ASN1_TYPE_ANY_ERROR ||       \
816
0
      result == GNUTLS_E_ASN1_SYNTAX_ERROR ||         \
817
0
      result == GNUTLS_E_ASN1_DER_OVERFLOW) {         \
818
0
    result = GNUTLS_E_DECRYPTION_FAILED;        \
819
0
  }
820
821
static int pkcs8_key_decrypt(const gnutls_datum_t *raw_key, asn1_node pkcs8_asn,
822
           const char *password, gnutls_x509_privkey_t pkey)
823
0
{
824
0
  int result, len;
825
0
  char enc_oid[MAX_OID_SIZE];
826
0
  gnutls_datum_t tmp = { NULL, 0 };
827
0
  int params_start, params_end, params_len;
828
0
  struct pbkdf2_params kdf_params;
829
0
  struct pbe_enc_params enc_params;
830
0
  schema_id schema;
831
832
  /* Check the encryption schema OID
833
   */
834
0
  len = sizeof(enc_oid);
835
0
  result = asn1_read_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
836
0
         enc_oid, &len);
837
0
  if (result != ASN1_SUCCESS) {
838
0
    gnutls_assert();
839
0
    goto error;
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, password,
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
    goto error;
870
0
  }
871
872
  /* Parameters have been decoded. Now
873
   * decrypt the EncryptedData.
874
   */
875
0
  result = _gnutls_pkcs_raw_decrypt_data(schema, pkcs8_asn,
876
0
                 "encryptedData", password,
877
0
                 &kdf_params, &enc_params, &tmp);
878
0
  if (result < 0) {
879
0
    gnutls_assert();
880
0
    result = GNUTLS_E_DECRYPTION_FAILED;
881
0
    goto error;
882
0
  }
883
884
0
  result = decode_private_key_info(&tmp, pkey);
885
0
  _gnutls_free_key_datum(&tmp);
886
887
0
  CHECK_ERR_FOR_ENCRYPTED(result);
888
0
  if (result < 0) {
889
0
    gnutls_assert();
890
0
    goto error;
891
0
  }
892
893
0
  return 0;
894
895
0
error:
896
0
  return result;
897
0
}
898
899
static int check_for_decrypted(const gnutls_datum_t *der)
900
0
{
901
0
  int result;
902
0
  asn1_node pkcs8_asn = NULL;
903
904
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
905
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
906
0
            &pkcs8_asn)) != ASN1_SUCCESS) {
907
0
    gnutls_assert();
908
0
    return _gnutls_asn2err(result);
909
0
  }
910
911
0
  result =
912
0
    _asn1_strict_der_decode(&pkcs8_asn, der->data, der->size, NULL);
913
0
  if (result != ASN1_SUCCESS) {
914
0
    gnutls_assert();
915
0
    result = _gnutls_asn2err(result);
916
0
    goto error;
917
0
  }
918
919
0
  result = 0;
920
0
error:
921
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
922
0
  return result;
923
0
}
924
925
static int pkcs8_key_info(const gnutls_datum_t *raw_key,
926
        const struct pkcs_cipher_schema_st **p,
927
        struct pbkdf2_params *kdf_params, char **oid)
928
0
{
929
0
  int result, len;
930
0
  char enc_oid[MAX_OID_SIZE * 2];
931
0
  int params_start, params_end, params_len;
932
0
  struct pbe_enc_params enc_params;
933
0
  schema_id schema;
934
0
  asn1_node pkcs8_asn = NULL;
935
936
0
  memset(&enc_params, 0, sizeof(enc_params));
937
938
0
  result = check_for_decrypted(raw_key);
939
0
  if (result == 0)
940
0
    return GNUTLS_E_INVALID_REQUEST;
941
942
0
  if ((result = asn1_create_element(
943
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
944
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
945
0
    gnutls_assert();
946
0
    result = _gnutls_asn2err(result);
947
0
    goto error;
948
0
  }
949
950
0
  result = _asn1_strict_der_decode(&pkcs8_asn, raw_key->data,
951
0
           raw_key->size, NULL);
952
0
  if (result != ASN1_SUCCESS) {
953
0
    gnutls_assert();
954
0
    result = _gnutls_asn2err(result);
955
0
    goto error;
956
0
  }
957
958
  /* Check the encryption schema OID
959
   */
960
0
  len = sizeof(enc_oid);
961
0
  result = asn1_read_value(pkcs8_asn, "encryptionAlgorithm.algorithm",
962
0
         enc_oid, &len);
963
0
  if (result != ASN1_SUCCESS) {
964
0
    gnutls_assert();
965
0
    goto error;
966
0
  }
967
968
0
  if (oid) {
969
0
    *oid = gnutls_strdup(enc_oid);
970
0
  }
971
972
0
  if ((result = _gnutls_check_pkcs_cipher_schema(enc_oid)) < 0) {
973
0
    gnutls_assert();
974
0
    goto error;
975
0
  }
976
977
0
  schema = result;
978
979
  /* Get the DER encoding of the parameters.
980
   */
981
0
  result = asn1_der_decoding_startEnd(pkcs8_asn, raw_key->data,
982
0
              raw_key->size,
983
0
              "encryptionAlgorithm.parameters",
984
0
              &params_start, &params_end);
985
0
  if (result != ASN1_SUCCESS) {
986
0
    gnutls_assert();
987
0
    result = _gnutls_asn2err(result);
988
0
    goto error;
989
0
  }
990
0
  params_len = params_end - params_start + 1;
991
992
0
  result = _gnutls_read_pkcs_schema_params(&schema, NULL,
993
0
             &raw_key->data[params_start],
994
0
             params_len, kdf_params,
995
0
             &enc_params);
996
997
0
  if (result < 0) {
998
0
    gnutls_assert();
999
0
    if (oid && enc_params.pbes2_oid[0] != 0) {
1000
0
      snprintf(enc_oid, sizeof(enc_oid), "%s/%s", *oid,
1001
0
         enc_params.pbes2_oid);
1002
0
      gnutls_free(*oid);
1003
0
      *oid = gnutls_strdup(enc_oid);
1004
0
    }
1005
0
    goto error;
1006
0
  }
1007
1008
0
  *p = _gnutls_pkcs_schema_get(schema);
1009
0
  if (*p == NULL) {
1010
0
    gnutls_assert();
1011
0
    result = GNUTLS_E_UNKNOWN_CIPHER_TYPE;
1012
0
    goto error;
1013
0
  }
1014
1015
0
  result = 0;
1016
1017
0
error:
1018
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
1019
0
  return result;
1020
0
}
1021
1022
/* Converts a PKCS #8 key to
1023
 * an internal structure (gnutls_private_key)
1024
 * (normally a PKCS #1 encoded RSA key)
1025
 */
1026
static int pkcs8_key_decode(const gnutls_datum_t *raw_key, const char *password,
1027
          gnutls_x509_privkey_t pkey, unsigned int decrypt)
1028
0
{
1029
0
  int result;
1030
0
  asn1_node pkcs8_asn = NULL;
1031
1032
0
  if ((result = asn1_create_element(
1033
0
         _gnutls_get_pkix(), "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
1034
0
         &pkcs8_asn)) != ASN1_SUCCESS) {
1035
0
    gnutls_assert();
1036
0
    result = _gnutls_asn2err(result);
1037
0
    goto error;
1038
0
  }
1039
1040
0
  result = _asn1_strict_der_decode(&pkcs8_asn, raw_key->data,
1041
0
           raw_key->size, NULL);
1042
0
  if (result != ASN1_SUCCESS) {
1043
0
    gnutls_assert();
1044
0
    result = _gnutls_asn2err(result);
1045
0
    goto error;
1046
0
  }
1047
1048
0
  if (decrypt)
1049
0
    result = pkcs8_key_decrypt(raw_key, pkcs8_asn, password, pkey);
1050
0
  else
1051
0
    result = 0;
1052
1053
0
error:
1054
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
1055
0
  return result;
1056
0
}
1057
1058
/* Decodes an RSA privateKey from a PKCS8 structure.
1059
 */
1060
static int _decode_pkcs8_rsa_key(asn1_node pkcs8_asn,
1061
         gnutls_x509_privkey_t pkey)
1062
0
{
1063
0
  int ret;
1064
0
  gnutls_datum_t tmp = { NULL, 0 };
1065
1066
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1067
0
  if (ret < 0) {
1068
0
    gnutls_assert();
1069
0
    goto error;
1070
0
  }
1071
1072
0
  pkey->key = _gnutls_privkey_decode_pkcs1_rsa_key(&tmp, pkey);
1073
0
  _gnutls_free_key_datum(&tmp);
1074
1075
0
  if (pkey->key == NULL) {
1076
0
    ret = GNUTLS_E_PK_INVALID_PRIVKEY;
1077
0
    gnutls_assert();
1078
0
    goto error;
1079
0
  }
1080
1081
0
  ret = 0;
1082
1083
0
error:
1084
0
  return ret;
1085
0
}
1086
1087
/* Decodes an RSA-PSS privateKey from a PKCS8 structure.
1088
 */
1089
static int _decode_pkcs8_rsa_pss_key(asn1_node pkcs8_asn,
1090
             gnutls_x509_privkey_t pkey)
1091
0
{
1092
0
  int ret;
1093
0
  gnutls_datum_t tmp = { NULL, 0 };
1094
0
  gnutls_x509_spki_st params;
1095
1096
0
  memset(&params, 0, sizeof(params));
1097
1098
0
  ret = _gnutls_x509_read_value(pkcs8_asn,
1099
0
              "privateKeyAlgorithm.parameters", &tmp);
1100
0
  if (ret < 0) {
1101
0
    if (ret == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||
1102
0
        ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
1103
0
      goto skip_params;
1104
1105
0
    gnutls_assert();
1106
0
    goto error;
1107
0
  }
1108
1109
0
  ret = _gnutls_x509_read_rsa_pss_params(tmp.data, tmp.size, &params);
1110
0
  _gnutls_free_key_datum(&tmp);
1111
1112
0
  if (ret < 0) {
1113
0
    gnutls_assert();
1114
0
    goto error;
1115
0
  }
1116
1117
0
skip_params:
1118
0
  ret = _decode_pkcs8_rsa_key(pkcs8_asn, pkey);
1119
0
  if (ret < 0) {
1120
0
    gnutls_assert();
1121
0
    goto error;
1122
0
  }
1123
1124
0
  pkey->params.algo = GNUTLS_PK_RSA_PSS;
1125
0
  ret = _gnutls_x509_spki_copy(&pkey->params.spki, &params);
1126
0
  if (ret < 0) {
1127
0
    gnutls_assert();
1128
0
    goto error;
1129
0
  }
1130
1131
0
  ret = 0;
1132
1133
0
error:
1134
0
  return ret;
1135
0
}
1136
1137
/* Decodes an RSA-OAEP privateKey from a PKCS8 structure.
1138
 */
1139
static int _decode_pkcs8_rsa_oaep_key(asn1_node pkcs8_asn,
1140
              gnutls_x509_privkey_t pkey)
1141
0
{
1142
0
  int ret;
1143
0
  gnutls_datum_t tmp = { NULL, 0 };
1144
0
  gnutls_x509_spki_st params;
1145
1146
0
  memset(&params, 0, sizeof(params));
1147
1148
0
  ret = _gnutls_x509_read_value(pkcs8_asn,
1149
0
              "privateKeyAlgorithm.parameters", &tmp);
1150
0
  if (ret < 0) {
1151
0
    if (ret == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||
1152
0
        ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
1153
0
      goto skip_params;
1154
1155
0
    gnutls_assert();
1156
0
    goto error;
1157
0
  }
1158
1159
0
  ret = _gnutls_x509_read_rsa_oaep_params(tmp.data, tmp.size, &params);
1160
0
  _gnutls_free_key_datum(&tmp);
1161
1162
0
  if (ret < 0) {
1163
0
    gnutls_assert();
1164
0
    goto error;
1165
0
  }
1166
1167
0
skip_params:
1168
0
  ret = _decode_pkcs8_rsa_key(pkcs8_asn, pkey);
1169
0
  if (ret < 0) {
1170
0
    gnutls_assert();
1171
0
    goto error;
1172
0
  }
1173
1174
0
  pkey->params.algo = GNUTLS_PK_RSA_OAEP;
1175
  /* Take ownership of allocated members of params */
1176
0
  pkey->params.spki = params;
1177
1178
0
  ret = 0;
1179
1180
0
error:
1181
0
  return ret;
1182
0
}
1183
1184
/* Decodes an ECC privateKey from a PKCS8 structure.
1185
 */
1186
static int _decode_pkcs8_ecc_key(asn1_node pkcs8_asn,
1187
         gnutls_x509_privkey_t pkey)
1188
0
{
1189
0
  int ret;
1190
0
  gnutls_datum_t tmp = { NULL, 0 };
1191
0
  unsigned char oid[MAX_OID_SIZE];
1192
0
  unsigned curve = GNUTLS_ECC_CURVE_INVALID;
1193
0
  int len, result;
1194
1195
  /* openssl PKCS #8 files with ECC keys place the curve in
1196
   * privateKeyAlgorithm.parameters instead of the ECPrivateKey.parameters.
1197
   */
1198
0
  len = sizeof(oid);
1199
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.parameters",
1200
0
         oid, &len);
1201
0
  if (result == ASN1_SUCCESS) {
1202
0
    ret = _gnutls_x509_read_ecc_params(oid, len, &curve);
1203
0
    if (ret < 0) {
1204
0
      _gnutls_debug_log("PKCS#8: unknown curve OID %s\n",
1205
0
            oid);
1206
0
      curve = GNUTLS_ECC_CURVE_INVALID;
1207
0
    }
1208
0
  }
1209
1210
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1211
0
  if (ret < 0) {
1212
0
    gnutls_assert();
1213
0
    goto error;
1214
0
  }
1215
1216
0
  ret = _gnutls_privkey_decode_ecc_key(&pkey->key, &tmp, pkey, curve);
1217
0
  _gnutls_free_key_datum(&tmp);
1218
1219
0
  if (ret < 0) {
1220
0
    gnutls_assert();
1221
0
    goto error;
1222
0
  }
1223
1224
0
  ret = 0;
1225
1226
0
error:
1227
0
  return ret;
1228
0
}
1229
1230
static int _decode_pkcs8_eddsa_key(asn1_node pkcs8_asn,
1231
           gnutls_x509_privkey_t pkey, const char *oid)
1232
0
{
1233
0
  int ret;
1234
0
  gnutls_datum_t tmp;
1235
0
  gnutls_ecc_curve_t curve = GNUTLS_ECC_CURVE_INVALID;
1236
0
  const gnutls_ecc_curve_entry_st *ce;
1237
1238
0
  gnutls_pk_params_init(&pkey->params);
1239
1240
0
  curve = gnutls_oid_to_ecc_curve(oid);
1241
0
  if (curve == GNUTLS_ECC_CURVE_INVALID) {
1242
0
    _gnutls_debug_log("PKCS#8: unknown curve OID %s\n", oid);
1243
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1244
0
  }
1245
1246
0
  ce = _gnutls_ecc_curve_get_params(curve);
1247
0
  if (_curve_is_eddsa(ce)) {
1248
0
    ret = _gnutls_x509_read_string(pkcs8_asn, "privateKey", &tmp,
1249
0
                 ASN1_ETYPE_OCTET_STRING, 1);
1250
0
    if (ret < 0) {
1251
0
      gnutls_assert();
1252
0
      return gnutls_assert_val(ret);
1253
0
    }
1254
1255
0
    if (tmp.size != ce->size) {
1256
0
      gnutls_free(tmp.data);
1257
0
      return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
1258
0
    }
1259
0
    gnutls_free(pkey->params.raw_priv.data);
1260
0
    switch (curve) {
1261
0
    case GNUTLS_ECC_CURVE_ED25519:
1262
0
      pkey->params.algo = GNUTLS_PK_EDDSA_ED25519;
1263
0
      break;
1264
0
    case GNUTLS_ECC_CURVE_ED448:
1265
0
      pkey->params.algo = GNUTLS_PK_EDDSA_ED448;
1266
0
      break;
1267
0
    default:
1268
0
      return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1269
0
    }
1270
0
    pkey->params.raw_priv.data = tmp.data;
1271
0
    pkey->params.raw_priv.size = tmp.size;
1272
0
    pkey->params.curve = curve;
1273
1274
0
    tmp.data = NULL;
1275
0
    return 0;
1276
0
  } else {
1277
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1278
0
  }
1279
0
}
1280
1281
static int _decode_pkcs8_modern_ecdh_key(asn1_node pkcs8_asn,
1282
           gnutls_x509_privkey_t pkey,
1283
           const char *oid)
1284
0
{
1285
0
  int ret;
1286
0
  gnutls_datum_t tmp;
1287
0
  gnutls_ecc_curve_t curve = GNUTLS_ECC_CURVE_INVALID;
1288
0
  const gnutls_ecc_curve_entry_st *ce;
1289
1290
0
  gnutls_pk_params_init(&pkey->params);
1291
1292
0
  curve = gnutls_oid_to_ecc_curve(oid);
1293
0
  if (curve == GNUTLS_ECC_CURVE_INVALID) {
1294
0
    _gnutls_debug_log("PKCS#8: unknown curve OID %s\n", oid);
1295
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1296
0
  }
1297
1298
0
  ce = _gnutls_ecc_curve_get_params(curve);
1299
0
  if (_curve_is_modern_ecdh(ce)) {
1300
0
    ret = _gnutls_x509_read_string(pkcs8_asn, "privateKey", &tmp,
1301
0
                 ASN1_ETYPE_OCTET_STRING, 1);
1302
0
    if (ret < 0) {
1303
0
      gnutls_assert();
1304
0
      return gnutls_assert_val(ret);
1305
0
    }
1306
1307
0
    if (tmp.size != ce->size) {
1308
0
      gnutls_free(tmp.data);
1309
0
      return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
1310
0
    }
1311
0
    gnutls_free(pkey->params.raw_priv.data);
1312
0
    switch (curve) {
1313
0
    case GNUTLS_ECC_CURVE_X25519:
1314
0
      pkey->params.algo = GNUTLS_PK_ECDH_X25519;
1315
0
      break;
1316
0
    case GNUTLS_ECC_CURVE_X448:
1317
0
      pkey->params.algo = GNUTLS_PK_ECDH_X448;
1318
0
      break;
1319
0
    default:
1320
0
      return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1321
0
    }
1322
0
    pkey->params.raw_priv.data = tmp.data;
1323
0
    pkey->params.raw_priv.size = tmp.size;
1324
0
    pkey->params.curve = curve;
1325
1326
0
    tmp.data = NULL;
1327
0
    return 0;
1328
0
  } else {
1329
0
    return gnutls_assert_val(GNUTLS_E_ECC_UNSUPPORTED_CURVE);
1330
0
  }
1331
0
}
1332
1333
/* Converts a GOST key to
1334
 * an internal structure (gnutls_private_key)
1335
 */
1336
static int _privkey_decode_gost_key(const gnutls_datum_t *raw_key,
1337
            gnutls_x509_privkey_t pkey)
1338
0
{
1339
0
  int ret;
1340
0
  int ecc_size = gnutls_ecc_curve_get_size(pkey->params.curve);
1341
1342
  /* Just to be sure here */
1343
0
  if (ecc_size <= 0) {
1344
0
    gnutls_assert();
1345
0
    ret = GNUTLS_E_ECC_UNSUPPORTED_CURVE;
1346
0
    goto error;
1347
0
  }
1348
1349
  /* Private key form described in R 50.1.112-2016.
1350
   * Private key can come up as masked value concatenated with several masks.
1351
   * each part is of ecc_size bytes. Key will be unmasked in pk_fixup */
1352
0
  if (raw_key->size % ecc_size == 0) {
1353
0
    ret = _gnutls_mpi_init_scan_le(&pkey->params.params[GOST_K],
1354
0
                 raw_key->data, raw_key->size);
1355
0
    if (ret < 0) {
1356
0
      gnutls_assert();
1357
0
      goto error;
1358
0
    }
1359
0
  } else if (raw_key->data[0] == ASN1_TAG_INTEGER) {
1360
0
    asn1_node pkey_asn;
1361
1362
    /* Very old format: INTEGER packed in OCTET STRING */
1363
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
1364
0
                 "GNUTLS.GOSTPrivateKeyOld",
1365
0
                 &pkey_asn)) != ASN1_SUCCESS) {
1366
0
      gnutls_assert();
1367
0
      ret = _gnutls_asn2err(ret);
1368
0
      goto error;
1369
0
    }
1370
1371
0
    ret = _asn1_strict_der_decode(&pkey_asn, raw_key->data,
1372
0
                raw_key->size, NULL);
1373
0
    if (ret != ASN1_SUCCESS) {
1374
0
      gnutls_assert();
1375
0
      ret = _gnutls_asn2err(ret);
1376
0
      asn1_delete_structure2(&pkey_asn,
1377
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1378
0
      goto error;
1379
0
    }
1380
1381
0
    ret = _gnutls_x509_read_key_int(pkey_asn, "",
1382
0
            &pkey->params.params[GOST_K]);
1383
0
    if (ret < 0) {
1384
0
      gnutls_assert();
1385
0
      asn1_delete_structure2(&pkey_asn,
1386
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1387
0
      goto error;
1388
0
    }
1389
0
    asn1_delete_structure2(&pkey_asn, ASN1_DELETE_FLAG_ZEROIZE);
1390
0
  } else if (raw_key->data[0] == ASN1_TAG_OCTET_STRING) {
1391
0
    asn1_node pkey_asn;
1392
1393
    /* format: OCTET STRING packed in OCTET STRING */
1394
0
    if ((ret = asn1_create_element(_gnutls_get_gnutls_asn(),
1395
0
                 "GNUTLS.GOSTPrivateKey",
1396
0
                 &pkey_asn)) != ASN1_SUCCESS) {
1397
0
      gnutls_assert();
1398
0
      ret = _gnutls_asn2err(ret);
1399
0
      goto error;
1400
0
    }
1401
1402
0
    ret = _asn1_strict_der_decode(&pkey_asn, raw_key->data,
1403
0
                raw_key->size, NULL);
1404
0
    if (ret != ASN1_SUCCESS) {
1405
0
      gnutls_assert();
1406
0
      ret = _gnutls_asn2err(ret);
1407
0
      asn1_delete_structure2(&pkey_asn,
1408
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1409
0
      goto error;
1410
0
    }
1411
1412
0
    ret = _gnutls_x509_read_key_int_le(
1413
0
      pkey_asn, "", &pkey->params.params[GOST_K]);
1414
0
    if (ret < 0) {
1415
0
      gnutls_assert();
1416
0
      asn1_delete_structure2(&pkey_asn,
1417
0
                 ASN1_DELETE_FLAG_ZEROIZE);
1418
0
      goto error;
1419
0
    }
1420
0
    asn1_delete_structure2(&pkey_asn, ASN1_DELETE_FLAG_ZEROIZE);
1421
0
  } else {
1422
0
    gnutls_assert();
1423
0
    ret = GNUTLS_E_PARSING_ERROR;
1424
0
    goto error;
1425
0
  }
1426
1427
0
  pkey->params.params_nr++;
1428
1429
0
  return 0;
1430
1431
0
error:
1432
0
  return ret;
1433
0
}
1434
1435
/* Decodes a GOST privateKey from a PKCS8 structure.
1436
 */
1437
static int _decode_pkcs8_gost_key(asn1_node pkcs8_asn,
1438
          gnutls_x509_privkey_t pkey,
1439
          gnutls_pk_algorithm_t algo)
1440
0
{
1441
0
  int ret;
1442
0
  gnutls_datum_t tmp;
1443
0
  unsigned char
1444
0
    oid[3 *
1445
0
        MAX_OID_SIZE]; /* GOST parameters can have 3 OIDs at most */
1446
0
  int len, result;
1447
1448
0
  gnutls_pk_params_init(&pkey->params);
1449
1450
0
  len = sizeof(oid);
1451
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.parameters",
1452
0
         oid, &len);
1453
0
  if (result != ASN1_SUCCESS) {
1454
0
    gnutls_assert();
1455
0
    ret = GNUTLS_E_PARSING_ERROR;
1456
0
    goto error;
1457
0
  } else {
1458
0
    ret = _gnutls_x509_read_gost_params(oid, len, &pkey->params,
1459
0
                algo);
1460
0
    if (ret < 0) {
1461
0
      gnutls_assert();
1462
0
      goto error;
1463
0
    }
1464
0
  }
1465
1466
  /* Will be fixed later by pk_fixup */
1467
0
  ret = _gnutls_mpi_init(&pkey->params.params[GOST_X]);
1468
0
  if (ret < 0) {
1469
0
    gnutls_assert();
1470
0
    goto error;
1471
0
  }
1472
0
  pkey->params.params_nr++;
1473
1474
0
  ret = _gnutls_mpi_init(&pkey->params.params[GOST_Y]);
1475
0
  if (ret < 0) {
1476
0
    gnutls_assert();
1477
0
    goto error;
1478
0
  }
1479
0
  pkey->params.params_nr++;
1480
1481
0
  _gnutls_mpi_set_ui(pkey->params.params[GOST_X], 0);
1482
0
  _gnutls_mpi_set_ui(pkey->params.params[GOST_Y], 0);
1483
1484
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1485
0
  if (ret < 0) {
1486
0
    gnutls_assert();
1487
0
    goto error;
1488
0
  }
1489
1490
0
  ret = _privkey_decode_gost_key(&tmp, pkey);
1491
0
  _gnutls_free_key_datum(&tmp);
1492
1493
0
  if (ret < 0) {
1494
0
    gnutls_assert();
1495
0
    goto error;
1496
0
  }
1497
1498
0
  pkey->params.algo = algo;
1499
1500
0
  return 0;
1501
1502
0
error:
1503
0
  gnutls_pk_params_clear(&pkey->params);
1504
0
  gnutls_pk_params_release(&pkey->params);
1505
1506
0
  return ret;
1507
0
}
1508
1509
/* Decodes an DSA privateKey and params from a PKCS8 structure.
1510
 */
1511
static int _decode_pkcs8_dsa_key(asn1_node pkcs8_asn,
1512
         gnutls_x509_privkey_t pkey)
1513
0
{
1514
0
  int ret;
1515
0
  gnutls_datum_t tmp = { NULL, 0 };
1516
1517
0
  gnutls_pk_params_init(&pkey->params);
1518
1519
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &tmp);
1520
0
  if (ret < 0) {
1521
0
    gnutls_assert();
1522
0
    goto error;
1523
0
  }
1524
1525
0
  ret = _gnutls_x509_read_der_int(tmp.data, tmp.size,
1526
0
          &pkey->params.params[4]);
1527
0
  _gnutls_free_key_datum(&tmp);
1528
1529
0
  if (ret < 0) {
1530
0
    gnutls_assert();
1531
0
    goto error;
1532
0
  }
1533
1534
0
  ret = _gnutls_x509_read_value(pkcs8_asn,
1535
0
              "privateKeyAlgorithm.parameters", &tmp);
1536
0
  if (ret < 0) {
1537
0
    gnutls_assert();
1538
0
    goto error;
1539
0
  }
1540
1541
0
  ret = _gnutls_x509_read_pubkey_params(GNUTLS_PK_DSA, tmp.data, tmp.size,
1542
0
                &pkey->params);
1543
0
  _gnutls_free_datum(&tmp);
1544
0
  if (ret < 0) {
1545
0
    gnutls_assert();
1546
0
    goto error;
1547
0
  }
1548
1549
0
  if (_gnutls_mpi_cmp_ui(pkey->params.params[0], 0) == 0) {
1550
0
    gnutls_assert();
1551
0
    ret = GNUTLS_E_ILLEGAL_PARAMETER;
1552
0
    goto error;
1553
0
  }
1554
1555
  /* the public key can be generated as g^x mod p */
1556
0
  ret = _gnutls_mpi_init(&pkey->params.params[3]);
1557
0
  if (ret < 0) {
1558
0
    gnutls_assert();
1559
0
    goto error;
1560
0
  }
1561
1562
0
  ret = _gnutls_mpi_powm(pkey->params.params[3], pkey->params.params[2],
1563
0
             pkey->params.params[4], pkey->params.params[0]);
1564
0
  if (ret < 0) {
1565
0
    gnutls_assert();
1566
0
    goto error;
1567
0
  }
1568
1569
0
  pkey->params.algo = GNUTLS_PK_DSA;
1570
0
  pkey->params.params_nr = DSA_PRIVATE_PARAMS;
1571
1572
0
  ret = _gnutls_asn1_encode_privkey(&pkey->key, &pkey->params);
1573
0
  if (ret < 0) {
1574
0
    gnutls_assert();
1575
0
    goto error;
1576
0
  }
1577
1578
0
  return 0;
1579
1580
0
error:
1581
0
  if (pkey->params.params_nr != DSA_PRIVATE_PARAMS)
1582
0
    _gnutls_mpi_release(&pkey->params.params[4]);
1583
0
  return ret;
1584
0
}
1585
1586
static int decode_ml_dsa_inner_private_key(const gnutls_datum_t *raw_key,
1587
             size_t raw_pub_size,
1588
             size_t raw_priv_size,
1589
             gnutls_x509_privkey_t pkey)
1590
0
{
1591
0
  int ret;
1592
0
  asn1_node inner_asn = NULL;
1593
1594
  /* libtasn1 doesn't support encoding instructions in CHOICE,
1595
   * parse it manually */
1596
0
  if (raw_key->size == 34 && raw_key->data[0] == 0x80 &&
1597
0
      raw_key->data[1] == 0x20) {
1598
0
    _gnutls_free_key_datum(&pkey->params.raw_seed);
1599
0
    ret = _gnutls_set_datum(&pkey->params.raw_seed,
1600
0
          &raw_key->data[2], 32);
1601
0
    if (ret < 0)
1602
0
      return gnutls_assert_val(ret);
1603
0
  } else {
1604
0
    int result;
1605
0
    char choice_name[16];
1606
0
    int choice_name_size = sizeof(choice_name) - 1;
1607
0
    unsigned int etype;
1608
1609
0
    result = asn1_create_element(_gnutls_get_gnutls_asn(),
1610
0
               "GNUTLS.MLDSAInnerPrivateKey",
1611
0
               &inner_asn);
1612
0
    if (result != ASN1_SUCCESS)
1613
0
      return gnutls_assert_val(_gnutls_asn2err(result));
1614
1615
0
    result = _asn1_strict_der_decode(&inner_asn, raw_key->data,
1616
0
             raw_key->size, NULL);
1617
0
    if (result != ASN1_SUCCESS) {
1618
0
      ret = gnutls_assert_val(_gnutls_asn2err(result));
1619
0
      goto cleanup;
1620
0
    }
1621
1622
0
    result = asn1_read_value_type(inner_asn, "", choice_name,
1623
0
                &choice_name_size, &etype);
1624
0
    if (result != ASN1_SUCCESS) {
1625
0
      ret = gnutls_assert_val(_gnutls_asn2err(result));
1626
0
      goto cleanup;
1627
0
    }
1628
1629
0
    if (etype != ASN1_ETYPE_CHOICE) {
1630
0
      ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1631
0
      goto cleanup;
1632
0
    }
1633
1634
0
    choice_name[choice_name_size] = '\0';
1635
0
    if (strcmp(choice_name, "expandedKey") == 0) {
1636
0
      _gnutls_free_key_datum(&pkey->params.raw_priv);
1637
0
      ret = _gnutls_x509_read_value(inner_asn, choice_name,
1638
0
                  &pkey->params.raw_priv);
1639
0
      if (ret < 0) {
1640
0
        gnutls_assert();
1641
0
        goto cleanup;
1642
0
      }
1643
1644
      /* The legacy format used in
1645
       * liboqs/oqsprovider, which embeds public key
1646
       * in the "privateKey" field after a private
1647
       * key, falls to this branch */
1648
0
      if (pkey->params.raw_priv.size ==
1649
0
          raw_pub_size + raw_priv_size) {
1650
0
        ret = _gnutls_set_datum(
1651
0
          &pkey->params.raw_pub,
1652
0
          &pkey->params.raw_priv
1653
0
             .data[raw_priv_size],
1654
0
          raw_pub_size);
1655
0
        if (ret < 0) {
1656
0
          gnutls_assert();
1657
0
          goto cleanup;
1658
0
        }
1659
0
        pkey->params.raw_priv.size = raw_priv_size;
1660
0
      }
1661
0
    } else if (strcmp(choice_name, "both") == 0) {
1662
0
      _gnutls_free_key_datum(&pkey->params.raw_seed);
1663
0
      ret = _gnutls_x509_read_value(inner_asn, "both.seed",
1664
0
                  &pkey->params.raw_seed);
1665
0
      if (ret < 0) {
1666
0
        gnutls_assert();
1667
0
        goto cleanup;
1668
0
      }
1669
0
      if (pkey->params.raw_seed.size != 32) {
1670
0
        ret = gnutls_assert_val(
1671
0
          GNUTLS_E_INVALID_REQUEST);
1672
0
        goto cleanup;
1673
0
      }
1674
0
      _gnutls_free_key_datum(&pkey->params.raw_priv);
1675
0
      ret = _gnutls_x509_read_value(inner_asn,
1676
0
                  "both.expandedKey",
1677
0
                  &pkey->params.raw_priv);
1678
0
      if (ret < 0) {
1679
0
        gnutls_assert();
1680
0
        goto cleanup;
1681
0
      }
1682
0
    } else {
1683
0
      ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1684
0
      goto cleanup;
1685
0
    }
1686
0
  }
1687
1688
  /* Expand seed if set */
1689
0
  if (pkey->params.raw_seed.data) {
1690
    /* For checking any inconsistency */
1691
0
    gnutls_datum_t raw_priv =
1692
0
      _gnutls_steal_datum(&pkey->params.raw_priv);
1693
1694
0
    pkey->params.pkflags |= GNUTLS_PK_FLAG_EXPAND_KEYS_FROM_SEED;
1695
0
    ret = _gnutls_pk_generate_keys(pkey->params.algo, 0,
1696
0
                 &pkey->params, 0);
1697
0
    if (ret < 0) {
1698
0
      gnutls_assert();
1699
0
      _gnutls_free_key_datum(&raw_priv);
1700
0
      goto cleanup;
1701
0
    }
1702
1703
0
    if (raw_priv.data &&
1704
0
        (pkey->params.raw_priv.size != raw_priv.size ||
1705
0
         gnutls_memcmp(pkey->params.raw_priv.data, raw_priv.data,
1706
0
           pkey->params.raw_priv.size) != 0)) {
1707
0
      ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1708
0
      _gnutls_free_key_datum(&raw_priv);
1709
0
      goto cleanup;
1710
0
    }
1711
0
    _gnutls_free_key_datum(&raw_priv);
1712
0
  }
1713
1714
0
cleanup:
1715
0
  asn1_delete_structure2(&inner_asn, ASN1_DELETE_FLAG_ZEROIZE);
1716
0
  return ret;
1717
0
}
1718
1719
static int _decode_pkcs8_ml_dsa_key(asn1_node pkcs8_asn,
1720
            gnutls_x509_privkey_t pkey,
1721
            gnutls_pk_algorithm_t algo)
1722
0
{
1723
0
  int ret;
1724
0
  unsigned int version;
1725
0
  gnutls_datum_t raw_priv = { NULL, 0 };
1726
0
  size_t raw_pub_size, raw_priv_size;
1727
1728
0
  switch (algo) {
1729
0
  case GNUTLS_PK_MLDSA44:
1730
0
    raw_priv_size = MLDSA44_PRIVKEY_SIZE;
1731
0
    raw_pub_size = MLDSA44_PUBKEY_SIZE;
1732
0
    break;
1733
0
  case GNUTLS_PK_MLDSA65:
1734
0
    raw_priv_size = MLDSA65_PRIVKEY_SIZE;
1735
0
    raw_pub_size = MLDSA65_PUBKEY_SIZE;
1736
0
    break;
1737
0
  case GNUTLS_PK_MLDSA87:
1738
0
    raw_priv_size = MLDSA87_PRIVKEY_SIZE;
1739
0
    raw_pub_size = MLDSA87_PUBKEY_SIZE;
1740
0
    break;
1741
0
  default:
1742
0
    return gnutls_assert_val(
1743
0
      GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM);
1744
0
  }
1745
1746
0
  gnutls_pk_params_init(&pkey->params);
1747
0
  pkey->params.algo = algo;
1748
1749
0
  ret = _gnutls_x509_read_uint(pkcs8_asn, "version", &version);
1750
0
  if (ret < 0) {
1751
0
    gnutls_assert();
1752
0
    goto cleanup;
1753
0
  }
1754
0
  if (version != 0 && version != 1)
1755
0
    return gnutls_assert_val(GNUTLS_E_ASN1_DER_ERROR);
1756
1757
0
  ret = _gnutls_x509_read_value(pkcs8_asn, "privateKey", &raw_priv);
1758
0
  if (ret < 0) {
1759
0
    gnutls_assert();
1760
0
    goto cleanup;
1761
0
  }
1762
1763
  /* Try the CHOICE format defined in
1764
   * draft-ietf-lamps-dilithium-certificates-12, section 6 */
1765
0
  ret = decode_ml_dsa_inner_private_key(&raw_priv, raw_pub_size,
1766
0
                raw_priv_size, pkey);
1767
0
  if (ret < 0) {
1768
0
    gnutls_assert();
1769
0
    goto cleanup;
1770
0
  }
1771
1772
  /* If version is 1, a public key may be embedded in a separate
1773
   * field */
1774
0
  if (version == 1) {
1775
    /* For checking any inconsistency */
1776
0
    gnutls_datum_t raw_pub =
1777
0
      _gnutls_steal_datum(&pkey->params.raw_pub);
1778
1779
0
    ret = _gnutls_x509_read_value(pkcs8_asn, "publicKey",
1780
0
                &pkey->params.raw_pub);
1781
0
    if (ret < 0) {
1782
0
      gnutls_assert();
1783
0
      _gnutls_free_key_datum(&raw_pub);
1784
0
      goto cleanup;
1785
0
    }
1786
1787
0
    if (raw_pub.data &&
1788
0
        (pkey->params.raw_pub.size != raw_pub.size ||
1789
0
         gnutls_memcmp(pkey->params.raw_pub.data, raw_pub.data,
1790
0
           pkey->params.raw_pub.size) != 0)) {
1791
0
      ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1792
0
      _gnutls_free_key_datum(&raw_pub);
1793
0
      goto cleanup;
1794
0
    }
1795
0
    _gnutls_free_key_datum(&raw_pub);
1796
0
  }
1797
1798
  /* Sanity check that the resulting keys have the expected sizes */
1799
0
  if ((pkey->params.raw_pub.data &&
1800
0
       pkey->params.raw_pub.size != raw_pub_size) ||
1801
0
      pkey->params.raw_priv.size != raw_priv_size) {
1802
0
    ret = gnutls_assert_val(GNUTLS_E_ASN1_DER_ERROR);
1803
0
    goto cleanup;
1804
0
  }
1805
1806
0
cleanup:
1807
0
  if (ret < 0) {
1808
0
    gnutls_pk_params_clear(&pkey->params);
1809
0
    gnutls_pk_params_release(&pkey->params);
1810
0
  }
1811
0
  _gnutls_free_key_datum(&raw_priv);
1812
1813
0
  return ret;
1814
0
}
1815
1816
static int decode_private_key_info(const gnutls_datum_t *der,
1817
           gnutls_x509_privkey_t pkey)
1818
0
{
1819
0
  int result, len;
1820
0
  char oid[MAX_OID_SIZE];
1821
0
  asn1_node pkcs8_asn = NULL;
1822
0
  gnutls_datum_t sder;
1823
0
  int ret;
1824
1825
0
  if ((result = asn1_create_element(_gnutls_get_pkix(),
1826
0
            "PKIX1.pkcs-8-PrivateKeyInfo",
1827
0
            &pkcs8_asn)) != ASN1_SUCCESS) {
1828
0
    gnutls_assert();
1829
0
    result = _gnutls_asn2err(result);
1830
0
    goto error;
1831
0
  }
1832
1833
0
  result =
1834
0
    _asn1_strict_der_decode(&pkcs8_asn, der->data, der->size, NULL);
1835
0
  if (result != ASN1_SUCCESS) {
1836
0
    gnutls_assert();
1837
0
    result = _gnutls_asn2err(result);
1838
0
    goto error;
1839
0
  }
1840
1841
  /* Check the private key algorithm OID
1842
   */
1843
0
  len = sizeof(oid);
1844
0
  result = asn1_read_value(pkcs8_asn, "privateKeyAlgorithm.algorithm",
1845
0
         oid, &len);
1846
0
  if (result != ASN1_SUCCESS) {
1847
0
    gnutls_assert();
1848
0
    result = _gnutls_asn2err(result);
1849
0
    goto error;
1850
0
  }
1851
1852
0
  pkey->params.algo = gnutls_oid_to_pk(oid);
1853
0
  if (pkey->params.algo == GNUTLS_PK_UNKNOWN) {
1854
0
    gnutls_assert();
1855
0
    _gnutls_debug_log(
1856
0
      "PKCS #8 private key OID '%s' is unsupported.\n", oid);
1857
0
    result = GNUTLS_E_UNKNOWN_PK_ALGORITHM;
1858
0
    goto error;
1859
0
  }
1860
1861
  /* Get the DER encoding of the actual private key.
1862
   */
1863
1864
0
  switch (pkey->params.algo) {
1865
0
  case GNUTLS_PK_RSA:
1866
0
    result = _decode_pkcs8_rsa_key(pkcs8_asn, pkey);
1867
0
    break;
1868
0
  case GNUTLS_PK_RSA_PSS:
1869
0
    result = _decode_pkcs8_rsa_pss_key(pkcs8_asn, pkey);
1870
0
    break;
1871
0
  case GNUTLS_PK_RSA_OAEP:
1872
0
    result = _decode_pkcs8_rsa_oaep_key(pkcs8_asn, pkey);
1873
0
    break;
1874
0
  case GNUTLS_PK_DSA:
1875
0
    result = _decode_pkcs8_dsa_key(pkcs8_asn, pkey);
1876
0
    break;
1877
0
  case GNUTLS_PK_ECDSA:
1878
0
    result = _decode_pkcs8_ecc_key(pkcs8_asn, pkey);
1879
0
    break;
1880
0
  case GNUTLS_PK_EDDSA_ED25519:
1881
0
  case GNUTLS_PK_EDDSA_ED448:
1882
0
    result = _decode_pkcs8_eddsa_key(pkcs8_asn, pkey, oid);
1883
0
    break;
1884
0
  case GNUTLS_PK_ECDH_X25519:
1885
0
  case GNUTLS_PK_ECDH_X448:
1886
0
    result = _decode_pkcs8_modern_ecdh_key(pkcs8_asn, pkey, oid);
1887
0
    break;
1888
0
  case GNUTLS_PK_GOST_01:
1889
0
  case GNUTLS_PK_GOST_12_256:
1890
0
  case GNUTLS_PK_GOST_12_512:
1891
0
    result = _decode_pkcs8_gost_key(pkcs8_asn, pkey,
1892
0
            pkey->params.algo);
1893
0
    break;
1894
0
  case GNUTLS_PK_MLDSA44:
1895
0
  case GNUTLS_PK_MLDSA65:
1896
0
  case GNUTLS_PK_MLDSA87:
1897
0
    result = _decode_pkcs8_ml_dsa_key(pkcs8_asn, pkey,
1898
0
              pkey->params.algo);
1899
0
    break;
1900
0
  default:
1901
0
    result = gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);
1902
0
    goto error;
1903
0
  }
1904
1905
0
  if (result < 0) {
1906
0
    gnutls_assert();
1907
0
    goto error;
1908
0
  }
1909
1910
  /* check for provable parameters attribute */
1911
0
  ret = _x509_parse_attribute(pkcs8_asn, "attributes", OID_ATTR_PROV_SEED,
1912
0
            0, 1, &sder);
1913
0
  if (ret >= 0) { /* ignore it when not being present */
1914
0
    ret = _x509_decode_provable_seed(pkey, &sder);
1915
0
    gnutls_free(sder.data);
1916
0
    if (ret < 0) {
1917
0
      gnutls_assert();
1918
0
    }
1919
0
  }
1920
1921
0
  result = 0;
1922
1923
0
error:
1924
0
  asn1_delete_structure2(&pkcs8_asn, ASN1_DELETE_FLAG_ZEROIZE);
1925
0
  return result;
1926
0
}
1927
1928
/**
1929
 * gnutls_x509_privkey_import_pkcs8:
1930
 * @key: The data to store the parsed key
1931
 * @data: The DER or PEM encoded key.
1932
 * @format: One of DER or PEM
1933
 * @password: the password to decrypt the key (if it is encrypted).
1934
 * @flags: 0 if encrypted or GNUTLS_PKCS_PLAIN if not encrypted.
1935
 *
1936
 * This function will convert the given DER or PEM encoded PKCS8 2.0
1937
 * encrypted key to the native gnutls_x509_privkey_t format. The
1938
 * output will be stored in @key.  Both RSA and DSA keys can be
1939
 * imported, and flags can only be used to indicate an unencrypted
1940
 * key.
1941
 *
1942
 * The @password can be either ASCII or UTF-8 in the default PBES2
1943
 * encryption schemas, or ASCII for the PKCS12 schemas.
1944
 *
1945
 * If the Certificate is PEM encoded it should have a header of
1946
 * "ENCRYPTED PRIVATE KEY", or "PRIVATE KEY". You only need to
1947
 * specify the flags if the key is DER encoded, since in that case
1948
 * the encryption status cannot be auto-detected.
1949
 *
1950
 * If the %GNUTLS_PKCS_PLAIN flag is specified and the supplied data
1951
 * are encrypted then %GNUTLS_E_DECRYPTION_FAILED is returned.
1952
 *
1953
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
1954
 *   negative error value.
1955
 **/
1956
int gnutls_x509_privkey_import_pkcs8(gnutls_x509_privkey_t key,
1957
             const gnutls_datum_t *data,
1958
             gnutls_x509_crt_fmt_t format,
1959
             const char *password, unsigned int flags)
1960
0
{
1961
0
  int result = 0, need_free = 0;
1962
0
  gnutls_datum_t _data;
1963
1964
0
  if (key == NULL) {
1965
0
    gnutls_assert();
1966
0
    return GNUTLS_E_INVALID_REQUEST;
1967
0
  }
1968
1969
0
  _data.data = data->data;
1970
0
  _data.size = data->size;
1971
1972
0
  key->params.algo = GNUTLS_PK_UNKNOWN;
1973
1974
  /* If the Certificate is in PEM format then decode it
1975
   */
1976
0
  if (format == GNUTLS_X509_FMT_PEM) {
1977
    /* Try the first header 
1978
     */
1979
0
    result = _gnutls_fbase64_decode(PEM_UNENCRYPTED_PKCS8,
1980
0
            data->data, data->size, &_data);
1981
1982
0
    if (result < 0) { /* Try the encrypted header 
1983
           */
1984
0
      result = _gnutls_fbase64_decode(PEM_PKCS8, data->data,
1985
0
              data->size, &_data);
1986
1987
0
      if (result < 0) {
1988
0
        gnutls_assert();
1989
0
        return result;
1990
0
      }
1991
0
    } else if (flags == 0)
1992
0
      flags |= GNUTLS_PKCS_PLAIN;
1993
1994
0
    need_free = 1;
1995
0
  }
1996
1997
0
  if (key->expanded) {
1998
0
    _gnutls_x509_privkey_reinit(key);
1999
0
  }
2000
0
  key->expanded = 1;
2001
2002
  /* Here we don't check for password == NULL to maintain a backwards
2003
   * compatibility behavior, with old versions that were encrypting using
2004
   * a NULL password.
2005
   */
2006
0
  if (flags & GNUTLS_PKCS_PLAIN) {
2007
0
    result = decode_private_key_info(&_data, key);
2008
0
    if (result < 0) { /* check if it is encrypted */
2009
0
      if (pkcs8_key_decode(&_data, "", key, 0) == 0)
2010
0
        result = GNUTLS_E_DECRYPTION_FAILED;
2011
0
    }
2012
0
  } else { /* encrypted. */
2013
0
    result = pkcs8_key_decode(&_data, password, key, 1);
2014
0
  }
2015
2016
0
  if (result < 0) {
2017
0
    gnutls_assert();
2018
0
    goto cleanup;
2019
0
  }
2020
2021
  /* This part is necessary to get the public key on certain algorithms.
2022
   * In the import above we only get the private key. */
2023
0
  result =
2024
0
    _gnutls_pk_fixup(key->params.algo, GNUTLS_IMPORT, &key->params);
2025
0
  if (result < 0) {
2026
0
    gnutls_assert();
2027
0
    goto cleanup;
2028
0
  }
2029
2030
0
  if (need_free)
2031
0
    _gnutls_free_datum(&_data);
2032
2033
  /* The key has now been decoded.
2034
   */
2035
0
  return 0;
2036
2037
0
cleanup:
2038
0
  asn1_delete_structure2(&key->key, ASN1_DELETE_FLAG_ZEROIZE);
2039
0
  key->params.algo = GNUTLS_PK_UNKNOWN;
2040
0
  if (need_free) {
2041
0
    zeroize_key(_data.data, _data.size);
2042
0
    _gnutls_free_datum(&_data);
2043
0
  }
2044
0
  return result;
2045
0
}