Coverage Report

Created: 2026-10-17 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hpn-ssh/sshkey.c
Line
Count
Source
1
/* $OpenBSD: sshkey.c,v 1.165 2026/10/01 07:07:49 djm Exp $ */
2
/*
3
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4
 * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
5
 * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions
9
 * are met:
10
 * 1. Redistributions of source code must retain the above copyright
11
 *    notice, this list of conditions and the following disclaimer.
12
 * 2. Redistributions in binary form must reproduce the above copyright
13
 *    notice, this list of conditions and the following disclaimer in the
14
 *    documentation and/or other materials provided with the distribution.
15
 *
16
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
 */
27
28
#include "includes.h"
29
30
#include <sys/types.h>
31
#include <sys/mman.h>
32
#include <netinet/in.h>
33
34
#ifdef WITH_OPENSSL
35
#include <openssl/bn.h>
36
#include <openssl/evp.h>
37
#include <openssl/err.h>
38
#include <openssl/pem.h>
39
#endif
40
41
#include "crypto_api.h"
42
43
#include <errno.h>
44
#include <limits.h>
45
#include <stdio.h>
46
#include <stdlib.h>
47
#include <string.h>
48
#include <resolv.h>
49
#include <time.h>
50
#include <util.h>
51
52
#include "ssh2.h"
53
#include "ssherr.h"
54
#include "misc.h"
55
#include "sshbuf.h"
56
#include "cipher.h"
57
#include "digest.h"
58
#define SSHKEY_INTERNAL
59
#include "sshkey.h"
60
#include "match.h"
61
#include "ssh-sk.h"
62
#include "ssh-pkcs11.h"
63
64
#include "openbsd-compat/openssl-compat.h"
65
66
/* openssh private key file format */
67
0
#define MARK_BEGIN    "-----BEGIN OPENSSH PRIVATE KEY-----\n"
68
0
#define MARK_END    "-----END OPENSSH PRIVATE KEY-----\n"
69
0
#define MARK_BEGIN_LEN    (sizeof(MARK_BEGIN) - 1)
70
0
#define MARK_END_LEN    (sizeof(MARK_END) - 1)
71
0
#define KDFNAME     "bcrypt"
72
0
#define AUTH_MAGIC    "openssh-key-v1"
73
0
#define SALT_LEN    16
74
0
#define DEFAULT_CIPHERNAME  "aes256-ctr"
75
0
#define DEFAULT_ROUNDS    32
76
0
#define MAX_KDF_ROUNDS    (1<<20)
77
78
/*
79
 * Constants relating to "shielding" support; protection of keys expected
80
 * to remain in memory for long durations
81
 */
82
0
#define SSHKEY_SHIELD_PREKEY_LEN  (16 * 1024)
83
0
#define SSHKEY_SHIELD_CIPHER    "aes256-ctr" /* XXX want AES-EME* */
84
0
#define SSHKEY_SHIELD_PREKEY_HASH SSH_DIGEST_SHA512
85
86
static int sshkey_from_blob_internal(struct sshbuf *buf,
87
    struct sshkey **keyp, int allow_cert,
88
    const char *alg_allowlist, const char *ca_sigalg_allowlist);
89
90
/* Supported key types */
91
extern const struct sshkey_impl sshkey_ed25519_impl;
92
extern const struct sshkey_impl sshkey_ed25519_cert_impl;
93
extern const struct sshkey_impl sshkey_ed25519_sk_impl;
94
extern const struct sshkey_impl sshkey_ed25519_sk_cert_impl;
95
# ifdef USE_MLDSA
96
extern const struct sshkey_impl sshkey_mldsa44_ed25519_impl;
97
extern const struct sshkey_impl sshkey_mldsa44_ed25519_cert_impl;
98
# endif /* USE_MLDSA */
99
#ifdef WITH_OPENSSL
100
# ifdef ENABLE_SK
101
extern const struct sshkey_impl sshkey_ecdsa_sk_impl;
102
extern const struct sshkey_impl sshkey_ecdsa_sk_cert_impl;
103
extern const struct sshkey_impl sshkey_ecdsa_sk_webauthn_impl;
104
extern const struct sshkey_impl sshkey_ecdsa_sk_webauthn_cert_impl;
105
# endif /* ENABLE_SK */
106
extern const struct sshkey_impl sshkey_ecdsa_nistp256_impl;
107
extern const struct sshkey_impl sshkey_ecdsa_nistp256_cert_impl;
108
extern const struct sshkey_impl sshkey_ecdsa_nistp384_impl;
109
extern const struct sshkey_impl sshkey_ecdsa_nistp384_cert_impl;
110
extern const struct sshkey_impl sshkey_ecdsa_nistp521_impl;
111
extern const struct sshkey_impl sshkey_ecdsa_nistp521_cert_impl;
112
extern const struct sshkey_impl sshkey_rsa_impl;
113
extern const struct sshkey_impl sshkey_rsa_cert_impl;
114
extern const struct sshkey_impl sshkey_rsa_sha256_impl;
115
extern const struct sshkey_impl sshkey_rsa_sha256_cert_impl;
116
extern const struct sshkey_impl sshkey_rsa_sha512_impl;
117
extern const struct sshkey_impl sshkey_rsa_sha512_cert_impl;
118
#endif /* WITH_OPENSSL */
119
120
const struct sshkey_impl * const keyimpls[] = {
121
  &sshkey_ed25519_impl,
122
  &sshkey_ed25519_cert_impl,
123
#ifdef ENABLE_SK
124
  &sshkey_ed25519_sk_impl,
125
  &sshkey_ed25519_sk_cert_impl,
126
#endif
127
#ifdef USE_MLDSA
128
  &sshkey_mldsa44_ed25519_impl,
129
  &sshkey_mldsa44_ed25519_cert_impl,
130
#endif /* USE_MLDSA */
131
#ifdef WITH_OPENSSL
132
  &sshkey_ecdsa_nistp256_impl,
133
  &sshkey_ecdsa_nistp256_cert_impl,
134
  &sshkey_ecdsa_nistp384_impl,
135
  &sshkey_ecdsa_nistp384_cert_impl,
136
  &sshkey_ecdsa_nistp521_impl,
137
  &sshkey_ecdsa_nistp521_cert_impl,
138
# ifdef ENABLE_SK
139
  &sshkey_ecdsa_sk_impl,
140
  &sshkey_ecdsa_sk_cert_impl,
141
  &sshkey_ecdsa_sk_webauthn_impl,
142
  &sshkey_ecdsa_sk_webauthn_cert_impl,
143
# endif /* ENABLE_SK */
144
  &sshkey_rsa_impl,
145
  &sshkey_rsa_cert_impl,
146
  &sshkey_rsa_sha256_impl,
147
  &sshkey_rsa_sha256_cert_impl,
148
  &sshkey_rsa_sha512_impl,
149
  &sshkey_rsa_sha512_cert_impl,
150
#endif /* WITH_OPENSSL */
151
  NULL
152
};
153
154
static const struct sshkey_impl *
155
sshkey_impl_from_type(int type)
156
0
{
157
0
  int i;
158
159
0
  for (i = 0; keyimpls[i] != NULL; i++) {
160
0
    if (keyimpls[i]->type == type)
161
0
      return keyimpls[i];
162
0
  }
163
0
  return NULL;
164
0
}
165
166
static const struct sshkey_impl *
167
sshkey_impl_from_type_nid(int type, int nid)
168
0
{
169
0
  int i;
170
171
0
  for (i = 0; keyimpls[i] != NULL; i++) {
172
0
    if (keyimpls[i]->type == type &&
173
0
        (keyimpls[i]->nid == 0 || keyimpls[i]->nid == nid))
174
0
      return keyimpls[i];
175
0
  }
176
0
  return NULL;
177
0
}
178
179
static const struct sshkey_impl *
180
sshkey_impl_from_key(const struct sshkey *k)
181
0
{
182
0
  if (k == NULL)
183
0
    return NULL;
184
0
  return sshkey_impl_from_type_nid(k->type, k->ecdsa_nid);
185
0
}
186
187
const char *
188
sshkey_type(const struct sshkey *k)
189
0
{
190
0
  const struct sshkey_impl *impl;
191
192
0
  if ((impl = sshkey_impl_from_key(k)) == NULL)
193
0
    return "unknown";
194
0
  return impl->shortname;
195
0
}
196
197
static const char *
198
sshkey_ssh_name_from_type_nid(int type, int nid)
199
0
{
200
0
  const struct sshkey_impl *impl;
201
202
0
  if ((impl = sshkey_impl_from_type_nid(type, nid)) == NULL)
203
0
    return "ssh-unknown";
204
0
  return impl->name;
205
0
}
206
207
int
208
sshkey_type_is_cert(int type)
209
0
{
210
0
  const struct sshkey_impl *impl;
211
212
0
  if ((impl = sshkey_impl_from_type(type)) == NULL)
213
0
    return 0;
214
0
  return impl->cert;
215
0
}
216
217
const char *
218
sshkey_ssh_name(const struct sshkey *k)
219
0
{
220
0
  return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
221
0
}
222
223
const char *
224
sshkey_ssh_name_plain(const struct sshkey *k)
225
0
{
226
0
  return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
227
0
      k->ecdsa_nid);
228
0
}
229
230
static int
231
type_from_name(const char *name, int allow_short)
232
0
{
233
0
  int i;
234
0
  const struct sshkey_impl *impl;
235
236
0
  for (i = 0; keyimpls[i] != NULL; i++) {
237
0
    impl = keyimpls[i];
238
0
    if (impl->name != NULL && strcmp(name, impl->name) == 0)
239
0
      return impl->type;
240
    /* Only allow shortname matches for plain key types */
241
0
    if (allow_short && !impl->cert && impl->shortname != NULL &&
242
0
        strcasecmp(impl->shortname, name) == 0)
243
0
      return impl->type;
244
0
  }
245
0
  return KEY_UNSPEC;
246
0
}
247
248
int
249
sshkey_type_from_name(const char *name)
250
0
{
251
0
  return type_from_name(name, 0);
252
0
}
253
254
int
255
sshkey_type_from_shortname(const char *name)
256
0
{
257
0
  return type_from_name(name, 1);
258
0
}
259
260
static int
261
key_type_is_ecdsa_variant(int type)
262
0
{
263
0
  switch (type) {
264
0
  case KEY_ECDSA:
265
0
  case KEY_ECDSA_CERT:
266
0
  case KEY_ECDSA_SK:
267
0
  case KEY_ECDSA_SK_CERT:
268
0
    return 1;
269
0
  }
270
0
  return 0;
271
0
}
272
273
int
274
sshkey_ecdsa_nid_from_name(const char *name)
275
0
{
276
0
  int i;
277
278
0
  for (i = 0; keyimpls[i] != NULL; i++) {
279
0
    if (!key_type_is_ecdsa_variant(keyimpls[i]->type))
280
0
      continue;
281
0
    if (keyimpls[i]->name != NULL &&
282
0
        strcmp(name, keyimpls[i]->name) == 0)
283
0
      return keyimpls[i]->nid;
284
0
  }
285
0
  return -1;
286
0
}
287
288
int
289
sshkey_match_keyname_to_sigalgs(const char *keyname, const char *sigalgs)
290
0
{
291
0
  int ktype;
292
293
0
  if (sigalgs == NULL || *sigalgs == '\0' ||
294
0
      (ktype = sshkey_type_from_name(keyname)) == KEY_UNSPEC)
295
0
    return 0;
296
0
  else if (ktype == KEY_RSA) {
297
0
    return match_pattern_list("ssh-rsa", sigalgs, 0) == 1 ||
298
0
        match_pattern_list("rsa-sha2-256", sigalgs, 0) == 1 ||
299
0
        match_pattern_list("rsa-sha2-512", sigalgs, 0) == 1;
300
0
  } else if (ktype == KEY_RSA_CERT) {
301
0
    return match_pattern_list("ssh-rsa-cert-v01@openssh.com",
302
0
        sigalgs, 0) == 1 ||
303
0
        match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
304
0
        sigalgs, 0) == 1 ||
305
0
        match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
306
0
        sigalgs, 0) == 1;
307
0
  } else if (ktype == KEY_ECDSA_SK) {
308
0
    return match_pattern_list("sk-ecdsa-sha2-nistp256@openssh.com",
309
0
        sigalgs, 0) == 1 || match_pattern_list(
310
0
        "webauthn-sk-ecdsa-sha2-nistp256@openssh.com",
311
0
        sigalgs, 0) == 1;
312
0
  } else if (ktype == KEY_ECDSA_SK_CERT) {
313
0
    return match_pattern_list(
314
0
        "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com",
315
0
        sigalgs, 0) == 1 || match_pattern_list(
316
0
        "webauthn-sk-ecdsa-sha2-nistp256-cert-v01@openssh.com",
317
0
        sigalgs, 0) == 1;
318
0
  } else
319
0
    return match_pattern_list(keyname, sigalgs, 0) == 1;
320
0
}
321
322
char *
323
sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
324
0
{
325
0
  char *ret = NULL;
326
0
  size_t i;
327
0
  const struct sshkey_impl *impl;
328
0
  char sep_str[2] = {sep, '\0'};
329
330
0
  for (i = 0; keyimpls[i] != NULL; i++) {
331
0
    impl = keyimpls[i];
332
0
    if (impl->name == NULL)
333
0
      continue;
334
0
    if (!include_sigonly && impl->sigonly)
335
0
      continue;
336
0
    if ((certs_only && !impl->cert) || (plain_only && impl->cert))
337
0
      continue;
338
0
    xextendf(&ret, sep_str, "%s", impl->name);
339
0
  }
340
0
  return ret;
341
0
}
342
343
int
344
sshkey_names_valid2(const char *names, int allow_wildcard, int plain_only)
345
0
{
346
0
  char *s, *cp, *p;
347
0
  const struct sshkey_impl *impl;
348
0
  int i, type;
349
350
0
  if (names == NULL || strcmp(names, "") == 0)
351
0
    return 0;
352
0
  if ((s = cp = strdup(names)) == NULL)
353
0
    return 0;
354
0
  for ((p = strsep(&cp, ",")); p && *p != '\0';
355
0
      (p = strsep(&cp, ","))) {
356
0
    type = sshkey_type_from_name(p);
357
0
    if (type == KEY_UNSPEC) {
358
0
      if (allow_wildcard) {
359
        /*
360
         * Try matching key types against the string.
361
         * If any has a positive or negative match then
362
         * the component is accepted.
363
         */
364
0
        impl = NULL;
365
0
        for (i = 0; keyimpls[i] != NULL; i++) {
366
0
          if (match_pattern_list(
367
0
              keyimpls[i]->name, p, 0) != 0) {
368
0
            impl = keyimpls[i];
369
0
            break;
370
0
          }
371
0
        }
372
0
        if (impl != NULL)
373
0
          continue;
374
0
      }
375
0
      free(s);
376
0
      return 0;
377
0
    } else if (plain_only && sshkey_type_is_cert(type)) {
378
0
      free(s);
379
0
      return 0;
380
0
    }
381
0
  }
382
0
  free(s);
383
0
  return 1;
384
0
}
385
386
u_int
387
sshkey_size(const struct sshkey *k)
388
0
{
389
0
  const struct sshkey_impl *impl;
390
391
0
  if ((impl = sshkey_impl_from_key(k)) == NULL)
392
0
    return 0;
393
0
  if (impl->funcs->size != NULL)
394
0
    return impl->funcs->size(k);
395
0
  return impl->keybits;
396
0
}
397
398
static int
399
sshkey_type_is_valid_ca(int type)
400
0
{
401
0
  const struct sshkey_impl *impl;
402
403
0
  if ((impl = sshkey_impl_from_type(type)) == NULL)
404
0
    return 0;
405
  /* All non-certificate types may act as CAs */
406
0
  return !impl->cert;
407
0
}
408
409
int
410
sshkey_is_cert(const struct sshkey *k)
411
0
{
412
0
  if (k == NULL)
413
0
    return 0;
414
0
  return sshkey_type_is_cert(k->type);
415
0
}
416
417
int
418
sshkey_is_sk(const struct sshkey *k)
419
0
{
420
0
  if (k == NULL)
421
0
    return 0;
422
0
  switch (sshkey_type_plain(k->type)) {
423
0
  case KEY_ECDSA_SK:
424
0
  case KEY_ED25519_SK:
425
0
    return 1;
426
0
  default:
427
0
    return 0;
428
0
  }
429
0
}
430
431
/* Return the cert-less equivalent to a certified key type */
432
int
433
sshkey_type_plain(int type)
434
0
{
435
0
  switch (type) {
436
0
  case KEY_RSA_CERT:
437
0
    return KEY_RSA;
438
0
  case KEY_ECDSA_CERT:
439
0
    return KEY_ECDSA;
440
0
  case KEY_ECDSA_SK_CERT:
441
0
    return KEY_ECDSA_SK;
442
0
  case KEY_ED25519_CERT:
443
0
    return KEY_ED25519;
444
0
  case KEY_MLDSA44_ED25519_CERT:
445
0
    return KEY_MLDSA44_ED25519;
446
0
  case KEY_ED25519_SK_CERT:
447
0
    return KEY_ED25519_SK;
448
0
  default:
449
0
    return type;
450
0
  }
451
0
}
452
453
/* Return the cert equivalent to a plain key type */
454
static int
455
sshkey_type_certified(int type)
456
0
{
457
0
  switch (type) {
458
0
  case KEY_RSA:
459
0
    return KEY_RSA_CERT;
460
0
  case KEY_ECDSA:
461
0
    return KEY_ECDSA_CERT;
462
0
  case KEY_ECDSA_SK:
463
0
    return KEY_ECDSA_SK_CERT;
464
0
  case KEY_ED25519:
465
0
    return KEY_ED25519_CERT;
466
0
  case KEY_MLDSA44_ED25519:
467
0
    return KEY_MLDSA44_ED25519_CERT;
468
0
  case KEY_ED25519_SK:
469
0
    return KEY_ED25519_SK_CERT;
470
0
  default:
471
0
    return -1;
472
0
  }
473
0
}
474
475
#ifdef WITH_OPENSSL
476
static const EVP_MD *
477
ssh_digest_to_md(int hash_alg)
478
0
{
479
0
  switch (hash_alg) {
480
0
  case SSH_DIGEST_SHA1:
481
0
    return EVP_sha1();
482
0
  case SSH_DIGEST_SHA256:
483
0
    return EVP_sha256();
484
0
  case SSH_DIGEST_SHA384:
485
0
    return EVP_sha384();
486
0
  case SSH_DIGEST_SHA512:
487
0
    return EVP_sha512();
488
0
  }
489
0
  return NULL;
490
0
}
491
492
int
493
sshkey_pkey_digest_sign(EVP_PKEY *pkey, int hash_alg, u_char **sigp,
494
    size_t *lenp, const u_char *data, size_t datalen)
