Coverage Report

Created: 2026-06-10 06:24

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