Coverage Report

Created: 2026-08-13 07:14

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