495
0
{
496
0
  EVP_MD_CTX *ctx = NULL;
497
0
  u_char *sig = NULL;
498
0
  int ret;
499
0
  size_t slen;
500
0
  const EVP_MD *evpmd;
501
502
0
  *sigp = NULL;
503
0
  *lenp = 0;
504
505
0
  slen = EVP_PKEY_size(pkey);
506
0
  if (slen <= 0 || slen > SSHBUF_MAX_BIGNUM ||
507
0
     (evpmd = ssh_digest_to_md(hash_alg)) == NULL)
508
0
    return SSH_ERR_INVALID_ARGUMENT;
509
510
0
  if ((sig = malloc(slen)) == NULL)
511
0
    return SSH_ERR_ALLOC_FAIL;
512
513
0
  if ((ctx = EVP_MD_CTX_new()) == NULL) {
514
0
    ret = SSH_ERR_ALLOC_FAIL;
515
0
    goto out;
516
0
  }
517
0
  if (EVP_DigestSignInit(ctx, NULL, evpmd, NULL, pkey) != 1 ||
518
0
      EVP_DigestSign(ctx, sig, &slen, data, datalen) != 1) {
519
0
    ret = SSH_ERR_LIBCRYPTO_ERROR;
520
0
    goto out;
521
0
  }
522
523
0
  *sigp = sig;
524
0
  *lenp = slen;
525
  /* Now owned by the caller */
526
0
  sig = NULL;
527
0
  ret = 0;
528
529
0
 out:
530
0
  EVP_MD_CTX_free(ctx);
531
0
  free(sig);
532
0
  return ret;
533
0
}
534
535
int
536
sshkey_pkey_digest_verify(EVP_PKEY *pkey, int hash_alg, const u_char *data,
537
    size_t datalen, u_char *sigbuf, size_t siglen)
538
0
{
539
0
  EVP_MD_CTX *ctx = NULL;
540
0
  int ret = SSH_ERR_INTERNAL_ERROR;
541
0
  const EVP_MD *evpmd;
542
543
0
  if ((evpmd = ssh_digest_to_md(hash_alg)) == NULL)
544
0
    return SSH_ERR_INVALID_ARGUMENT;
545
0
  if ((ctx = EVP_MD_CTX_new()) == NULL)
546
0
    return SSH_ERR_ALLOC_FAIL;
547
0
  if (EVP_DigestVerifyInit(ctx, NULL, evpmd, NULL, pkey) != 1) {
548
0
    ret = SSH_ERR_LIBCRYPTO_ERROR;
549
0
    goto out;
550
0
  }
551
0
  switch (EVP_DigestVerify(ctx, sigbuf, siglen, data, datalen)) {
552
0
  case 1:
553
0
    ret = 0;
554
0
    break;
555
0
  case 0:
556
0
    ret = SSH_ERR_SIGNATURE_INVALID;
557
0
    break;
558
0
  default:
559
0
    ret = SSH_ERR_LIBCRYPTO_ERROR;
560
0
    break;
561
0
  }
562
563
0
 out:
564
0
  EVP_MD_CTX_free(ctx);
565
0
  return ret;
566
0
}
567
568
/* XXX: these are really begging for a table-driven approach */
569
int
570
sshkey_curve_name_to_nid(const char *name)
571
0
{
572
0
  if (strcmp(name, "nistp256") == 0)
573
0
    return NID_X9_62_prime256v1;
574
0
  else if (strcmp(name, "nistp384") == 0)
575
0
    return NID_secp384r1;
576
0
  else if (strcmp(name, "nistp521") == 0)
577
0
    return NID_secp521r1;
578
0
  else
579
0
    return -1;
580
0
}
581
582
u_int
583
sshkey_curve_nid_to_bits(int nid)
584
0
{
585
0
  switch (nid) {
586
0
  case NID_X9_62_prime256v1:
587
0
    return 256;
588
0
  case NID_secp384r1:
589
0
    return 384;
590
0
  case NID_secp521r1:
591
0
    return 521;
592
0
  default:
593
0
    return 0;
594
0
  }
595
0
}
596
597
int
598
sshkey_ecdsa_bits_to_nid(int bits)
599
0
{
600
0
  switch (bits) {
601
0
  case 256:
602
0
    return NID_X9_62_prime256v1;
603
0
  case 384:
604
0
    return NID_secp384r1;
605
0
  case 521:
606
0
    return NID_secp521r1;
607
0
  default:
608
0
    return -1;
609
0
  }
610
0
}
611
612
const char *
613
sshkey_curve_nid_to_name(int nid)
614
0
{
615
0
  switch (nid) {
616
0
  case NID_X9_62_prime256v1:
617
0
    return "nistp256";
618
0
  case NID_secp384r1:
619
0
    return "nistp384";
620
0
  case NID_secp521r1:
621
0
    return "nistp521";
622
0
  default:
623
0
    return NULL;
624
0
  }
625
0
}
626
627
int
628
sshkey_ec_nid_to_hash_alg(int nid)
629
0
{
630
0
  int kbits = sshkey_curve_nid_to_bits(nid);
631
632
0
  if (kbits <= 0)
633
0
    return -1;
634
635
  /* RFC5656 section 6.2.1 */
636
0
  if (kbits <= 256)
637
0
    return SSH_DIGEST_SHA256;
638
0
  else if (kbits <= 384)
639
0
    return SSH_DIGEST_SHA384;
640
0
  else
641
0
    return SSH_DIGEST_SHA512;
642
0
}
643
#endif /* WITH_OPENSSL */
644
645
static void
646
cert_free(struct sshkey_cert *cert)
647
0
{
648
0
  u_int i;
649
650
0
  if (cert == NULL)
651
0
    return;
652
0
  sshbuf_free(cert->certblob);
653
0
  sshbuf_free(cert->critical);
654
0
  sshbuf_free(cert->extensions);
655
0
  free(cert->key_id);
656
0
  for (i = 0; i < cert->nprincipals; i++)
657
0
    free(cert->principals[i]);
658
0
  free(cert->principals);
659
0
  sshkey_free(cert->signature_key);
660
0
  free(cert->signature_type);
661
0
  freezero(cert, sizeof(*cert));
662
0
}
663
664
static struct sshkey_cert *
665
cert_new(void)
666
0
{
667
0
  struct sshkey_cert *cert;
668
669
0
  if ((cert = calloc(1, sizeof(*cert))) == NULL)
670
0
    return NULL;
671
0
  if ((cert->certblob = sshbuf_new()) == NULL ||
672
0
      (cert->critical = sshbuf_new()) == NULL ||
673
0
      (cert->extensions = sshbuf_new()) == NULL) {
674
0
    cert_free(cert);
675
0
    return NULL;
676
0
  }
677
0
  cert->key_id = NULL;
678
0
  cert->principals = NULL;
679
0
  cert->signature_key = NULL;
680
0
  cert->signature_type = NULL;
681
0
  return cert;
682
0
}
683
684
struct sshkey *
685
sshkey_new(int type)
686
0
{
687
0
  struct sshkey *k;
688
0
  const struct sshkey_impl *impl = NULL;
689
690
0
  if (type != KEY_UNSPEC &&
691
0
      (impl = sshkey_impl_from_type(type)) == NULL)
692
0
    return NULL;
693
694
  /* All non-certificate types may act as CAs */
695
0
  if ((k = calloc(1, sizeof(*k))) == NULL)
696
0
    return NULL;
697
0
  k->type = type;
698
0
  k->ecdsa_nid = -1;
699
0
  if (impl != NULL && impl->funcs->alloc != NULL) {
700
0
    if (impl->funcs->alloc(k) != 0) {
701
0
      free(k);
702
0
      return NULL;
703
0
    }
704
0
  }
705
0
  if (sshkey_is_cert(k)) {
706
0
    if ((k->cert = cert_new()) == NULL) {
707
0
      sshkey_free(k);
708
0
      return NULL;
709
0
    }
710
0
  }
711
712
0
  return k;
713
0
}
714
715
/* Frees common FIDO fields */
716
void
717
sshkey_sk_cleanup(struct sshkey *k)
718
0
{
719
0
  free(k->sk_application);
720
0
  sshbuf_free(k->sk_key_handle);
721
0
  sshbuf_free(k->sk_reserved);
722
0
  k->sk_application = NULL;
723
0
  k->sk_key_handle = k->sk_reserved = NULL;
724
0
}
725
726
#if defined(MAP_CONCEAL)
727
# define PREKEY_MMAP_FLAG MAP_CONCEAL
728
#elif defined(MAP_NOCORE)
729
# define PREKEY_MMAP_FLAG MAP_NOCORE
730
#else
731
0
# define PREKEY_MMAP_FLAG 0
732
#endif
733
734
static int
735
sshkey_prekey_alloc(u_char **prekeyp, size_t len)
736
0
{
737
0
#if defined(HAVE_MMAP) && defined(MAP_ANON) && defined(MAP_PRIVATE)
738
0
  u_char *prekey;
739
740
0
  *prekeyp = NULL;
741
0
  if ((prekey = mmap(NULL, len, PROT_READ|PROT_WRITE,
742
0
      MAP_ANON|MAP_PRIVATE|PREKEY_MMAP_FLAG, -1, 0)) == MAP_FAILED)
743
0
    return SSH_ERR_SYSTEM_ERROR;
744
0
#if defined(MADV_DONTDUMP) && !defined(MAP_CONCEAL) && !defined(MAP_NOCORE)
745
0
  (void)madvise(prekey, len, MADV_DONTDUMP);
746
0
#endif
747
0
  *prekeyp = prekey;
748
#else
749
  *prekeyp = calloc(1, len);
750
#endif /* HAVE_MMAP et al */
751
0
  return 0;
752
0
}
753
754
static void
755
sshkey_prekey_free(void *prekey, size_t len)
756
0
{
757
0
#if defined(HAVE_MMAP) && defined(MAP_ANON) && defined(MAP_PRIVATE)
758
0
  if (prekey == NULL)
759
0
    return;
760
0
  munmap(prekey, len);
761
#else
762
  free(prekey);
763
#endif /* HAVE_MMAP et al */
764
0
}
765
766
static void
767
sshkey_free_contents(struct sshkey *k)
768
0
{
769
0
  const struct sshkey_impl *impl;
770
771
0
  if (k == NULL)
772
0
    return;
773
0
  if ((k->flags & SSHKEY_FLAG_EXT) != 0)
774
0
    pkcs11_key_free(k);
775
0
  if ((impl = sshkey_impl_from_type(k->type)) != NULL &&
776
0
      impl->funcs->cleanup != NULL)
777
0
    impl->funcs->cleanup(k);
778
0
  if (sshkey_is_cert(k))
779
0
    cert_free(k->cert);
780
0
  freezero(k->shielded_private, k->shielded_len);
781
0
  sshkey_prekey_free(k->shield_prekey, k->shield_prekey_len);
782
0
}
783
784
void
785
sshkey_free(struct sshkey *k)
786
0
{
787
0
  sshkey_free_contents(k);
788
0
  freezero(k, sizeof(*k));
789
0
}
790
791
static int
792
cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
793
0
{
794
0
  if (a == NULL && b == NULL)
795
0
    return 1;
796
0
  if (a == NULL || b == NULL)
797
0
    return 0;
798
0
  if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
799
0
    return 0;
800
0
  if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
801
0
      sshbuf_len(a->certblob)) != 0)
802
0
    return 0;
803
0
  return 1;
804
0
}
805
806
/* Compares FIDO-specific pubkey fields only */
807
int
808
sshkey_sk_fields_equal(const struct sshkey *a, const struct sshkey *b)
809
0
{
810
0
  if (a->sk_application == NULL || b->sk_application == NULL)
811
0
    return 0;
812
0
  if (strcmp(a->sk_application, b->sk_application) != 0)
813
0
    return 0;
814
0
  return 1;
815
0
}
816
817
/*
818
 * Compare public portions of key only, allowing comparisons between
819
 * certificates and plain keys too.
820
 */
821
int
822
sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
823
0
{
824
0
  const struct sshkey_impl *impl;
825
826
0
  if (a == NULL || b == NULL ||
827
0
      sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
828
0
    return 0;
829
0
  if ((impl = sshkey_impl_from_type(a->type)) == NULL)
830
0
    return 0;
831
0
  return impl->funcs->equal(a, b);
832
0
}
833
834
int
835
sshkey_equal(const struct sshkey *a, const struct sshkey *b)
836
0
{
837
0
  if (a == NULL || b == NULL || a->type != b->type)
838
0
    return 0;
839
0
  if (sshkey_is_cert(a)) {
840
0
    if (!cert_compare(a->cert, b->cert))
841
0
      return 0;
842
0
  }
843
0
  return sshkey_equal_public(a, b);
844
0
}
845
846
847
/* Serialise common FIDO key parts */
848
int
849
sshkey_serialize_sk(const struct sshkey *key, struct sshbuf *b)
850
0
{
851
0
  int r;
852
853
0
  if ((r = sshbuf_put_cstring(b, key->sk_application)) != 0)
854
0
    return r;
855
856
0
  return 0;
857
0
}
858
859
static int
860
to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain,
861
  enum sshkey_serialize_rep opts)
862
0
{
863
0
  int type, ret = SSH_ERR_INTERNAL_ERROR;
864
0
  const char *typename;
865
0
  const struct sshkey_impl *impl;
866
867
0
  if (key == NULL)
868
0
    return SSH_ERR_INVALID_ARGUMENT;
869
870
0
  type = force_plain ? sshkey_type_plain(key->type) : key->type;
871
872
0
  if (sshkey_type_is_cert(type)) {
873
0
    if (key->cert == NULL)
874
0
      return SSH_ERR_EXPECTED_CERT;
875
0
    if (sshbuf_len(key->cert->certblob) == 0)
876
0
      return SSH_ERR_KEY_LACKS_CERTBLOB;
877
    /* Use the existing blob */
878
0
    if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
879
0
      return ret;
880
0
    return 0;
881
0
  }
882
0
  if ((impl = sshkey_impl_from_type(type)) == NULL)
883
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
884
885
0
  typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
886
0
  if ((ret = sshbuf_put_cstring(b, typename)) != 0)
887
0
    return ret;
888
0
  return impl->funcs->serialize_public(key, b, opts);
889
0
}
890
891
int
892
sshkey_putb(const struct sshkey *key, struct sshbuf *b)
893
0
{
894
0
  return to_blob_buf(key, b, 0, SSHKEY_SERIALIZE_DEFAULT);
895
0
}
896
897
static int
898
sshkey_puts_opts_internal(const struct sshkey *key, struct sshbuf *b,
899
    enum sshkey_serialize_rep opts, int force_plain)
900
0
{
901
0
  struct sshbuf *tmp;
902
0
  int r;
903
904
0
  if ((tmp = sshbuf_new()) == NULL)
905
0
    return SSH_ERR_ALLOC_FAIL;
906
0
  r = to_blob_buf(key, tmp, force_plain, opts);
907
0
  if (r == 0)
908
0
    r = sshbuf_put_stringb(b, tmp);
909
0
  sshbuf_free(tmp);
910
0
  return r;
911
0
}
912
913
int
914
sshkey_puts(const struct sshkey *key, struct sshbuf *b)
915
0
{
916
0
  return sshkey_puts_opts_internal(key, b, SSHKEY_SERIALIZE_DEFAULT, 0);
917
0
}
918
919
int
920
sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
921
0
{
922
0
  return to_blob_buf(key, b, 1, SSHKEY_SERIALIZE_DEFAULT);
923
0
}
924
925
int
926
sshkey_puts_plain(const struct sshkey *key, struct sshbuf *b)
927
0
{
928
0
  return sshkey_puts_opts_internal(key, b, SSHKEY_SERIALIZE_DEFAULT, 1);
929
0
}
930
931
static int
932
to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain,
933
    enum sshkey_serialize_rep opts)
934
0
{
935
0
  int ret = SSH_ERR_INTERNAL_ERROR;
936
0
  size_t len;
937
0
  struct sshbuf *b = NULL;
938
939
0
  if (lenp != NULL)
940
0
    *lenp = 0;
941
0
  if (blobp != NULL)
942
0
    *blobp = NULL;
943
0
  if ((b = sshbuf_new()) == NULL)
944
0
    return SSH_ERR_ALLOC_FAIL;
945
0
  if ((ret = to_blob_buf(key, b, force_plain, opts)) != 0)
946
0
    goto out;
947
0
  len = sshbuf_len(b);
948
0
  if (lenp != NULL)
949
0
    *lenp = len;
950
0
  if (blobp != NULL) {
951
0
    if ((*blobp = malloc(len)) == NULL) {
952
0
      ret = SSH_ERR_ALLOC_FAIL;
953
0
      goto out;
954
0
    }
955
0
    memcpy(*blobp, sshbuf_ptr(b), len);
956
0
  }
957
0
  ret = 0;
958
0
 out:
959
0
  sshbuf_free(b);
960
0
  return ret;
961
0
}
962
963
int
964
sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
965
0
{
966
0
  return to_blob(key, blobp, lenp, 0, SSHKEY_SERIALIZE_DEFAULT);
967
0
}
968
969
int
970
sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
971
0
{
972
0
  return to_blob(key, blobp, lenp, 1, SSHKEY_SERIALIZE_DEFAULT);
973
0
}
974
975
int
976
sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
977
    u_char **retp, size_t *lenp)
