Coverage Report

Created: 2025-08-28 06:03

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