Coverage Report

Created: 2026-07-16 06:54

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