978
0
{
979
0
  u_char *blob = NULL, *ret = NULL;
980
0
  size_t blob_len = 0;
981
0
  int r = SSH_ERR_INTERNAL_ERROR;
982
983
0
  if (retp != NULL)
984
0
    *retp = NULL;
985
0
  if (lenp != NULL)
986
0
    *lenp = 0;
987
0
  if (ssh_digest_bytes(dgst_alg) == 0) {
988
0
    r = SSH_ERR_INVALID_ARGUMENT;
989
0
    goto out;
990
0
  }
991
0
  if ((r = to_blob(k, &blob, &blob_len, 1, SSHKEY_SERIALIZE_DEFAULT))
992
0
      != 0)
993
0
    goto out;
994
0
  if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
995
0
    r = SSH_ERR_ALLOC_FAIL;
996
0
    goto out;
997
0
  }
998
0
  if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
999
0
      ret, SSH_DIGEST_MAX_LENGTH)) != 0)
1000
0
    goto out;
1001
  /* success */
1002
0
  if (retp != NULL) {
1003
0
    *retp = ret;
1004
0
    ret = NULL;
1005
0
  }
1006
0
  if (lenp != NULL)
1007
0
    *lenp = ssh_digest_bytes(dgst_alg);
1008
0
  r = 0;
1009
0
 out:
1010
0
  free(ret);
1011
0
  if (blob != NULL)
1012
0
    freezero(blob, blob_len);
1013
0
  return r;
1014
0
}
1015
1016
static char *
1017
fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1018
0
{
1019
0
  char *ret;
1020
0
  size_t plen = strlen(alg) + 1;
1021
0
  size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
1022
1023
0
  if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
1024
0
    return NULL;
1025
0
  strlcpy(ret, alg, rlen);
1026
0
  strlcat(ret, ":", rlen);
1027
0
  if (dgst_raw_len == 0)
1028
0
    return ret;
1029
0
  if (b64_ntop(dgst_raw, dgst_raw_len, ret + plen, rlen - plen) == -1) {
1030
0
    freezero(ret, rlen);
1031
0
    return NULL;
1032
0
  }
1033
  /* Trim padding characters from end */
1034
0
  ret[strcspn(ret, "=")] = '\0';
1035
0
  return ret;
1036
0
}
1037
1038
static char *
1039
fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1040
0
{
1041
0
  char *retval, hex[5];
1042
0
  size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
1043
1044
0
  if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
1045
0
    return NULL;
1046
0
  strlcpy(retval, alg, rlen);
1047
0
  strlcat(retval, ":", rlen);
1048
0
  for (i = 0; i < dgst_raw_len; i++) {
1049
0
    snprintf(hex, sizeof(hex), "%s%02x",
1050
0
        i > 0 ? ":" : "", dgst_raw[i]);
1051
0
    strlcat(retval, hex, rlen);
1052
0
  }
1053
0
  return retval;
1054
0
}
1055
1056
static char *
1057
fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
1058
0
{
1059
0
  char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
1060
0
  char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
1061
0
      'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1062
0
  u_int i, j = 0, rounds, seed = 1;
1063
0
  char *retval;
1064
1065
0
  rounds = (dgst_raw_len / 2) + 1;
1066
0
  if ((retval = calloc(rounds, 6)) == NULL)
1067
0
    return NULL;
1068
0
  retval[j++] = 'x';
1069
0
  for (i = 0; i < rounds; i++) {
1070
0
    u_int idx0, idx1, idx2, idx3, idx4;
1071
0
    if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
1072
0
      idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1073
0
          seed) % 6;
1074
0
      idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
1075
0
      idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1076
0
          (seed / 6)) % 6;
1077
0
      retval[j++] = vowels[idx0];
1078
0
      retval[j++] = consonants[idx1];
1079
0
      retval[j++] = vowels[idx2];
1080
0
      if ((i + 1) < rounds) {
1081
0
        idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1082
0
        idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1083
0
        retval[j++] = consonants[idx3];
1084
0
        retval[j++] = '-';
1085
0
        retval[j++] = consonants[idx4];
1086
0
        seed = ((seed * 5) +
1087
0
            ((((u_int)(dgst_raw[2 * i])) * 7) +
1088
0
            ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1089
0
      }
1090
0
    } else {
1091
0
      idx0 = seed % 6;
1092
0
      idx1 = 16;
1093
0
      idx2 = seed / 6;
1094
0
      retval[j++] = vowels[idx0];
1095
0
      retval[j++] = consonants[idx1];
1096
0
      retval[j++] = vowels[idx2];
1097
0
    }
1098
0
  }
1099
0
  retval[j++] = 'x';
1100
0
  retval[j++] = '\0';
1101
0
  return retval;
1102
0
}
1103
1104
/*
1105
 * Draw an ASCII-Art representing the fingerprint so human brain can
1106
 * profit from its built-in pattern recognition ability.
1107
 * This technique is called "random art" and can be found in some
1108
 * scientific publications like this original paper:
1109
 *
1110
 * "Hash Visualization: a New Technique to improve Real-World Security",
1111
 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1112
 * Techniques and E-Commerce (CrypTEC '99)
1113
 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1114
 *
1115
 * The subject came up in a talk by Dan Kaminsky, too.
1116
 *
1117
 * If you see the picture is different, the key is different.
1118
 * If the picture looks the same, you still know nothing.
1119
 *
1120
 * The algorithm used here is a worm crawling over a discrete plane,
1121
 * leaving a trace (augmenting the field) everywhere it goes.
1122
 * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1123
 * makes the respective movement vector be ignored for this turn.
1124
 * Graphs are not unambiguous, because circles in graphs can be
1125
 * walked in either direction.
1126
 */
1127
1128
/*
1129
 * Field sizes for the random art.  Have to be odd, so the starting point
1130
 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1131
 * Else pictures would be too dense, and drawing the frame would
1132
 * fail, too, because the key type would not fit in anymore.
1133
 */
1134
0
#define FLDBASE   8
1135
0
#define FLDSIZE_Y (FLDBASE + 1)
1136
0
#define FLDSIZE_X (FLDBASE * 2 + 1)
1137
static char *
1138
fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1139
    const struct sshkey *k)
1140
0
{
1141
  /*
1142
   * Chars to be used after each other every time the worm
1143
   * intersects with itself.  Matter of taste.
1144
   */
1145
0
  char  *augmentation_string = " .o+=*BOX@%&#/^SE";
1146
0
  char  *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1147
0
  u_char   field[FLDSIZE_X][FLDSIZE_Y];
1148
0
  size_t   i, tlen, hlen;
1149
0
  u_int  b;
1150
0
  int  x, y, r;
1151
0
  size_t   len = strlen(augmentation_string) - 1;
1152
1153
0
  if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1154
0
    return NULL;
1155
1156
  /* initialize field */
1157
0
  memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1158
0
  x = FLDSIZE_X / 2;
1159
0
  y = FLDSIZE_Y / 2;
1160
1161
  /* process raw key */
1162
0
  for (i = 0; i < dgst_raw_len; i++) {
1163
0
    int input;
1164
    /* each byte conveys four 2-bit move commands */
1165
0
    input = dgst_raw[i];
1166
0
    for (b = 0; b < 4; b++) {
1167
      /* evaluate 2 bit, rest is shifted later */
1168
0
      x += (input & 0x1) ? 1 : -1;
1169
0
      y += (input & 0x2) ? 1 : -1;
1170
1171
      /* assure we are still in bounds */
1172
0
      x = MAXIMUM(x, 0);
1173
0
      y = MAXIMUM(y, 0);
1174
0
      x = MINIMUM(x, FLDSIZE_X - 1);
1175
0
      y = MINIMUM(y, FLDSIZE_Y - 1);
1176
1177
      /* augment the field */
1178
0
      if (field[x][y] < len - 2)
1179
0
        field[x][y]++;
1180
0
      input = input >> 2;
1181
0
    }
1182
0
  }
1183
1184
  /* mark starting point and end point*/
1185
0
  field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1186
0
  field[x][y] = len;
1187
1188
  /* assemble title */
1189
0
  r = snprintf(title, sizeof(title), "[%s %u]",
1190
0
    sshkey_type(k), sshkey_size(k));
1191
  /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1192
0
  if (r < 0 || r > (int)sizeof(title))
1193
0
    r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1194
0
  tlen = (r <= 0) ? 0 : strlen(title);
1195
1196
  /* assemble hash ID. */
1197
0
  r = snprintf(hash, sizeof(hash), "[%s]", alg);
1198
0
  hlen = (r <= 0) ? 0 : strlen(hash);
1199
1200
  /* output upper border */
1201
0
  p = retval;
1202
0
  *p++ = '+';
1203
0
  for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1204
0
    *p++ = '-';
1205
0
  memcpy(p, title, tlen);
1206
0
  p += tlen;
1207
0
  for (i += tlen; i < FLDSIZE_X; i++)
1208
0
    *p++ = '-';
1209
0
  *p++ = '+';
1210
0
  *p++ = '\n';
1211
1212
  /* output content */
1213
0
  for (y = 0; y < FLDSIZE_Y; y++) {
1214
0
    *p++ = '|';
1215
0
    for (x = 0; x < FLDSIZE_X; x++)
1216
0
      *p++ = augmentation_string[MINIMUM(field[x][y], len)];
1217
0
    *p++ = '|';
1218
0
    *p++ = '\n';
1219
0
  }
1220
1221
  /* output lower border */
1222
0
  *p++ = '+';
1223
0
  for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1224
0
    *p++ = '-';
1225
0
  memcpy(p, hash, hlen);
1226
0
  p += hlen;
1227
0
  for (i += hlen; i < FLDSIZE_X; i++)
1228
0
    *p++ = '-';
1229
0
  *p++ = '+';
1230
1231
0
  return retval;
1232
0
}
1233
1234
char *
1235
sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1236
    enum sshkey_fp_rep dgst_rep)
1237
0
{
1238
0
  char *retval = NULL;
1239
0
  u_char *dgst_raw;
1240
0
  size_t dgst_raw_len;
1241
1242
0
  if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1243
0
    return NULL;
1244
0
  switch (dgst_rep) {
1245
0
  case SSH_FP_DEFAULT:
1246
0
    if (dgst_alg == SSH_DIGEST_MD5) {
1247
0
      retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1248
0
          dgst_raw, dgst_raw_len);
1249
0
    } else {
1250
0
      retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1251
0
          dgst_raw, dgst_raw_len);
1252
0
    }
1253
0
    break;
1254
0
  case SSH_FP_HEX:
1255
0
    retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1256
0
        dgst_raw, dgst_raw_len);
1257
0
    break;
1258
0
  case SSH_FP_BASE64:
1259
0
    retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1260
0
        dgst_raw, dgst_raw_len);
1261
0
    break;
1262
0
  case SSH_FP_BUBBLEBABBLE:
1263
0
    retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1264
0
    break;
1265
0
  case SSH_FP_RANDOMART:
1266
0
    retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1267
0
        dgst_raw, dgst_raw_len, k);
1268
0
    break;
1269
0
  default:
1270
0
    freezero(dgst_raw, dgst_raw_len);
1271
0
    return NULL;
1272
0
  }
1273
0
  freezero(dgst_raw, dgst_raw_len);
1274
0
  return retval;
1275
0
}
1276
1277
static int
1278
peek_type_nid(const char *s, size_t l, int *nid)
1279
0
{
1280
0
  const struct sshkey_impl *impl;
1281
0
  int i;
1282
1283
0
  for (i = 0; keyimpls[i] != NULL; i++) {
1284
0
    impl = keyimpls[i];
1285
0
    if (impl->name == NULL || strlen(impl->name) != l)
1286
0
      continue;
1287
0
    if (memcmp(s, impl->name, l) == 0) {
1288
0
      *nid = -1;
1289
0
      if (key_type_is_ecdsa_variant(impl->type))
1290
0
        *nid = impl->nid;
1291
0
      return impl->type;
1292
0
    }
1293
0
  }
1294
0
  return KEY_UNSPEC;
1295
0
}
1296
1297
/* XXX this can now be made const char * */
1298
int
1299
sshkey_read(struct sshkey *ret, char **cpp)
1300
0
{
1301
0
  struct sshkey *k;
1302
0
  char *cp, *blobcopy;
1303
0
  size_t space;
1304
0
  int r, type, curve_nid = -1;
1305
0
  struct sshbuf *blob;
1306
1307
0
  if (ret == NULL)
1308
0
    return SSH_ERR_INVALID_ARGUMENT;
1309
0
  if (ret->type != KEY_UNSPEC && sshkey_impl_from_type(ret->type) == NULL)
1310
0
    return SSH_ERR_INVALID_ARGUMENT;
1311
1312
  /* Decode type */
1313
0
  cp = *cpp;
1314
0
  space = strcspn(cp, " \t");
1315
0
  if (space == strlen(cp))
1316
0
    return SSH_ERR_INVALID_FORMAT;
1317
0
  if ((type = peek_type_nid(cp, space, &curve_nid)) == KEY_UNSPEC)
1318
0
    return SSH_ERR_INVALID_FORMAT;
1319
1320
  /* skip whitespace */
1321
0
  for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1322
0
    ;
1323
0
  if (*cp == '\0')
1324
0
    return SSH_ERR_INVALID_FORMAT;
1325
0
  if (ret->type != KEY_UNSPEC && ret->type != type)
1326
0
    return SSH_ERR_KEY_TYPE_MISMATCH;
1327
0
  if ((blob = sshbuf_new()) == NULL)
1328
0
    return SSH_ERR_ALLOC_FAIL;
1329
1330
  /* find end of keyblob and decode */
1331
0
  space = strcspn(cp, " \t");
1332
0
  if ((blobcopy = strndup(cp, space)) == NULL) {
1333
0
    sshbuf_free(blob);
1334
0
    return SSH_ERR_ALLOC_FAIL;
1335
0
  }
1336
0
  if ((r = sshbuf_b64tod(blob, blobcopy)) != 0) {
1337
0
    free(blobcopy);
1338
0
    sshbuf_free(blob);
1339
0
    return r;
1340
0
  }
1341
0
  free(blobcopy);
1342
0
  if ((r = sshkey_fromb(blob, &k)) != 0) {
1343
0
    sshbuf_free(blob);
1344
0
    return r;
1345
0
  }
1346
0
  sshbuf_free(blob);
1347
1348
  /* skip whitespace and leave cp at start of comment */
1349
0
  for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1350
0
    ;
1351
1352
  /* ensure type of blob matches type at start of line */
1353
0
  if (k->type != type) {
1354
0
    sshkey_free(k);
1355
0
    return SSH_ERR_KEY_TYPE_MISMATCH;
1356
0
  }
1357
0
  if (key_type_is_ecdsa_variant(type) && curve_nid != k->ecdsa_nid) {
1358
0
    sshkey_free(k);
1359
0
    return SSH_ERR_EC_CURVE_MISMATCH;
1360
0
  }
1361
1362
  /* Fill in ret from parsed key */
1363
0
  sshkey_free_contents(ret);
1364
0
  *ret = *k;
1365
0
  freezero(k, sizeof(*k));
1366
1367
  /* success */
1368
0
  *cpp = cp;
1369
0
  return 0;
1370
0
}
1371
1372
int
1373
sshkey_to_base64(const struct sshkey *key, char **b64p)
1374
0
{
1375
0
  int r = SSH_ERR_INTERNAL_ERROR;
1376
0
  struct sshbuf *b = NULL;
1377
0
  char *uu = NULL;
1378
1379
0
  if (b64p != NULL)
1380
0
    *b64p = NULL;
1381
0
  if ((b = sshbuf_new()) == NULL)
1382
0
    return SSH_ERR_ALLOC_FAIL;
1383
0
  if ((r = sshkey_putb(key, b)) != 0)
1384
0
    goto out;
1385
0
  if ((uu = sshbuf_dtob64_string(b, 0)) == NULL) {
1386
0
    r = SSH_ERR_ALLOC_FAIL;
1387
0
    goto out;
1388
0
  }
1389
  /* Success */
1390
0
  if (b64p != NULL) {
1391
0
    *b64p = uu;
1392
0
    uu = NULL;
1393
0
  }
1394
0
  r = 0;
1395
0
 out:
1396
0
  sshbuf_free(b);
1397
0
  free(uu);
1398
0
  return r;
1399
0
}
1400
1401
int
1402
sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1403
0
{
1404
0
  int r = SSH_ERR_INTERNAL_ERROR;
1405
0
  char *uu = NULL;
1406
1407
0
  if ((r = sshkey_to_base64(key, &uu)) != 0)
1408
0
    goto out;
1409
0
  if ((r = sshbuf_putf(b, "%s %s",
1410
0
      sshkey_ssh_name(key), uu)) != 0)
1411
0
    goto out;
1412
0
  r = 0;
1413
0
 out:
1414
0
  free(uu);
1415
0
  return r;
1416
0
}
1417
1418
int
1419
sshkey_write(const struct sshkey *key, FILE *f)
1420
0
{
1421
0
  struct sshbuf *b = NULL;
1422
0
  int r = SSH_ERR_INTERNAL_ERROR;
1423
1424
0
  if ((b = sshbuf_new()) == NULL)
1425
0
    return SSH_ERR_ALLOC_FAIL;
1426
0
  if ((r = sshkey_format_text(key, b)) != 0)
1427
0
    goto out;
1428
0
  if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1429
0
    if (feof(f))
1430
0
      errno = EPIPE;
1431
0
    r = SSH_ERR_SYSTEM_ERROR;
1432
0
    goto out;
1433
0
  }
1434
  /* Success */
1435
0
  r = 0;
1436
0
 out:
1437
0
  sshbuf_free(b);
1438
0
  return r;
