Coverage Report

Created: 2025-08-29 06:46

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