1439
0
}
1440
1441
const char *
1442
sshkey_cert_type(const struct sshkey *k)
1443
0
{
1444
0
  switch (k->cert->type) {
1445
0
  case SSH2_CERT_TYPE_USER:
1446
0
    return "user";
1447
0
  case SSH2_CERT_TYPE_HOST:
1448
0
    return "host";
1449
0
  default:
1450
0
    return "unknown";
1451
0
  }
1452
0
}
1453
1454
int
1455
sshkey_check_rsa_length(const struct sshkey *k, int min_size)
1456
0
{
1457
0
#ifdef WITH_OPENSSL
1458
0
  int nbits;
1459
1460
0
  if (k == NULL || k->pkey == NULL ||
1461
0
      (k->type != KEY_RSA && k->type != KEY_RSA_CERT))
1462
0
    return 0;
1463
0
  nbits = EVP_PKEY_bits(k->pkey);
1464
0
  if (nbits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1465
0
      (min_size > 0 && nbits < min_size))
1466
0
    return SSH_ERR_KEY_LENGTH;
1467
0
#endif /* WITH_OPENSSL */
1468
0
  return 0;
1469
0
}
1470
1471
#ifdef WITH_OPENSSL
1472
int
1473
sshkey_ecdsa_key_to_nid(const EC_KEY *k)
1474
0
{
1475
0
  const EC_GROUP *g;
1476
0
  int nid;
1477
1478
0
  if (k == NULL || (g = EC_KEY_get0_group(k)) == NULL)
1479
0
    return -1;
1480
0
  if ((nid = EC_GROUP_get_curve_name(g)) <= 0)
1481
0
    return -1;
1482
0
  return nid;
1483
0
}
1484
1485
int
1486
sshkey_ecdsa_pkey_to_nid(EVP_PKEY *pkey)
1487
0
{
1488
0
  return sshkey_ecdsa_key_to_nid(EVP_PKEY_get0_EC_KEY(pkey));
1489
0
}
1490
#endif /* WITH_OPENSSL */
1491
1492
int
1493
sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1494
0
{
1495
0
  struct sshkey *k;
1496
0
  int ret = SSH_ERR_INTERNAL_ERROR;
1497
0
  const struct sshkey_impl *impl;
1498
1499
0
  if (keyp == NULL || sshkey_type_is_cert(type))
1500
0
    return SSH_ERR_INVALID_ARGUMENT;
1501
0
  *keyp = NULL;
1502
0
  if ((impl = sshkey_impl_from_type(type)) == NULL)
1503
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
1504
0
  if (impl->funcs->generate == NULL)
1505
0
    return SSH_ERR_FEATURE_UNSUPPORTED;
1506
0
  if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1507
0
    return SSH_ERR_ALLOC_FAIL;
1508
0
  k->type = type;
1509
0
  if ((ret = impl->funcs->generate(k, bits)) != 0) {
1510
0
    sshkey_free(k);
1511
0
    return ret;
1512
0
  }
1513
  /* success */
1514
0
  *keyp = k;
1515
0
  return 0;
1516
0
}
1517
1518
int
1519
sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1520
0
{
1521
0
  u_int i;
1522
0
  const struct sshkey_cert *from;
1523
0
  struct sshkey_cert *to;
1524
0
  int r = SSH_ERR_INTERNAL_ERROR;
1525
1526
0
  if (to_key == NULL || (from = from_key->cert) == NULL)
1527
0
    return SSH_ERR_INVALID_ARGUMENT;
1528
1529
0
  if ((to = cert_new()) == NULL)
1530
0
    return SSH_ERR_ALLOC_FAIL;
1531
1532
0
  if ((r = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1533
0
      (r = sshbuf_putb(to->critical, from->critical)) != 0 ||
1534
0
      (r = sshbuf_putb(to->extensions, from->extensions)) != 0)
1535
0
    goto out;
1536
1537
0
  to->serial = from->serial;
1538
0
  to->type = from->type;
1539
0
  if (from->key_id == NULL)
1540
0
    to->key_id = NULL;
1541
0
  else if ((to->key_id = strdup(from->key_id)) == NULL) {
1542
0
    r = SSH_ERR_ALLOC_FAIL;
1543
0
    goto out;
1544
0
  }
1545
0
  to->valid_after = from->valid_after;
1546
0
  to->valid_before = from->valid_before;
1547
0
  if (from->signature_key == NULL)
1548
0
    to->signature_key = NULL;
1549
0
  else if ((r = sshkey_from_private(from->signature_key,
1550
0
      &to->signature_key)) != 0)
1551
0
    goto out;
1552
0
  if (from->signature_type != NULL &&
1553
0
      (to->signature_type = strdup(from->signature_type)) == NULL) {
1554
0
    r = SSH_ERR_ALLOC_FAIL;
1555
0
    goto out;
1556
0
  }
1557
0
  if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS) {
1558
0
    r = SSH_ERR_INVALID_ARGUMENT;
1559
0
    goto out;
1560
0
  }
1561
0
  if (from->nprincipals > 0) {
1562
0
    if ((to->principals = calloc(from->nprincipals,
1563
0
        sizeof(*to->principals))) == NULL) {
1564
0
      r = SSH_ERR_ALLOC_FAIL;
1565
0
      goto out;
1566
0
    }
1567
0
    for (i = 0; i < from->nprincipals; i++) {
1568
0
      to->principals[i] = strdup(from->principals[i]);
1569
0
      if (to->principals[i] == NULL) {
1570
0
        to->nprincipals = i;
1571
0
        r = SSH_ERR_ALLOC_FAIL;
1572
0
        goto out;
1573
0
      }
1574
0
    }
1575
0
  }
1576
0
  to->nprincipals = from->nprincipals;
1577
1578
  /* success */
1579
0
  cert_free(to_key->cert);
1580
0
  to_key->cert = to;
1581
0
  to = NULL;
1582
0
  r = 0;
1583
0
 out:
1584
0
  cert_free(to);
1585
0
  return r;
1586
0
}
1587
1588
int
1589
sshkey_copy_public_sk(const struct sshkey *from, struct sshkey *to)
1590
0
{
1591
  /* Append security-key application string */
1592
0
  if ((to->sk_application = strdup(from->sk_application)) == NULL)
1593
0
    return SSH_ERR_ALLOC_FAIL;
1594
0
  return 0;
1595
0
}
1596
1597
int
1598
sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1599
0
{
1600
0
  struct sshkey *n = NULL;
1601
0
  int r = SSH_ERR_INTERNAL_ERROR;
1602
0
  const struct sshkey_impl *impl;
1603
1604
0
  *pkp = NULL;
1605
0
  if ((impl = sshkey_impl_from_key(k)) == NULL)
1606
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
1607
0
  if ((n = sshkey_new(k->type)) == NULL) {
1608
0
    r = SSH_ERR_ALLOC_FAIL;
1609
0
    goto out;
1610
0
  }
1611
0
  if ((r = impl->funcs->copy_public(k, n)) != 0)
1612
0
    goto out;
1613
0
  if (sshkey_is_cert(k) && (r = sshkey_cert_copy(k, n)) != 0)
1614
0
    goto out;
1615
  /* success */
1616
0
  *pkp = n;
1617
0
  n = NULL;
1618
0
  r = 0;
1619
0
 out:
1620
0
  sshkey_free(n);
1621
0
  return r;
1622
0
}
1623
1624
int
1625
sshkey_is_shielded(struct sshkey *k)
1626
0
{
1627
0
  return k != NULL && k->shielded_private != NULL;
1628
0
}
1629
1630
int
1631
sshkey_shield_private(struct sshkey *k)
1632
0
{
1633
0
  struct sshbuf *prvbuf = NULL;
1634
0
  u_char *prekey = NULL, *enc = NULL, keyiv[SSH_DIGEST_MAX_LENGTH];
1635
0
  struct sshcipher_ctx *cctx = NULL;
1636
0
  const struct sshcipher *cipher;
1637
0
  size_t i, enclen = 0;
1638
0
  struct sshkey *kswap = NULL, tmp;
1639
0
  int r = SSH_ERR_INTERNAL_ERROR;
1640
1641
#ifdef DEBUG_PK
1642
  fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
1643
#endif
1644
0
  if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
1645
0
    r = SSH_ERR_INVALID_ARGUMENT;
1646
0
    goto out;
1647
0
  }
1648
0
  if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
1649
0
      ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
1650
0
    r = SSH_ERR_INTERNAL_ERROR;
1651
0
    goto out;
1652
0
  }
1653
1654
  /* Prepare a random pre-key, and from it an ephemeral key */
1655
0
  if ((r = sshkey_prekey_alloc(&prekey, SSHKEY_SHIELD_PREKEY_LEN)) != 0)
1656
0
    goto out;
1657
0
  arc4random_buf(prekey, SSHKEY_SHIELD_PREKEY_LEN);
1658
0
  if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
1659
0
      prekey, SSHKEY_SHIELD_PREKEY_LEN,
1660
0
      keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
1661
0
    goto out;
1662
#ifdef DEBUG_PK
1663
  fprintf(stderr, "%s: key+iv\n", __func__);
1664
  sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
1665
      stderr);
1666
#endif
1667
0
  if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
1668
0
      keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0,
1669
0
      CIPHER_ENCRYPT, CIPHER_SERIAL)) != 0)
1670
0
    goto out;
1671
1672
  /* Serialise and encrypt the private key using the ephemeral key */
1673
0
  if ((prvbuf = sshbuf_new()) == NULL) {
1674
0
    r = SSH_ERR_ALLOC_FAIL;
1675
0
    goto out;
1676
0
  }
1677
0
  if (sshkey_is_shielded(k) && (r = sshkey_unshield_private(k)) != 0)
1678
0
    goto out;
1679
0
  if ((r = sshkey_private_serialize(k, prvbuf)) != 0)
1680
0
    goto out;
1681
  /* pad to cipher blocksize */
1682
0
  i = 0;
1683
0
  while (sshbuf_len(prvbuf) % cipher_blocksize(cipher)) {
1684
0
    if ((r = sshbuf_put_u8(prvbuf, ++i & 0xff)) != 0)
1685
0
      goto out;
1686
0
  }
1687
#ifdef DEBUG_PK
1688
  fprintf(stderr, "%s: serialised\n", __func__);
1689
  sshbuf_dump(prvbuf, stderr);
1690
#endif
1691
  /* encrypt */
1692
0
  enclen = sshbuf_len(prvbuf);
1693
0
  if ((enc = malloc(enclen)) == NULL) {
1694
0
    r = SSH_ERR_ALLOC_FAIL;
1695
0
    goto out;
1696
0
  }
1697
0
  if ((r = cipher_crypt(cctx, 0, enc, sshbuf_ptr(prvbuf),
1698
0
      sshbuf_len(prvbuf), 0, 0)) != 0)
1699
0
    goto out;
1700
#ifdef DEBUG_PK
1701
  fprintf(stderr, "%s: encrypted\n", __func__);
1702
  sshbuf_dump_data(enc, enclen, stderr);
1703
#endif
1704
1705
  /* Make a scrubbed, public-only copy of our private key argument */
1706
0
  if ((r = sshkey_from_private(k, &kswap)) != 0)
1707
0
    goto out;
1708
1709
  /* Swap the private key out (it will be destroyed below) */
1710
0
  tmp = *kswap;
1711
0
  *kswap = *k;
1712
0
  *k = tmp;
1713
1714
  /* Insert the shielded key into our argument */
1715
0
  k->shielded_private = enc;
1716
0
  k->shielded_len = enclen;
1717
0
  k->shield_prekey = prekey;
1718
0
  k->shield_prekey_len = SSHKEY_SHIELD_PREKEY_LEN;
1719
0
  enc = prekey = NULL; /* transferred */
1720
0
  enclen = 0;
1721
1722
  /* preserve key fields that are required for correct operation */
1723
0
  k->sk_flags = kswap->sk_flags;
1724
1725
  /* success */
1726
0
  r = 0;
1727
1728
0
 out:
1729
  /* XXX behaviour on error - invalidate original private key? */
1730
0
  cipher_free(cctx);
1731
0
  explicit_bzero(keyiv, sizeof(keyiv));
1732
0
  explicit_bzero(&tmp, sizeof(tmp));
1733
0
  freezero(enc, enclen);
1734
0
  sshkey_prekey_free(prekey, SSHKEY_SHIELD_PREKEY_LEN);
1735
0
  sshkey_free(kswap);
1736
0
  sshbuf_free(prvbuf);
1737
0
  return r;
1738
0
}
1739
1740
/* Check deterministic padding after private key */
1741
static int
1742
private2_check_padding(struct sshbuf *decrypted)
1743
0
{
1744
0
  u_char pad;
1745
0
  size_t i;
1746
0
  int r;
1747
1748
0
  i = 0;
1749
0
  while (sshbuf_len(decrypted)) {
1750
0
    if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
1751
0
      goto out;
1752
0
    if (pad != (++i & 0xff)) {
1753
0
      r = SSH_ERR_INVALID_FORMAT;
1754
0
      goto out;
1755
0
    }
1756
0
  }
1757
  /* success */
1758
0
  r = 0;
1759
0
 out:
1760
0
  explicit_bzero(&pad, sizeof(pad));
1761
0
  explicit_bzero(&i, sizeof(i));
1762
0
  return r;
1763
0
}
1764
1765
int
1766
sshkey_unshield_private(struct sshkey *k)
1767
0
{
1768
0
  struct sshbuf *prvbuf = NULL;
1769
0
  u_char *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
1770
0
  struct sshcipher_ctx *cctx = NULL;
1771
0
  const struct sshcipher *cipher;
1772
0
  struct sshkey *kswap = NULL, tmp;
1773
0
  int r = SSH_ERR_INTERNAL_ERROR;
1774
1775
#ifdef DEBUG_PK
1776
  fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
1777
#endif
1778
0
  if (!sshkey_is_shielded(k))
1779
0
    return 0; /* nothing to do */
1780
1781
0
  if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
1782
0
    r = SSH_ERR_INVALID_ARGUMENT;
1783
0
    goto out;
1784
0
  }
1785
0
  if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
1786
0
      ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
1787
0
    r = SSH_ERR_INTERNAL_ERROR;
1788
0
    goto out;
1789
0
  }
1790
  /* check size of shielded key blob */
1791
0
  if (k->shielded_len < cipher_blocksize(cipher) ||
1792
0
      (k->shielded_len % cipher_blocksize(cipher)) != 0) {
1793
0
    r = SSH_ERR_INVALID_FORMAT;
1794
0
    goto out;
1795
0
  }
1796
1797
  /* Calculate the ephemeral key from the prekey */
1798
0
  if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
1799
0
      k->shield_prekey, k->shield_prekey_len,
1800
0
      keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
1801
0
    goto out;
1802
0
  if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
1803
0
      keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0,
1804
0
      CIPHER_DECRYPT, CIPHER_SERIAL)) != 0)
1805
0
    goto out;
1806
#ifdef DEBUG_PK
1807
  fprintf(stderr, "%s: key+iv\n", __func__);
1808
  sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
1809
      stderr);
1810
#endif
1811
1812
  /* Decrypt and parse the shielded private key using the ephemeral key */
1813
0
  if ((prvbuf = sshbuf_new()) == NULL) {
1814
0
    r = SSH_ERR_ALLOC_FAIL;
1815
0
    goto out;
1816
0
  }
1817
0
  if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
1818
0
    goto out;
1819
  /* decrypt */
1820
#ifdef DEBUG_PK
1821
  fprintf(stderr, "%s: encrypted\n", __func__);
1822
  sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
1823
#endif
1824
0
  if ((r = cipher_crypt(cctx, 0, cp, k->shielded_private, k->shielded_len,
1825
0
      0, 0)) != 0)
1826
0
    goto out;
1827
#ifdef DEBUG_PK
1828
  fprintf(stderr, "%s: serialised\n", __func__);
1829
  sshbuf_dump(prvbuf, stderr);
1830
#endif
1831
  /* Parse private key */
1832
0
  if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
1833
0
    goto out;
1834
1835
0
  if ((r = private2_check_padding(prvbuf)) != 0)
1836
0
    goto out;
1837
1838
  /* Swap the parsed key back into place */
1839
0
  tmp = *kswap;
1840
0
  *kswap = *k;
1841
0
  *k = tmp;
1842
1843
  /* success */
1844
0
  r = 0;
1845
1846
0
 out:
1847
0
  cipher_free(cctx);
1848
0
  explicit_bzero(keyiv, sizeof(keyiv));
1849
0
  explicit_bzero(&tmp, sizeof(tmp));
1850
0
  sshkey_free(kswap);
1851
0
  sshbuf_free(prvbuf);
1852
0
  return r;
1853
0
}
1854
1855
static int
1856
cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf,
1857
    const char *ca_sigalg_allowlist)
1858
0
{
1859
0
  struct sshbuf *principals = NULL, *crit = NULL;
1860
0
  struct sshbuf *exts = NULL, *ca = NULL;
1861
0
  u_char *sig = NULL;
1862
0
  char *sigtype = NULL;
1863
0
  size_t signed_len = 0, slen = 0, kidlen = 0;
1864
0
  int ret = SSH_ERR_INTERNAL_ERROR;
1865
1866
  /* Copy the entire key blob for verification and later serialisation */
1867
0
  if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1868
0
    return ret;
1869
1870
  /* Parse body of certificate up to signature */
1871
0
  if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1872
0
      (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1873
0
      (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1874
0
      (ret = sshbuf_froms(b, &principals)) != 0 ||
1875
0
      (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1876
0
      (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1877
0
      (ret = sshbuf_froms(b, &crit)) != 0 ||
1878
0
      (ret = sshbuf_froms(b, &exts)) != 0 ||
1879
0
      (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1880
0
      (ret = sshbuf_froms(b, &ca)) != 0) {
1881
    /* XXX debug print error for ret */
1882
0
    ret = SSH_ERR_INVALID_FORMAT;
1883
0
    goto out;
1884
0
  }
1885
1886
  /* Signature is left in the buffer so we can calculate this length */
1887
0
  signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1888
1889
0
  if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1890
0
    ret = SSH_ERR_INVALID_FORMAT;
1891
0
    goto out;
1892
0
  }
1893
1894
  /* Is this a signature we're prepared to accept? */
1895
0
  if ((ret = sshkey_get_sigtype(sig, slen, &sigtype)) != 0) {
1896
0
    ret = SSH_ERR_INVALID_FORMAT;
1897
0
    goto out;
1898
0
  }
1899
0
  if (ca_sigalg_allowlist != NULL &&
1900
0
      match_pattern_list(sigtype, ca_sigalg_allowlist, 0) != 1) {
1901
0
    ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
1902
0
    goto out;
1903
0
  }
1904
1905
  /* Parse CA key and check whether we might accept it */
1906
0
  if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0,
1907
0
      ca_sigalg_allowlist, NULL) != 0) {
1908
0
    ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1909
0
    goto out;
1910
0
  }
1911
0
  if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1912
0
    ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1913
0
    goto out;
1914
0
  }
1915
1916
0
  if (key->cert->type != SSH2_CERT_TYPE_USER &&
1917
0
      key->cert->type != SSH2_CERT_TYPE_HOST) {
1918
0
    ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1919
0
    goto out;
1920
0
  }
1921
1922
  /* Parse principals section */
1923
0
  while (sshbuf_len(principals) > 0) {
1924
0
    char *principal = NULL;
1925
0
    char **oprincipals = NULL;
1926
1927
0
    if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1928
0
      ret = SSH_ERR_INVALID_FORMAT;
1929
0
      goto out;
1930
0
    }
1931
0
    if ((ret = sshbuf_get_cstring(principals, &principal,
1932
0
        NULL)) != 0) {
1933
0
      ret = SSH_ERR_INVALID_FORMAT;
1934
0
      goto out;
1935
0
    }
1936
0
    oprincipals = key->cert->principals;
1937
0
    key->cert->principals = recallocarray(key->cert->principals,
1938
0
        key->cert->nprincipals, key->cert->nprincipals + 1,
1939
0
        sizeof(*key->cert->principals));
1940
0
    if (key->cert->principals == NULL) {
1941
0
      free(principal);
1942
0
      key->cert->principals = oprincipals;
1943
0
      ret = SSH_ERR_ALLOC_FAIL;
1944
0
      goto out;
1945
0
    }
1946
0
    key->cert->principals[key->cert->nprincipals++] = principal;
1947
0
  }
1948
1949
  /*
1950
   * Stash a copies of the critical options and extensions sections
1951
   * for later use.
1952
   */
1953
0
  if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1954
0
      (exts != NULL &&
1955
0
      (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1956
0
    goto out;
1957
1958
  /*
1959
   * Validate critical options and extensions sections format.
1960
   */
1961
0
  while (sshbuf_len(crit) != 0) {
1962
0
    if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1963
0
        (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1964
0
      sshbuf_reset(key->cert->critical);
1965
0
      ret = SSH_ERR_INVALID_FORMAT;
1966
0
      goto out;
1967
0
    }
1968
0
  }
1969
0
  while (exts != NULL && sshbuf_len(exts) != 0) {
1970
0
    if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1971
0
        (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1972
0
      sshbuf_reset(key->cert->extensions);
1973
0
      ret = SSH_ERR_INVALID_FORMAT;
1974
0
      goto out;
1975
0
    }
1976
0
  }
1977
1978
  /* Finally, validate signature */
1979
0
  if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1980
0
      sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
1981
0
    goto out;
1982
1983
  /* Success */
1984
0
  ret = 0;
1985
0
  key->cert->signature_type = sigtype;
1986
0
  sigtype = NULL;
1987
0
 out:
1988
0
  sshbuf_free(ca);
1989
0
  sshbuf_free(crit);
1990
0
  sshbuf_free(exts);
1991
0
  sshbuf_free(principals);
1992
0
  free(sig);
1993
0
  free(sigtype);
1994
0
  return ret;
1995
0
}
1996
1997
int
1998
sshkey_deserialize_sk(struct sshbuf *b, struct sshkey *key)
1999
0
{
2000
  /* Parse additional security-key application string */
2001
0
  if (sshbuf_get_cstring(b, &key->sk_application, NULL) != 0)
2002
0
    return SSH_ERR_INVALID_FORMAT;
2003
0
  return 0;
2004
0
}
2005
2006
static int
2007
sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
2008
    int allow_cert, const char *alg_allowlist, const char *ca_sigalg_allowlist)
2009
0
{
2010
0
  int type, ret = SSH_ERR_INTERNAL_ERROR;
2011
0
  char *ktype = NULL;
2012
0
  struct sshkey *key = NULL;
2013
0
  struct sshbuf *copy;
2014
0
  const struct sshkey_impl *impl;
2015
2016
#ifdef DEBUG_PK /* XXX */
2017
  sshbuf_dump(b, stderr);
2018
#endif
2019
0
  if (keyp != NULL)
2020
0
    *keyp = NULL;
2021
0
  if ((copy = sshbuf_fromb(b)) == NULL) {
2022
0
    ret = SSH_ERR_ALLOC_FAIL;
2023
0
    goto out;
2024
0
  }
2025
0
  if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
2026
0
    ret = SSH_ERR_INVALID_FORMAT;
2027
0
    goto out;
2028
0
  }
2029
2030
0
  type = sshkey_type_from_name(ktype);
2031
0
  if (!allow_cert && sshkey_type_is_cert(type)) {
2032
0
    ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2033
0
    goto out;
2034
0
  }
2035
2036
0
  if (alg_allowlist != NULL &&
2037
0
      !sshkey_match_keyname_to_sigalgs(ktype, alg_allowlist)) {
2038
0
    ret = SSH_ERR_KEY_ALG_UNSUPPORTED;
2039
0
    goto out;
2040
0
  }
2041
2042
0
  if ((impl = sshkey_impl_from_type(type)) == NULL) {
2043
0
    ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2044
0
    goto out;
2045
0
  }
2046
0
  if ((key = sshkey_new(type)) == NULL) {
2047
0
    ret = SSH_ERR_ALLOC_FAIL;
2048
0
    goto out;
2049
0
  }
2050
0
  if (sshkey_type_is_cert(type)) {
2051
    /* Skip nonce that precedes all certificates */
2052
0
    if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2053
0
      ret = SSH_ERR_INVALID_FORMAT;
2054
0
      goto out;
2055
0
    }
2056
0
  }
2057
0
  if ((ret = impl->funcs->deserialize_public(ktype, b, key)) != 0)
2058
0
    goto out;
2059
2060
  /* Parse certificate potion */
2061
0
  if (sshkey_is_cert(key) &&
2062
0
      (ret = cert_parse(b, key, copy, ca_sigalg_allowlist)) != 0)
2063
0
    goto out;
2064
2065
0
  if (key != NULL && sshbuf_len(b) != 0) {
2066
0
    ret = SSH_ERR_INVALID_FORMAT;
2067
0
    goto out;
2068
0
  }
2069
0
  ret = 0;
2070
0
  if (keyp != NULL) {
2071
0
    *keyp = key;
2072
0
    key = NULL;
2073
0
  }
2074
0
 out:
2075
0
  sshbuf_free(copy);
2076
0
  sshkey_free(key);
2077
0
  free(ktype);
2078
0
  return ret;
2079
0
}
2080
2081
int
2082
sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2083
0
{
2084
0
  struct sshbuf *b;
2085
0
  int r;
2086
2087
0
  if ((b = sshbuf_from(blob, blen)) == NULL)
2088
0
    return SSH_ERR_ALLOC_FAIL;
2089
0
  r = sshkey_from_blob_internal(b, keyp, 1, NULL, NULL);
2090
0
  sshbuf_free(b);
2091
0
  return r;
2092
0
}
2093
2094
int
2095
sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2096
0
{
2097
0
  return sshkey_from_blob_internal(b, keyp, 1, NULL, NULL);
2098
0
}
2099
2100
int
2101
sshkey_fromb_allowlist(struct sshbuf *b, struct sshkey **keyp,
2102
    const char *alg_allowlist, const char *ca_sigalg_allowlist)
2103
0
{
2104
0
  return sshkey_from_blob_internal(b, keyp, 1,
2105
0
      alg_allowlist, ca_sigalg_allowlist);
2106
0
}
2107
2108
int
2109
sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2110
0
{
2111
0
  struct sshbuf *b;
2112
0
  int r;
2113
2114
0
  if ((r = sshbuf_froms(buf, &b)) != 0)
2115
0
    return r;
2116
0
  r = sshkey_from_blob_internal(b, keyp, 1, NULL, NULL);
2117
0
  sshbuf_free(b);
2118
0
  return r;
2119
0
}
2120
2121
int
2122
sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
2123
0
{
2124
0
  int r;
2125
0
  struct sshbuf *b = NULL;
2126
0
  char *sigtype = NULL;
2127
2128
0
  if (sigtypep != NULL)
2129
0
    *sigtypep = NULL;
2130
0
  if ((b = sshbuf_from(sig, siglen)) == NULL)
2131
0
    return SSH_ERR_ALLOC_FAIL;
2132
0
  if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2133
0
    goto out;
2134
  /* success */
2135
0
  if (sigtypep != NULL) {
2136
0
    *sigtypep = sigtype;
2137
0
    sigtype = NULL;
2138
0
  }
2139
0
  r = 0;
2140
0
 out:
2141
0
  free(sigtype);
2142
0
  sshbuf_free(b);
2143
0
  return r;
2144
0
}
2145
2146
/*
2147
 *
2148
 * Checks whether a certificate's signature type is allowed.
2149
 * Returns 0 (success) if the certificate signature type appears in the
2150
 * "allowed" pattern-list, or the key is not a certificate to begin with.
2151
 * Otherwise returns a ssherr.h code.
2152
 */
2153
int
2154
sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2155
0
{
2156
0
  if (key == NULL || allowed == NULL)
2157
0
    return SSH_ERR_INVALID_ARGUMENT;
2158
0
  if (!sshkey_type_is_cert(key->type))
2159
0
    return 0;
2160
0
  if (key->cert == NULL || key->cert->signature_type == NULL)
2161
0
    return SSH_ERR_INVALID_ARGUMENT;
2162
0
  if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2163
0
    return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2164
0
  return 0;
2165
0
}
2166
2167
/*
2168
 * Returns the expected signature algorithm for a given public key algorithm.
2169
 */
2170
const char *
2171
sshkey_sigalg_by_name(const char *name)
2172
0
{
2173
0
  const struct sshkey_impl *impl;
2174
0
  int i;
2175
2176
0
  for (i = 0; keyimpls[i] != NULL; i++) {
2177
0
    impl = keyimpls[i];
2178
0
    if (strcmp(impl->name, name) != 0)
2179
0
      continue;
2180
0
    if (impl->sigalg != NULL)
2181
0
      return impl->sigalg;
2182
0
    if (!impl->cert)
2183
0
      return impl->name;
2184
0
    return sshkey_ssh_name_from_type_nid(
2185
0
        sshkey_type_plain(impl->type), impl->nid);
2186
0
  }
2187
0
  return NULL;
2188
0
}
2189
2190
/*
2191
 * Verifies that the signature algorithm appearing inside the signature blob
2192
 * matches that which was requested.
2193
 */
2194
int
2195
sshkey_check_sigtype(const u_char *sig, size_t siglen,
2196
    const char *requested_alg)
2197
0
{
2198
0
  const char *expected_alg;
2199
0
  char *sigtype = NULL;
2200
0
  int r;
2201
2202
0
  if (requested_alg == NULL)
2203
0
    return 0;
2204
0
  if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2205
0
    return SSH_ERR_INVALID_ARGUMENT;
2206
0
  if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2207
0
    return r;
2208
0
  r = strcmp(expected_alg, sigtype) == 0;
2209
0
  free(sigtype);
2210
0
  return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2211
0
}
2212
2213
int
2214
sshkey_sign(struct sshkey *key,
2215
    u_char **sigp, size_t *lenp,
2216
    const u_char *data, size_t datalen,
2217
    const char *alg, const char *sk_provider, const char *sk_pin, u_int compat)
2218
0
{
2219
0
  int was_shielded = sshkey_is_shielded(key);
2220
0
  int r2, r = SSH_ERR_INTERNAL_ERROR;
2221
0
  const struct sshkey_impl *impl;
2222
2223
0
  if (sigp != NULL)
2224
0
    *sigp = NULL;
2225
0
  if (lenp != NULL)
2226
0
    *lenp = 0;
2227
0
  if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2228
0
    return SSH_ERR_INVALID_ARGUMENT;
2229
0
  if ((impl = sshkey_impl_from_key(key)) == NULL)
2230
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
2231
0
  if ((r = sshkey_unshield_private(key)) != 0)
2232
0
    return r;
2233
0
  if (sshkey_is_sk(key)) {
2234
0
    r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2235
0
        datalen, compat, sk_pin);
2236
0
  } else if ((key->flags & SSHKEY_FLAG_EXT) != 0) {
2237
0
    r = pkcs11_sign(key, sigp, lenp, data, datalen,
2238
0
        alg, sk_provider, sk_pin, compat);
2239
0
  } else {
2240
0
    if (impl->funcs->sign == NULL)
2241
0
      r = SSH_ERR_SIGN_ALG_UNSUPPORTED;
2242
0
    else {
2243
0
      r = impl->funcs->sign(key, sigp, lenp, data, datalen,
2244
0
          alg, sk_provider, sk_pin, compat);
2245
0
     }
2246
0
  }
2247
0
  if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2248
0
    return r2;
2249
0
  return r;
2250
0
}
2251
2252
/*
2253
 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2254
 * If "alg" specified, then the signature must use that algorithm.
2255
 */
2256
int
2257
sshkey_verify(const struct sshkey *key,
2258
    const u_char *sig, size_t siglen,
2259
    const u_char *data, size_t dlen, const char *alg, u_int compat,
2260
    struct sshkey_sig_details **detailsp)
2261
0
{
2262
0
  const struct sshkey_impl *impl;
2263
2264
0
  if (detailsp != NULL)
2265
0
    *detailsp = NULL;
2266
0
  if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2267
0
    return SSH_ERR_INVALID_ARGUMENT;
2268
0
  if ((impl = sshkey_impl_from_key(key)) == NULL)
2269
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
2270
0
  return impl->funcs->verify(key, sig, siglen, data, dlen,
2271
0
      alg, compat, detailsp);
2272
0
}
2273
2274
/* Convert a plain key to their _CERT equivalent */
2275
int
2276
sshkey_to_certified(struct sshkey *k)
2277
0
{
2278
0
  int newtype;
2279
2280
0
  if ((newtype = sshkey_type_certified(k->type)) == -1)
2281
0
    return SSH_ERR_INVALID_ARGUMENT;
2282
0
  if ((k->cert = cert_new()) == NULL)
2283
0
    return SSH_ERR_ALLOC_FAIL;
2284
0
  k->type = newtype;
2285
0
  return 0;
2286
0
}
2287
2288
/* Convert a certificate to its raw key equivalent */
2289
int
2290
sshkey_drop_cert(struct sshkey *k)
2291
0
{
2292
0
  if (!sshkey_type_is_cert(k->type))
2293
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
2294
0
  cert_free(k->cert);
2295
0
  k->cert = NULL;
2296
0
  k->type = sshkey_type_plain(k->type);
2297
0
  return 0;
2298
0
}
2299
2300
/* Sign a certified key, (re-)generating the signed certblob. */
2301
int
2302
sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2303
    const char *sk_provider, const char *sk_pin,
2304
    sshkey_certify_signer *signer, void *signer_ctx)
2305
0
{
2306
0
  const struct sshkey_impl *impl;
2307
0
  struct sshbuf *principals = NULL;
2308
0
  u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2309
0
  size_t i, ca_len, sig_len;
2310
0
  int ret = SSH_ERR_INTERNAL_ERROR;
2311
0
  struct sshbuf *cert = NULL;
2312
0
  char *sigtype = NULL;
2313
2314
0
  if (k == NULL || k->cert == NULL ||
2315
0
      k->cert->certblob == NULL || ca == NULL)
2316
0
    return SSH_ERR_INVALID_ARGUMENT;
2317
0
  if (!sshkey_is_cert(k))
2318
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
2319
0
  if (!sshkey_type_is_valid_ca(ca->type))
2320
0
    return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2321
0
  if ((impl = sshkey_impl_from_key(k)) == NULL)
2322
0
    return SSH_ERR_INTERNAL_ERROR;
2323
2324
  /*
2325
   * If no alg specified as argument but a signature_type was set,
2326
   * then prefer that. If both were specified, then they must match.
2327
   */
2328
0
  if (alg == NULL)
2329
0
    alg = k->cert->signature_type;
2330
0
  else if (k->cert->signature_type != NULL &&
2331
0
      strcmp(alg, k->cert->signature_type) != 0)
2332
0
    return SSH_ERR_INVALID_ARGUMENT;
2333
2334
  /*
2335
   * If no signing algorithm or signature_type was specified and we're
2336
   * using a RSA key, then default to a good signature algorithm.
2337
   */
2338
0
  if (alg == NULL && ca->type == KEY_RSA)
2339
0
    alg = "rsa-sha2-512";
2340
2341
0
  if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2342
0
    return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2343
2344
0
  cert = k->cert->certblob; /* for readability */
2345
0
  sshbuf_reset(cert);
2346
0
  if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2347
0
    goto out;
2348
2349
  /* -v01 certs put nonce first */
2350
0
  arc4random_buf(&nonce, sizeof(nonce));
2351
0
  if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2352
0
    goto out;
2353
2354
  /* Public key next */
2355
0
  if ((ret = impl->funcs->serialize_public(k, cert,
2356
0
      SSHKEY_SERIALIZE_DEFAULT)) != 0)
2357
0
    goto out;
2358
2359
  /* Then remaining cert fields */
2360
0
  if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2361
0
      (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2362
0
      (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2363
0
    goto out;
2364
2365
0
  if ((principals = sshbuf_new()) == NULL) {
2366
0
    ret = SSH_ERR_ALLOC_FAIL;
2367
0
    goto out;
2368
0
  }
2369
0
  for (i = 0; i < k->cert->nprincipals; i++) {
2370
0
    if ((ret = sshbuf_put_cstring(principals,
2371
0
        k->cert->principals[i])) != 0)
2372
0
      goto out;
2373
0
  }
2374
0
  if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2375
0
      (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2376
0
      (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2377
0
      (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2378
0
      (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2379
0
      (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2380
0
      (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2381
0
    goto out;
2382
2383
  /* Sign the whole mess */
2384
0
  if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2385
0
      sshbuf_len(cert), alg, sk_provider, sk_pin, 0, signer_ctx)) != 0)
2386
0
    goto out;
2387
  /* Check and update signature_type against what was actually used */
2388
0
  if ((ret = sshkey_get_sigtype(sig_blob, sig_len, &sigtype)) != 0)
2389
0
    goto out;
2390
0
  if (alg != NULL && strcmp(alg, sigtype) != 0) {
2391
0
    ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
2392
0
    goto out;
2393
0
  }
2394
0
  if (k->cert->signature_type == NULL) {
2395
0
    k->cert->signature_type = sigtype;
2396
0
    sigtype = NULL;
2397
0
  }
2398
  /* Append signature and we are done */
2399
0
  if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2400
0
    goto out;
2401
0
  ret = 0;
2402
0
 out:
2403
0
  if (ret != 0)
2404
0
    sshbuf_reset(cert);
2405
0
  free(sig_blob);
2406
0
  free(ca_blob);
2407
0
  free(sigtype);
2408
0
  sshbuf_free(principals);
2409
0
  return ret;
2410
0
}
2411
2412
static int
2413
default_key_sign(struct sshkey *key, u_char **sigp, size_t *lenp,
2414
    const u_char *data, size_t datalen,
2415
    const char *alg, const char *sk_provider, const char *sk_pin,
2416
    u_int compat, void *ctx)
2417
0
{
2418
0
  if (ctx != NULL)
2419
0
    return SSH_ERR_INVALID_ARGUMENT;
2420
0
  return sshkey_sign(key, sigp, lenp, data, datalen, alg,
2421
0
      sk_provider, sk_pin, compat);
2422
0
}
2423
2424
int
2425
sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg,
2426
    const char *sk_provider, const char *sk_pin)
2427
0
{
2428
0
  return sshkey_certify_custom(k, ca, alg, sk_provider, sk_pin,
2429
0
      default_key_sign, NULL);
2430
0
}
2431
2432
int
2433
sshkey_cert_check_authority(const struct sshkey *k,
2434
    int want_host, int wildcard_pattern, uint64_t verify_time,
2435
    const char *name, const char **reason)
2436
0
{
2437
0
  u_int i, principal_matches;
2438
2439
0
  if (reason == NULL)
2440
0
    return SSH_ERR_INVALID_ARGUMENT;
2441
0
  if (!sshkey_is_cert(k)) {
2442
0
    *reason = "Key is not a certificate";
2443
0
    return SSH_ERR_KEY_CERT_INVALID;
2444
0
  }
2445
0
  if (want_host) {
2446
0
    if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2447
0
      *reason = "Certificate invalid: not a host certificate";
2448
0
      return SSH_ERR_KEY_CERT_INVALID;
2449
0
    }
2450
0
  } else {
2451
0
    if (k->cert->type != SSH2_CERT_TYPE_USER) {
2452
0
      *reason = "Certificate invalid: not a user certificate";
2453
0
      return SSH_ERR_KEY_CERT_INVALID;
2454
0
    }
2455
0
  }
2456
0
  if (verify_time < k->cert->valid_after) {
2457
0
    *reason = "Certificate invalid: not yet valid";
2458
0
    return SSH_ERR_KEY_CERT_INVALID;
2459
0
  }
2460
0
  if (verify_time >= k->cert->valid_before) {
2461
0
    *reason = "Certificate invalid: expired";
2462
0
    return SSH_ERR_KEY_CERT_INVALID;
2463
0
  }
2464
0
  if (k->cert->nprincipals == 0) {
2465
0
    *reason = "Certificate lacks principal list";
2466
0
    return SSH_ERR_KEY_CERT_INVALID;
2467
0
  }
2468
0
  if (name == NULL)
2469
0
    return 0; /* principal matching not requested */
2470
2471
0
  principal_matches = 0;
2472
0
  for (i = 0; i < k->cert->nprincipals; i++) {
2473
0
    if (wildcard_pattern) {
2474
0
      if (match_pattern(name, k->cert->principals[i])) {
2475
0
        principal_matches = 1;
2476
0
        break;
2477
0
      }
2478
0
    } else if (strcmp(name, k->cert->principals[i]) == 0) {
2479
0
      principal_matches = 1;
2480
0
      break;
2481
0
    }
2482
0
  }
2483
0
  if (!principal_matches) {
2484
0
    *reason = "Certificate invalid: name is not a listed "
2485
0
        "principal";
2486
0
    return SSH_ERR_KEY_CERT_INVALID;
2487
0
  }
2488
0
  return 0;
2489
0
}
2490
2491
int
2492
sshkey_cert_check_authority_now(const struct sshkey *k,
2493
    int want_host, int wildcard_pattern, const char *name,
2494
    const char **reason)
2495
0
{
2496
0
  time_t now;
2497
2498
0
  if ((now = time(NULL)) < 0) {
2499
    /* yikes - system clock before epoch! */
2500
0
    *reason = "Certificate invalid: not yet valid";
2501
0
    return SSH_ERR_KEY_CERT_INVALID;
2502
0
  }
2503
0
  return sshkey_cert_check_authority(k, want_host, wildcard_pattern,
2504
0
      (uint64_t)now, name, reason);
2505
0
}
2506
2507
int
2508
sshkey_cert_check_host(const struct sshkey *key, const char *host,
2509
    const char *ca_sign_algorithms, const char **reason)
2510
0
{
2511
0
  int r;
2512
2513
0
  if ((r = sshkey_cert_check_authority_now(key, 1, 1, host, reason)) != 0)
2514
0
    return r;
2515
0
  if (sshbuf_len(key->cert->critical) != 0) {
2516
0
    *reason = "Certificate contains unsupported critical options";
2517
0
    return SSH_ERR_KEY_CERT_INVALID;
2518
0
  }
2519
0
  if (ca_sign_algorithms != NULL &&
2520
0
      (r = sshkey_check_cert_sigtype(key, ca_sign_algorithms)) != 0) {
2521
0
    *reason = "Certificate signed with disallowed algorithm";
2522
0
    return SSH_ERR_KEY_CERT_INVALID;
2523
0
  }
2524
0
  return 0;
2525
0
}
2526
2527
size_t
2528
sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2529
0
{
2530
0
  char from[32], to[32], ret[128];
2531
2532
0
  *from = *to = '\0';
2533
0
  if (cert->valid_after == 0 &&
2534
0
      cert->valid_before == 0xffffffffffffffffULL)
2535
0
    return strlcpy(s, "forever", l);
2536
2537
0
  if (cert->valid_after != 0)
2538
0
    format_absolute_time(cert->valid_after, from, sizeof(from));
2539
0
  if (cert->valid_before != 0xffffffffffffffffULL)
2540
0
    format_absolute_time(cert->valid_before, to, sizeof(to));
2541
2542
0
  if (cert->valid_after == 0)
2543
0
    snprintf(ret, sizeof(ret), "before %s", to);
2544
0
  else if (cert->valid_before == 0xffffffffffffffffULL)
2545
0
    snprintf(ret, sizeof(ret), "after %s", from);
2546
0
  else
2547
0
    snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2548
2549
0
  return strlcpy(s, ret, l);
2550
0
}
2551
2552
/* Common serialization for FIDO private keys */
2553
int
2554
sshkey_serialize_private_sk(const struct sshkey *key, struct sshbuf *b)
2555
0
{
2556
0
  int r;
2557
2558
0
  if ((r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
2559
0
      (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
2560
0
      (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
2561
0
      (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
2562
0
    return r;
2563
2564
0
  return 0;
2565
0
}
2566
2567
static int
2568
sshkey_private_serialize_opt(struct sshkey *key, struct sshbuf *buf,
2569
    enum sshkey_serialize_rep opts)
2570
0
{
2571
0
  int r = SSH_ERR_INTERNAL_ERROR;
2572
0
  int was_shielded = sshkey_is_shielded(key);
2573
0
  struct sshbuf *b = NULL;
2574
0
  const struct sshkey_impl *impl;
2575
2576
0
  if ((impl = sshkey_impl_from_key(key)) == NULL)
2577
0
    return SSH_ERR_INTERNAL_ERROR;
2578
0
  if ((r = sshkey_unshield_private(key)) != 0)
2579
0
    return r;
2580
0
  if ((b = sshbuf_new()) == NULL)
2581
0
    return SSH_ERR_ALLOC_FAIL;
2582
0
  if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2583
0
    goto out;
2584
0
  if (sshkey_is_cert(key)) {
2585
0
    if (key->cert == NULL ||
2586
0
        sshbuf_len(key->cert->certblob) == 0) {
2587
0
      r = SSH_ERR_INVALID_ARGUMENT;
2588
0
      goto out;
2589
0
    }
2590
0
    if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0)
2591
0
      goto out;
2592
0
  }
2593
0
  if ((r = impl->funcs->serialize_private(key, b, opts)) != 0)
2594
0
    goto out;
2595
2596
  /*
2597
   * success (but we still need to append the output to buf after
2598
   * possibly re-shielding the private key)
2599
   */
2600
0
  r = 0;
2601
0
 out:
2602
0
  if (was_shielded)
2603
0
    r = sshkey_shield_private(key);
2604
0
  if (r == 0)
2605
0
    r = sshbuf_putb(buf, b);
2606
0
  sshbuf_free(b);
2607
2608
0
  return r;
2609
0
}
2610
2611
int
2612
sshkey_private_serialize(struct sshkey *key, struct sshbuf *b)
2613
0
{
2614
0
  return sshkey_private_serialize_opt(key, b,
2615
0
      SSHKEY_SERIALIZE_DEFAULT);
2616
0
}
2617
2618
2619
/* Shared deserialization of FIDO private key components */
2620
int
2621
sshkey_private_deserialize_sk(struct sshbuf *buf, struct sshkey *k)
2622
0
{
2623
0
  int r;
2624
2625
0
  if ((k->sk_key_handle = sshbuf_new()) == NULL ||
2626
0
      (k->sk_reserved = sshbuf_new()) == NULL)
2627
0
    return SSH_ERR_ALLOC_FAIL;
2628
0
  if ((r = sshbuf_get_cstring(buf, &k->sk_application, NULL)) != 0 ||
2629
0
      (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
2630
0
      (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
2631
0
      (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
2632
0
    return r;
2633
2634
0
  return 0;
2635
0
}
2636
2637
int
2638
sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2639
0
{
2640
0
  const struct sshkey_impl *impl;
2641
0
  char *tname = NULL;
2642
0
  char *expect_sk_application = NULL;
2643
0
  u_char *expect_ed25519_pk = NULL;
2644
0
  struct sshkey *k = NULL;
2645
0
  int type, r = SSH_ERR_INTERNAL_ERROR;
2646
2647
0
  if (kp != NULL)
2648
0
    *kp = NULL;
2649
0
  if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2650
0
    goto out;
2651
0
  type = sshkey_type_from_name(tname);
2652
0
  if (sshkey_type_is_cert(type)) {
2653
    /*
2654
     * Certificate key private keys begin with the certificate
2655
     * itself. Make sure this matches the type of the enclosing
2656
     * private key.
2657
     */
2658
0
    if ((r = sshkey_froms(buf, &k)) != 0)
2659
0
      goto out;
2660
0
    if (k->type != type) {
2661
0
      r = SSH_ERR_KEY_CERT_MISMATCH;
2662
0
      goto out;
2663
0
    }
2664
    /* For ECDSA keys, the group must match too */
2665
0
    if (k->type == KEY_ECDSA &&
2666
0
        k->ecdsa_nid != sshkey_ecdsa_nid_from_name(tname)) {
2667
0
      r = SSH_ERR_KEY_CERT_MISMATCH;
2668
0
      goto out;
2669
0
    }
2670
    /*
2671
     * Several fields are redundant between certificate and
2672
     * private key body, we require these to match.
2673
     */
2674
0
    expect_sk_application = k->sk_application;
2675
0
    expect_ed25519_pk = k->ed25519_pk;
2676
0
    k->sk_application = NULL;
2677
0
    k->ed25519_pk = NULL;
2678
0
  } else {
2679
0
    if ((k = sshkey_new(type)) == NULL) {
2680
0
      r = SSH_ERR_ALLOC_FAIL;
2681
0
      goto out;
2682
0
    }
2683
0
  }
2684
0
  if ((impl = sshkey_impl_from_type(type)) == NULL) {
2685
0
    r = SSH_ERR_INTERNAL_ERROR;
2686
0
    goto out;
2687
0
  }
2688
0
  if ((r = impl->funcs->deserialize_private(tname, buf, k)) != 0)
2689
0
    goto out;
2690
2691
0
  if ((expect_sk_application != NULL && (k->sk_application == NULL ||
2692
0
      strcmp(expect_sk_application, k->sk_application) != 0)) ||
2693
0
      (expect_ed25519_pk != NULL && (k->ed25519_pk == NULL ||
2694
0
      memcmp(expect_ed25519_pk, k->ed25519_pk, ED25519_PK_SZ) != 0))) {
2695
0
    r = SSH_ERR_KEY_CERT_MISMATCH;
2696
0
    goto out;
2697
0
  }
2698
  /* success */
2699
0
  r = 0;
2700
0
  if (kp != NULL) {
2701
0
    *kp = k;
2702
0
    k = NULL;
2703
0
  }
2704
0
 out:
2705
0
  free(tname);
2706
0
  sshkey_free(k);
2707
0
  free(expect_sk_application);
2708
0
  free(expect_ed25519_pk);
2709
0
  return r;
2710
0
}
2711
2712
#ifdef WITH_OPENSSL
2713
int
2714
sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2715
0
{
2716
0
  EC_POINT *nq = NULL;
2717
0
  BIGNUM *order = NULL, *cofactor = NULL;
2718
0
  int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2719
2720
  /*
2721
   * NB. This assumes OpenSSL has already verified that the public
2722
   * point lies on the curve and that its coordinates are in [0, p).
2723
   * This is done by EC_POINT_oct2point() on at least OpenSSL >= 1.1,
2724
   * LibreSSL and BoringSSL.
2725
   */
2726
2727
  /* Q != infinity */
2728
0
  if (EC_POINT_is_at_infinity(group, public))
2729
0
    goto out;
2730
2731
0
  if ((cofactor = BN_new()) == NULL) {
2732
0
    ret = SSH_ERR_ALLOC_FAIL;
2733
0
    goto out;
2734
0
  }
2735
0
  if (EC_GROUP_get_cofactor(group, cofactor, NULL) != 1)
2736
0
    goto out;
2737
2738
  /*
2739
   * Verify nQ == infinity (n == order of subgroup)
2740
   * This check may be skipped for curves with cofactor 1, as per
2741
   * NIST SP 800-56A, 5.6.2.3.
2742
   */
2743
0
  if (!BN_is_one(cofactor)) {
2744
0
    if ((order = BN_new()) == NULL) {
2745
0
      ret = SSH_ERR_ALLOC_FAIL;
2746
0
      goto out;
2747
0
    }
2748
0
    if (EC_GROUP_get_order(group, order, NULL) != 1) {
2749
0
      ret = SSH_ERR_LIBCRYPTO_ERROR;
2750
0
      goto out;
2751
0
    }
2752
0
    if ((nq = EC_POINT_new(group)) == NULL) {
2753
0
      ret = SSH_ERR_ALLOC_FAIL;
2754
0
      goto out;
2755
0
    }
2756
0
    if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
2757
0
      ret = SSH_ERR_LIBCRYPTO_ERROR;
2758
0
      goto out;
2759
0
    }
2760
0
    if (EC_POINT_is_at_infinity(group, nq) != 1)
2761
0
      goto out;
2762
0
  }
2763
2764
  /* success */
2765
0
  ret = 0;
2766
0
 out:
2767
0
  BN_clear_free(cofactor);
2768
0
  BN_clear_free(order);
2769
0
  EC_POINT_free(nq);
2770
0
  return ret;
2771
0
}
2772
2773
int
2774
sshkey_ec_validate_private(const EC_KEY *key)
2775
0
{
2776
0
  BIGNUM *order = NULL, *tmp = NULL;
2777
0
  int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2778
2779
0
  if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
2780
0
    ret = SSH_ERR_ALLOC_FAIL;
2781
0
    goto out;
2782
0
  }
2783
2784
  /* log2(private) > log2(order)/2 */
2785
0
  if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
2786
0
    ret = SSH_ERR_LIBCRYPTO_ERROR;
2787
0
    goto out;
2788
0
  }
2789
0
  if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2790
0
      BN_num_bits(order) / 2)
2791
0
    goto out;
2792
2793
  /* private < order - 1 */
2794
0
  if (!BN_sub(tmp, order, BN_value_one())) {
2795
0
    ret = SSH_ERR_LIBCRYPTO_ERROR;
2796
0
    goto out;
2797
0
  }
2798
0
  if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2799
0
    goto out;
2800
0
  ret = 0;
2801
0
 out:
2802
0
  BN_clear_free(order);
2803
0
  BN_clear_free(tmp);
2804
0
  return ret;
2805
0
}
2806
2807
void
2808
sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2809
0
{
2810
0
  BIGNUM *x = NULL, *y = NULL;
2811
2812
0
  if (point == NULL) {
2813
0
    fputs("point=(NULL)\n", stderr);
2814
0
    return;
2815
0
  }
2816
0
  if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
2817
0
    fprintf(stderr, "%s: BN_new failed\n", __func__);
2818
0
    goto out;
2819
0
  }
2820
0
  if (EC_POINT_get_affine_coordinates(group, point, x, y, NULL) != 1) {
2821
0
    fprintf(stderr, "%s: EC_POINT_get_affine_coordinates\n",
2822
0
        __func__);
2823
0
    goto out;
2824
0
  }
2825
0
  fputs("x=", stderr);
2826
0
  BN_print_fp(stderr, x);
2827
0
  fputs("\ny=", stderr);
2828
0
  BN_print_fp(stderr, y);
2829
0
  fputs("\n", stderr);
2830
0
 out:
2831
0
  BN_clear_free(x);
2832
0
  BN_clear_free(y);
2833
0
}
2834
2835
void
2836
sshkey_dump_ec_key(const EC_KEY *key)
2837
0
{
2838
0
  const BIGNUM *exponent;
2839
2840
0
  sshkey_dump_ec_point(EC_KEY_get0_group(key),
2841
0
      EC_KEY_get0_public_key(key));
2842
0
  fputs("exponent=", stderr);
2843
0
  if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2844
0
    fputs("(NULL)", stderr);
2845
0
  else
2846
0
    BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2847
0
  fputs("\n", stderr);
2848
0
}
2849
#endif /* WITH_OPENSSL */
2850
2851
static int
2852
sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
2853
    const char *passphrase, const char *comment, const char *ciphername,
2854
    int rounds)
2855
0
{
2856
0
  u_char *cp, *key = NULL, *pubkeyblob = NULL;
2857
0
  u_char salt[SALT_LEN];
2858
0
  size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2859
0
  u_int check;
2860
0
  int r = SSH_ERR_INTERNAL_ERROR;
2861
0
  struct sshcipher_ctx *ciphercontext = NULL;
2862
0
  const struct sshcipher *cipher;
2863
0
  const char *kdfname = KDFNAME;
2864
0
  struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2865
2866
0
  if (rounds <= 0)
2867
0
    rounds = DEFAULT_ROUNDS;
2868
0
  if (rounds > MAX_KDF_ROUNDS) {
2869
0
    r = SSH_ERR_INVALID_ARGUMENT;
2870
0
    goto out;
2871
0
  }
2872
0
  if (passphrase == NULL || !strlen(passphrase)) {
2873
0
    ciphername = "none";
2874
0
    kdfname = "none";
2875
0
  } else if (ciphername == NULL)
2876
0
    ciphername = DEFAULT_CIPHERNAME;
2877
  /*
2878
   * NOTE: Without OpenSSL, this string comparison is still safe, even
2879
   * though it will never match because the multithreaded cipher is not
2880
   * enabled.
2881
   */
2882
0
  else if (strcmp(ciphername, "chacha20-poly1305-mt@hpnssh.org") == 0)
2883
0
    ciphername = "chacha20-poly1305@openssh.com";
2884
0
  if ((cipher = cipher_by_name(ciphername)) == NULL) {
2885
0
    r = SSH_ERR_INVALID_ARGUMENT;
2886
0
    goto out;
2887
0
  }
2888
2889
0
  if ((kdf = sshbuf_new()) == NULL ||
2890
0
      (encoded = sshbuf_new()) == NULL ||
2891
0
      (encrypted = sshbuf_new()) == NULL) {
2892
0
    r = SSH_ERR_ALLOC_FAIL;
2893
0
    goto out;
2894
0
  }
2895
0
  blocksize = cipher_blocksize(cipher);
2896
0
  keylen = cipher_keylen(cipher);
2897
0
  ivlen = cipher_ivlen(cipher);
2898
0
  authlen = cipher_authlen(cipher);
2899
0
  if ((key = calloc(1, keylen + ivlen)) == NULL) {
2900
0
    r = SSH_ERR_ALLOC_FAIL;
2901
0
    goto out;
2902
0
  }
2903
0
  if (strcmp(kdfname, "bcrypt") == 0) {
2904
0
    arc4random_buf(salt, SALT_LEN);
2905
0
    if (bcrypt_pbkdf(passphrase, strlen(passphrase),
2906
0
        salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
2907
0
      r = SSH_ERR_INVALID_ARGUMENT;
2908
0
      goto out;
2909
0
    }
2910
0
    if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
2911
0
        (r = sshbuf_put_u32(kdf, rounds)) != 0)
2912
0
      goto out;
2913
0
  } else if (strcmp(kdfname, "none") != 0) {
2914
    /* Unsupported KDF type */
2915
0
    r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2916
0
    goto out;
2917
0
  }
2918
0
  if ((r = cipher_init(&ciphercontext, cipher, key, keylen, key + keylen,
2919
0
      ivlen, 0, CIPHER_ENCRYPT, CIPHER_SERIAL)) != 0)
2920
0
    goto out;
2921
2922
0
  if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
2923
0
      (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
2924
0
      (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
2925
0
      (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
2926
0
      (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
2927
0
      (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
2928
0
      (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
2929
0
    goto out;
2930
2931
  /* set up the buffer that will be encrypted */
2932
2933
  /* Random check bytes */
2934
0
  check = arc4random();
2935
0
  if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
2936
0
      (r = sshbuf_put_u32(encrypted, check)) != 0)
2937
0
    goto out;
2938
2939
  /* append private key and comment*/
2940
0
  if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
2941
0
      (r = sshbuf_put_cstring(encrypted, comment)) != 0)
2942
0
    goto out;
2943
2944
  /* padding */
2945
0
  i = 0;
2946
0
  while (sshbuf_len(encrypted) % blocksize) {
2947
0
    if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
2948
0
      goto out;
2949
0
  }
2950
2951
  /* length in destination buffer */
2952
0
  if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
2953
0
    goto out;
2954
2955
  /* encrypt */
2956
0
  if ((r = sshbuf_reserve(encoded,
2957
0
      sshbuf_len(encrypted) + authlen, &cp)) != 0)
2958
0
    goto out;
2959
0
  if ((r = cipher_crypt(ciphercontext, 0, cp, sshbuf_ptr(encrypted),
2960
0
      sshbuf_len(encrypted), 0, authlen)) != 0)
2961
0
    goto out;
2962
2963
0
  sshbuf_reset(blob);
2964
2965
  /* assemble uuencoded key */
2966
0
  if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
2967
0
      (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
2968
0
      (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
2969
0
    goto out;
2970
2971
  /* success */
2972
0
  r = 0;
2973
2974
0
 out:
2975
0
  sshbuf_free(kdf);
2976
0
  sshbuf_free(encoded);
2977
0
  sshbuf_free(encrypted);
2978
0
  cipher_free(ciphercontext);
2979
0
  explicit_bzero(salt, sizeof(salt));
2980
0
  if (key != NULL)
2981
0
    freezero(key, keylen + ivlen);
2982
0
  if (pubkeyblob != NULL)
2983
0
    freezero(pubkeyblob, pubkeylen);
2984
0
  return r;
2985
0
}
2986
2987
static int
2988
private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
2989
0
{
2990
0
  const u_char *cp;
2991
0
  size_t encoded_len;
2992
0
  int r;
2993
0
  u_char last;
2994
0
  struct sshbuf *encoded = NULL, *decoded = NULL;
2995
2996
0
  if (blob == NULL || decodedp == NULL)
2997
0
    return SSH_ERR_INVALID_ARGUMENT;
2998
2999
0
  *decodedp = NULL;
3000
3001
0
  if ((encoded = sshbuf_new()) == NULL ||
3002
0
      (decoded = sshbuf_new()) == NULL) {
3003
0
    r = SSH_ERR_ALLOC_FAIL;
3004
0
    goto out;
3005
0
  }
3006
3007
  /* check preamble */
3008
0
  cp = sshbuf_ptr(blob);
3009
0
  encoded_len = sshbuf_len(blob);
3010
0
  if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3011
0
      memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3012
0
    r = SSH_ERR_INVALID_FORMAT;
3013
0
    goto out;
3014
0
  }
3015
0
  cp += MARK_BEGIN_LEN;
3016
0
  encoded_len -= MARK_BEGIN_LEN;
3017
3018
  /* Look for end marker, removing whitespace as we go */
3019
0
  while (encoded_len > 0) {
3020
0
    if (*cp != '\n' && *cp != '\r') {
3021
0
      if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3022
0
        goto out;
3023
0
    }
3024
0
    last = *cp;
3025
0
    encoded_len--;
3026
0
    cp++;
3027
0
    if (last == '\n') {
3028
0
      if (encoded_len >= MARK_END_LEN &&
3029
0
          memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3030
        /* \0 terminate */
3031
0
        if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3032
0
          goto out;
3033
0
        break;
3034
0
      }
3035
0
    }
3036
0
  }
3037
0
  if (encoded_len == 0) {
3038
0
    r = SSH_ERR_INVALID_FORMAT;
3039
0
    goto out;
3040
0
  }
3041
3042
  /* decode base64 */
3043
0
  if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3044
0
    goto out;
3045
3046
  /* check magic */
3047
0
  if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3048
0
      memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3049
0
    r = SSH_ERR_INVALID_FORMAT;
3050
0
    goto out;
3051
0
  }
3052
  /* success */
3053
0
  *decodedp = decoded;
3054
0
  decoded = NULL;
3055
0
  r = 0;
3056
0
 out:
3057
0
  sshbuf_free(encoded);
3058
0
  sshbuf_free(decoded);
3059
0
  return r;
3060
0
}
3061
3062
static int
3063
private2_decrypt(struct sshbuf *decoded, const char *passphrase,
3064
    struct sshbuf **decryptedp, struct sshkey **pubkeyp)
3065
0
{
3066
0
  char *ciphername = NULL, *kdfname = NULL;
3067
0
  const struct sshcipher *cipher = NULL;
3068
0
  int r = SSH_ERR_INTERNAL_ERROR;
3069
0
  size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3070
0
  struct sshbuf *kdf = NULL, *decrypted = NULL;
3071
0
  struct sshcipher_ctx *ciphercontext = NULL;
3072
0
  struct sshkey *pubkey = NULL;
3073
0
  u_char *key = NULL, *salt = NULL, *dp;
3074
0
  u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3075
3076
0
  if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
3077
0
    return SSH_ERR_INVALID_ARGUMENT;
3078
3079
0
  *decryptedp = NULL;
3080
0
  *pubkeyp = NULL;
3081
3082
0
  if ((decrypted = sshbuf_new()) == NULL) {
3083
0
    r = SSH_ERR_ALLOC_FAIL;
3084
0
    goto out;
3085
0
  }
3086
3087
  /* parse public portion of key */
3088
0
  if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3089
0
      (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3090
0
      (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3091
0
      (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3092
0
      (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
3093
0
    goto out;
3094
3095
0
  if (nkeys != 1) {
3096
    /* XXX only one key supported at present */
3097
0
    r = SSH_ERR_INVALID_FORMAT;
3098
0
    goto out;
3099
0
  }
3100
3101
0
  if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
3102
0
      (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3103
0
    goto out;
3104
3105
0
  if (strcmp(ciphername, "chacha20-poly1305-mt@hpnssh.org") == 0)
3106
0
    strcpy(ciphername, "chacha20-poly1305@openssh.com");
3107
0
  if ((cipher = cipher_by_name(ciphername)) == NULL) {
3108
0
    r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3109
0
    goto out;
3110
0
  }
3111
0
  if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3112
0
    r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3113
0
    goto out;
3114
0
  }
3115
0
  if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
3116
0
    r = SSH_ERR_INVALID_FORMAT;
3117
0
    goto out;
3118
0
  }
3119
0
  if ((passphrase == NULL || strlen(passphrase) == 0) &&
3120
0
      strcmp(kdfname, "none") != 0) {
3121
    /* passphrase required */
3122
0
    r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3123
0
    goto out;
3124
0
  }
3125
3126
  /* check size of encrypted key blob */
3127
0
  blocksize = cipher_blocksize(cipher);
3128
0
  if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3129
0
    r = SSH_ERR_INVALID_FORMAT;
3130
0
    goto out;
3131
0
  }
3132
3133
  /* setup key */
3134
0
  keylen = cipher_keylen(cipher);
3135
0
  ivlen = cipher_ivlen(cipher);
3136
0
  authlen = cipher_authlen(cipher);
3137
0
  if ((key = calloc(1, keylen + ivlen)) == NULL) {
3138
0
    r = SSH_ERR_ALLOC_FAIL;
3139
0
    goto out;
3140
0
  }
3141
0
  if (strcmp(kdfname, "bcrypt") == 0) {
3142
0
    if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3143
0
        (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3144
0
      goto out;
3145
0
    if (rounds > MAX_KDF_ROUNDS) {
3146
0
      r = SSH_ERR_INVALID_FORMAT;
3147
0
      goto out;
3148
0
    }
3149
0
    if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3150
0
        key, keylen + ivlen, rounds) < 0) {
3151
0
      r = SSH_ERR_INVALID_FORMAT;
3152
0
      goto out;
3153
0
    }
3154
0
  }
3155
3156
  /* check that an appropriate amount of auth data is present */
3157
0
  if (sshbuf_len(decoded) < authlen ||
3158
0
      sshbuf_len(decoded) - authlen < encrypted_len) {
3159
0
    r = SSH_ERR_INVALID_FORMAT;
3160
0
    goto out;
3161
0
  }
3162
3163
  /* decrypt private portion of key */
3164
0
  if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3165
0
      (r = cipher_init(&ciphercontext, cipher, key, keylen, key + keylen,
3166
0
      ivlen, 0, CIPHER_DECRYPT, CIPHER_SERIAL)) != 0)
3167
0
    goto out;
3168
0
  if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3169
0
      encrypted_len, 0, authlen)) != 0) {
3170
    /* an integrity error here indicates an incorrect passphrase */
3171
0
    if (r == SSH_ERR_MAC_INVALID)
3172
0
      r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3173
0
    goto out;
3174
0
  }
3175
0
  if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3176
0
    goto out;
3177
  /* there should be no trailing data */
3178
0
  if (sshbuf_len(decoded) != 0) {
3179
0
    r = SSH_ERR_INVALID_FORMAT;
3180
0
    goto out;
3181
0
  }
3182
3183
  /* check check bytes */
3184
0
  if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3185
0
      (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3186
0
    goto out;
3187
0
  if (check1 != check2) {
3188
0
    r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3189
0
    goto out;
3190
0
  }
3191
  /* success */
3192
0
  *decryptedp = decrypted;
3193
0
  decrypted = NULL;
3194
0
  *pubkeyp = pubkey;
3195
0
  pubkey = NULL;
3196
0
  r = 0;
3197
0
 out:
3198
0
  cipher_free(ciphercontext);
3199
0
  free(ciphername);
3200
0
  free(kdfname);
3201
0
  sshkey_free(pubkey);
3202
0
  if (salt != NULL) {
3203
0
    explicit_bzero(salt, slen);
3204
0
    free(salt);
3205
0
  }
3206
0
  if (key != NULL) {
3207
0
    explicit_bzero(key, keylen + ivlen);
3208
0
    free(key);
3209
0
  }
3210
0
  sshbuf_free(kdf);
3211
0
  sshbuf_free(decrypted);
3212
0
  return r;
3213
0
}
3214
3215
static int
3216
sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3217
    struct sshkey **keyp, char **commentp)
3218
0
{
3219
0
  char *comment = NULL;
3220
0
  int r = SSH_ERR_INTERNAL_ERROR;
3221
0
  struct sshbuf *decoded = NULL, *decrypted = NULL;
3222
0
  struct sshkey *k = NULL, *pubkey = NULL;
3223
3224
0
  if (keyp != NULL)
3225
0
    *keyp = NULL;
3226
0
  if (commentp != NULL)
3227
0
    *commentp = NULL;
3228
3229
  /* Undo base64 encoding and decrypt the private section */
3230
0
  if ((r = private2_uudecode(blob, &decoded)) != 0 ||
3231
0
      (r = private2_decrypt(decoded, passphrase,
3232
0
      &decrypted, &pubkey)) != 0)
3233
0
    goto out;
3234
3235
0
  if (type != KEY_UNSPEC &&
3236
0
      sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3237
0
    r = SSH_ERR_KEY_TYPE_MISMATCH;
3238
0
    goto out;
3239
0
  }
3240
3241
  /* Load the private key and comment */
3242
0
  if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3243
0
      (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3244
0
    goto out;
3245
3246
  /* Check deterministic padding after private section */
3247
0
  if ((r = private2_check_padding(decrypted)) != 0)
3248
0
    goto out;
3249
3250
  /* Check that the public key in the envelope matches the private key */
3251
0
  if (!sshkey_equal(pubkey, k)) {
3252
0
    r = SSH_ERR_INVALID_FORMAT;
3253
0
    goto out;
3254
0
  }
3255
3256
  /* success */
3257
0
  r = 0;
3258
0
  if (keyp != NULL) {
3259
0
    *keyp = k;
3260
0
    k = NULL;
3261
0
  }
3262
0
  if (commentp != NULL) {
3263
0
    *commentp = comment;
3264
0
    comment = NULL;
3265
0
  }
3266
0
 out:
3267
0
  free(comment);
3268
0
  sshbuf_free(decoded);
3269
0
  sshbuf_free(decrypted);
3270
0
  sshkey_free(k);
3271
0
  sshkey_free(pubkey);
3272
0
  return r;
3273
0
}
3274
3275
static int
3276
sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
3277
    struct sshkey **keyp)
3278
0
{
3279
0
  int r = SSH_ERR_INTERNAL_ERROR;
3280
0
  struct sshbuf *decoded = NULL;
3281
0
  struct sshkey *pubkey = NULL;
3282
0
  u_int nkeys = 0;
3283
3284
0
  if (keyp != NULL)
3285
0
    *keyp = NULL;
3286
3287
0
  if ((r = private2_uudecode(blob, &decoded)) != 0)
3288
0
    goto out;
3289
  /* parse public key from unencrypted envelope */
3290
0
  if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3291
0
      (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
3292
0
      (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
3293
0
      (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
3294
0
      (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
3295
0
    goto out;
3296
3297
0
  if (nkeys != 1) {
3298
    /* XXX only one key supported at present */
3299
0
    r = SSH_ERR_INVALID_FORMAT;
3300
0
    goto out;
3301
0
  }
3302
3303
  /* Parse the public key */
3304
0
  if ((r = sshkey_froms(decoded, &pubkey)) != 0)
3305
0
    goto out;
3306
3307
0
  if (type != KEY_UNSPEC &&
3308
0
      sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3309
0
    r = SSH_ERR_KEY_TYPE_MISMATCH;
3310
0
    goto out;
3311
0
  }
3312
3313
  /* success */
3314
0
  r = 0;
3315
0
  if (keyp != NULL) {
3316
0
    *keyp = pubkey;
3317
0
    pubkey = NULL;
3318
0
  }
3319
0
 out:
3320
0
  sshbuf_free(decoded);
3321
0
  sshkey_free(pubkey);
3322
0
  return r;
3323
0
}
3324
3325
#ifdef WITH_OPENSSL
3326
/* convert SSH v2 key to PEM or PKCS#8 format */
3327
static int
3328
sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
3329
    int format, const char *_passphrase, const char *comment)
3330
0
{
3331
0
  int was_shielded = sshkey_is_shielded(key);
3332
0
  int success, r;
3333
0
  int blen, len = strlen(_passphrase);
3334
0
  u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3335
0
  const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3336
0
  char *bptr;
3337
0
  BIO *bio = NULL;
3338
0
  struct sshbuf *blob;
3339
0
  EVP_PKEY *pkey = NULL;
3340
3341
0
  if (len > 0 && len <= 4)
3342
0
    return SSH_ERR_PASSPHRASE_TOO_SHORT;
3343
0
  if ((blob = sshbuf_new()) == NULL)
3344
0
    return SSH_ERR_ALLOC_FAIL;
3345
0
  if ((bio = BIO_new(BIO_s_mem())) == NULL) {
3346
0
    r = SSH_ERR_ALLOC_FAIL;
3347
0
    goto out;
3348
0
  }
3349
0
  if ((r = sshkey_unshield_private(key)) != 0)
3350
0
    goto out;
3351
3352
0
  switch (key->type) {
3353
0
  case KEY_ECDSA:
3354
0
    if (format == SSHKEY_PRIVATE_PEM) {
3355
0
      success = PEM_write_bio_ECPrivateKey(bio,
3356
0
          EVP_PKEY_get0_EC_KEY(key->pkey),
3357
0
          cipher, passphrase, len, NULL, NULL);
3358
0
    } else {
3359
0
      pkey = key->pkey;
3360
0
      EVP_PKEY_up_ref(key->pkey);
3361
0
      success = 1;
3362
0
    }
3363
0
    break;
3364
0
  case KEY_RSA:
3365
0
    if (format == SSHKEY_PRIVATE_PEM) {
3366
0
      success = PEM_write_bio_RSAPrivateKey(bio,
3367
0
          EVP_PKEY_get0_RSA(key->pkey),
3368
0
          cipher, passphrase, len, NULL, NULL);
3369
0
    } else {
3370
0
      pkey = key->pkey;
3371
0
      EVP_PKEY_up_ref(key->pkey);
3372
0
      success = 1;
3373
0
    }
3374
0
    break;
3375
0
#ifdef OPENSSL_HAS_ED25519
3376
0
  case KEY_ED25519:
3377
0
    if (format == SSHKEY_PRIVATE_PEM) {
3378
0
      r = SSH_ERR_INVALID_FORMAT;
3379
0
      goto out;
3380
0
    } else {
3381
0
      pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519,
3382
0
          NULL, key->ed25519_sk,
3383
0
          ED25519_SK_SZ - ED25519_PK_SZ);
3384
0
      success = pkey != NULL;
3385
0
    }
3386
0
    break;
3387
0
#endif
3388
0
  default:
3389
0
    success = 0;
3390
0
    break;
3391
0
  }
3392
0
  if (success == 0) {
3393
0
    r = SSH_ERR_LIBCRYPTO_ERROR;
3394
0
    goto out;
3395
0
  }
3396
0
  if (format == SSHKEY_PRIVATE_PKCS8) {
3397
0
    if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
3398
0
        passphrase, len, NULL, NULL)) == 0) {
3399
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3400
0
      goto out;
3401
0
    }
3402
0
  }
3403
0
  if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3404
0
    r = SSH_ERR_INTERNAL_ERROR;
3405
0
    goto out;
3406
0
  }
3407
0
  if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3408
0
    goto out;
3409
0
  r = 0;
3410
0
 out:
3411
0
  if (was_shielded)
3412
0
    r = sshkey_shield_private(key);
3413
0
  if (r == 0)
3414
0
    r = sshbuf_putb(buf, blob);
3415
3416
0
  EVP_PKEY_free(pkey);
3417
0
  sshbuf_free(blob);
3418
0
  BIO_free(bio);
3419
0
  return r;
3420
0
}
3421
#endif /* WITH_OPENSSL */
3422
3423
/* Serialise "key" to buffer "blob" */
3424
int
3425
sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3426
    const char *passphrase, const char *comment,
3427
    int format, const char *openssh_format_cipher, int openssh_format_rounds)
3428
0
{
3429
0
  switch (key->type) {
3430
0
#ifdef WITH_OPENSSL
3431
0
  case KEY_ECDSA:
3432
0
  case KEY_RSA:
3433
0
  case KEY_ED25519:
3434
0
    break; /* see below */
3435
#else /* WITH_OPENSSL */
3436
  case KEY_ED25519:
3437
#endif /* WITH_OPENSSL */
3438
0
  case KEY_ED25519_SK:
3439
0
#ifdef WITH_OPENSSL
3440
0
  case KEY_ECDSA_SK:
3441
0
#endif /* WITH_OPENSSL */
3442
0
  case KEY_MLDSA44_ED25519:
3443
0
    return sshkey_private_to_blob2(key, blob, passphrase,
3444
0
        comment, openssh_format_cipher, openssh_format_rounds);
3445
0
  default:
3446
0
    return SSH_ERR_KEY_TYPE_UNKNOWN;
3447
0
  }
3448
3449
0
#ifdef WITH_OPENSSL
3450
0
  switch (format) {
3451
0
  case SSHKEY_PRIVATE_OPENSSH:
3452
0
    return sshkey_private_to_blob2(key, blob, passphrase,
3453
0
        comment, openssh_format_cipher, openssh_format_rounds);
3454
0
  case SSHKEY_PRIVATE_PEM:
3455
0
  case SSHKEY_PRIVATE_PKCS8:
3456
0
    return sshkey_private_to_blob_pem_pkcs8(key, blob,
3457
0
        format, passphrase, comment);
3458
0
  default:
3459
0
    return SSH_ERR_INVALID_ARGUMENT;
3460
0
  }
3461
0
#endif /* WITH_OPENSSL */
3462
0
}
3463
3464
#ifdef WITH_OPENSSL
3465
static int
3466
translate_libcrypto_error(unsigned long pem_err)
3467
0
{
3468
0
  int pem_reason = ERR_GET_REASON(pem_err);
3469
3470
0
  switch (ERR_GET_LIB(pem_err)) {
3471
0
  case ERR_LIB_PEM:
3472
0
    switch (pem_reason) {
3473
0
    case PEM_R_BAD_PASSWORD_READ:
3474
0
#ifdef PEM_R_PROBLEMS_GETTING_PASSWORD
3475
0
    case PEM_R_PROBLEMS_GETTING_PASSWORD:
3476
0
#endif
3477
0
#ifdef PEM_R_BAD_DECRYPT
3478
0
    case PEM_R_BAD_DECRYPT:
3479
0
#endif
3480
0
      return SSH_ERR_KEY_WRONG_PASSPHRASE;
3481
0
    default:
3482
0
      return SSH_ERR_INVALID_FORMAT;
3483
0
    }
3484
0
  case ERR_LIB_EVP:
3485
0
    switch (pem_reason) {
3486
0
#ifdef EVP_R_BAD_DECRYPT
3487
0
    case EVP_R_BAD_DECRYPT:
3488
0
      return SSH_ERR_KEY_WRONG_PASSPHRASE;
3489
0
#endif
3490
#ifdef EVP_R_BN_DECODE_ERROR
3491
    case EVP_R_BN_DECODE_ERROR:
3492
#endif
3493
0
    case EVP_R_DECODE_ERROR:
3494
0
#ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3495
0
    case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3496
0
#endif
3497
0
      return SSH_ERR_INVALID_FORMAT;
3498
0
    default:
3499
0
      return SSH_ERR_LIBCRYPTO_ERROR;
3500
0
    }
3501
0
  case ERR_LIB_ASN1:
3502
#ifdef ERR_LIB_OSSL_DECODER
3503
  case ERR_LIB_OSSL_DECODER:
3504
#endif
3505
0
    return SSH_ERR_INVALID_FORMAT;
3506
0
  }
3507
0
  return SSH_ERR_LIBCRYPTO_ERROR;
3508
0
}
3509
3510
static void
3511
clear_libcrypto_errors(void)
3512
0
{
3513
0
  while (ERR_get_error() != 0)
3514
0
    ;
3515
0
}
3516
3517
/*
3518
 * Translate OpenSSL error codes to determine whether
3519
 * passphrase is required/incorrect.
3520
 */
3521
static int
3522
convert_libcrypto_error(void)
3523
0
{
3524
  /*
3525
   * Some password errors are reported at the beginning
3526
   * of the error queue.
3527
   */
3528
0
  if (translate_libcrypto_error(ERR_peek_error()) ==
3529
0
      SSH_ERR_KEY_WRONG_PASSPHRASE)
3530
0
    return SSH_ERR_KEY_WRONG_PASSPHRASE;
3531
0
  return translate_libcrypto_error(ERR_peek_last_error());
3532
0
}
3533
3534
static int
3535
pem_passphrase_cb(char *buf, int size, int rwflag, void *u)
3536
0
{
3537
0
  char *p = (char *)u;
3538
0
  size_t len;
3539
3540
0
  if (p == NULL || (len = strlen(p)) == 0)
3541
0
    return -1;
3542
0
  if (size < 0 || len > (size_t)size)
3543
0
    return -1;
3544
0
  memcpy(buf, p, len);
3545
0
  return (int)len;
3546
0
}
3547
3548
static int
3549
sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3550
    const char *passphrase, struct sshkey **keyp)
3551
0
{
3552
0
  EVP_PKEY *pk = NULL;
3553
0
  struct sshkey *prv = NULL;
3554
0
  BIO *bio = NULL;
3555
0
  int r;
3556
0
  RSA *rsa = NULL;
3557
0
  EC_KEY *ecdsa = NULL;
3558
3559
0
  if (keyp != NULL)
3560
0
    *keyp = NULL;
3561
3562
0
  if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3563
0
    return SSH_ERR_ALLOC_FAIL;
3564
0
  if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3565
0
      (int)sshbuf_len(blob)) {
3566
0
    r = SSH_ERR_ALLOC_FAIL;
3567
0
    goto out;
3568
0
  }
3569
3570
0
  clear_libcrypto_errors();
3571
0
  if ((pk = PEM_read_bio_PrivateKey(bio, NULL, pem_passphrase_cb,
3572
0
      (char *)passphrase)) == NULL) {
3573
    /*
3574
     * libcrypto may return various ASN.1 errors when attempting
3575
     * to parse a key with an incorrect passphrase.
3576
     * Treat all format errors as "incorrect passphrase" if a
3577
     * passphrase was supplied.
3578
     */
3579
0
    if (passphrase != NULL && *passphrase != '\0')
3580
0
      r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3581
0
    else
3582
0
      r = convert_libcrypto_error();
3583
0
    goto out;
3584
0
  }
3585
0
  if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
3586
0
      (type == KEY_UNSPEC || type == KEY_RSA)) {
3587
0
    if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3588
0
      r = SSH_ERR_ALLOC_FAIL;
3589
0
      goto out;
3590
0
    }
3591
0
    if ((rsa = EVP_PKEY_get1_RSA(pk)) == NULL) {
3592
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3593
0
      goto out;
3594
0
    }
3595
0
    prv->type = KEY_RSA;
3596
#ifdef DEBUG_PK
3597
    RSA_print_fp(stderr, rsa, 8);
3598
#endif
3599
0
    if (RSA_blinding_on(rsa, NULL) != 1 ||
3600
0
        EVP_PKEY_set1_RSA(pk, rsa) != 1) {
3601
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3602
0
      goto out;
3603
0
    }
3604
0
    EVP_PKEY_up_ref(pk);
3605
0
    prv->pkey = pk;
3606
0
    if ((r = sshkey_check_rsa_length(prv, 0)) != 0)
3607
0
      goto out;
3608
0
  } else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
3609
0
      (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3610
0
    if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3611
0
      r = SSH_ERR_ALLOC_FAIL;
3612
0
      goto out;
3613
0
    }
3614
0
    if ((prv->ecdsa_nid = sshkey_ecdsa_fixup_group(pk)) == -1 ||
3615
0
        (ecdsa = EVP_PKEY_get1_EC_KEY(pk)) == NULL) {
3616
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3617
0
      goto out;
3618
0
    }
3619
0
    prv->type = KEY_ECDSA;
3620
0
    if (sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3621
0
        sshkey_ec_validate_public(EC_KEY_get0_group(ecdsa),
3622
0
        EC_KEY_get0_public_key(ecdsa)) != 0 ||
3623
0
        sshkey_ec_validate_private(ecdsa) != 0) {
3624
0
      r = SSH_ERR_INVALID_FORMAT;
3625
0
      goto out;
3626
0
    }
3627
0
    EVP_PKEY_up_ref(pk);
3628
0
    prv->pkey = pk;
3629
#ifdef DEBUG_PK
3630
    if (prv != NULL && prv->pkey != NULL)
3631
      sshkey_dump_ec_key(EVP_PKEY_get0_EC_KEY(prv->pkey));
3632
#endif
3633
0
#ifdef OPENSSL_HAS_ED25519
3634
0
  } else if (EVP_PKEY_base_id(pk) == EVP_PKEY_ED25519 &&
3635
0
      (type == KEY_UNSPEC || type == KEY_ED25519)) {
3636
0
    size_t len;
3637
3638
0
    if ((prv = sshkey_new(KEY_UNSPEC)) == NULL ||
3639
0
        (prv->ed25519_sk = calloc(1, ED25519_SK_SZ)) == NULL ||
3640
0
        (prv->ed25519_pk = calloc(1, ED25519_PK_SZ)) == NULL) {
3641
0
      r = SSH_ERR_ALLOC_FAIL;
3642
0
      goto out;
3643
0
    }
3644
0
    prv->type = KEY_ED25519;
3645
0
    len = ED25519_PK_SZ;
3646
0
    if (!EVP_PKEY_get_raw_public_key(pk, prv->ed25519_pk, &len)) {
3647
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3648
0
      goto out;
3649
0
    }
3650
0
    if (len != ED25519_PK_SZ) {
3651
0
      r = SSH_ERR_INVALID_FORMAT;
3652
0
      goto out;
3653
0
    }
3654
0
    len = ED25519_SK_SZ - ED25519_PK_SZ;
3655
0
    if (!EVP_PKEY_get_raw_private_key(pk, prv->ed25519_sk, &len)) {
3656
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
3657
0
      goto out;
3658
0
    }
3659
0
    if (len != ED25519_SK_SZ - ED25519_PK_SZ) {
3660
0
      r = SSH_ERR_INVALID_FORMAT;
3661
0
      goto out;
3662
0
    }
3663
    /* Append the public key to our private key */
3664
0
    memcpy(prv->ed25519_sk + (ED25519_SK_SZ - ED25519_PK_SZ),
3665
0
        prv->ed25519_pk, ED25519_PK_SZ);
3666
#ifdef DEBUG_PK
3667
    sshbuf_dump_data(prv->ed25519_sk, ED25519_SK_SZ, stderr);
3668
#endif
3669
0
#endif /* OPENSSL_HAS_ED25519 */
3670
0
  } else {
3671
0
    r = SSH_ERR_INVALID_FORMAT;
3672
0
    goto out;
3673
0
  }
3674
0
  r = 0;
3675
0
  if (keyp != NULL) {
3676
0
    *keyp = prv;
3677
0
    prv = NULL;
3678
0
  }
3679
0
 out:
3680
0
  BIO_free(bio);
3681
0
  EVP_PKEY_free(pk);
3682
0
  RSA_free(rsa);
3683
0
  EC_KEY_free(ecdsa);
3684
0
  sshkey_free(prv);
3685
0
  return r;
3686
0
}
3687
#endif /* WITH_OPENSSL */
3688
3689
int
3690
sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3691
    const char *passphrase, struct sshkey **keyp, char **commentp)
3692
0
{
3693
0
  int r = SSH_ERR_INTERNAL_ERROR;
3694
3695
0
  if (keyp != NULL)
3696
0
    *keyp = NULL;
3697
0
  if (commentp != NULL)
3698
0
    *commentp = NULL;
3699
3700
0
  r = sshkey_parse_private2(blob, type, passphrase, keyp, commentp);
3701
  /* Only fallback to PEM parser if a format error occurred. */
3702
0
  if (r != SSH_ERR_INVALID_FORMAT)
3703
0
    return r;
3704
0
#ifdef WITH_OPENSSL
3705
0
  return sshkey_parse_private_pem_fileblob(blob, type,
3706
0
      passphrase, keyp);
3707
#else
3708
  return SSH_ERR_INVALID_FORMAT;
3709
#endif /* WITH_OPENSSL */
3710
0
}
3711
3712
int
3713
sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3714
    struct sshkey **keyp, char **commentp)
3715
0
{
3716
0
  if (keyp != NULL)
3717
0
    *keyp = NULL;
3718
0
  if (commentp != NULL)
3719
0
    *commentp = NULL;
3720
3721
0
  return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3722
0
      passphrase, keyp, commentp);
3723
0
}
3724
3725
void
3726
sshkey_sig_details_free(struct sshkey_sig_details *details)
3727
0
{
3728
0
  freezero(details, sizeof(*details));
3729
0
}
3730
3731
int
3732
sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
3733
    struct sshkey **pubkeyp)
3734
0
{
3735
0
  int r = SSH_ERR_INTERNAL_ERROR;
3736
3737
0
  if (pubkeyp != NULL)
3738
0
    *pubkeyp = NULL;
3739
  /* only new-format private keys bundle a public key inside */
3740
0
  if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
3741
0
    return r;
3742
0
  return 0;
3743
0
}