1 /* $NetBSD: ssh-keygen.c,v 1.45 2023/07/26 17:58:16 christos Exp $ */ 2 /* $OpenBSD: ssh-keygen.c,v 1.466 2023/03/08 00:05:37 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Identity and host key generation and maintenance. 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 */ 15 16 #include "includes.h" 17 __RCSID("$NetBSD: ssh-keygen.c,v 1.45 2023/07/26 17:58:16 christos Exp $"); 18 #include <sys/types.h> 19 #include <sys/socket.h> 20 #include <sys/stat.h> 21 22 #ifdef WITH_OPENSSL 23 #include <openssl/evp.h> 24 #include <openssl/pem.h> 25 #endif 26 27 #include <stdint.h> 28 #include <errno.h> 29 #include <fcntl.h> 30 #include <netdb.h> 31 #include <pwd.h> 32 #include <stdarg.h> 33 #include <stdio.h> 34 #include <stdlib.h> 35 #include <string.h> 36 #include <unistd.h> 37 #include <limits.h> 38 #include <locale.h> 39 40 #include "xmalloc.h" 41 #include "sshkey.h" 42 #include "authfile.h" 43 #include "sshbuf.h" 44 #include "pathnames.h" 45 #include "log.h" 46 #include "misc.h" 47 #include "match.h" 48 #include "hostfile.h" 49 #include "dns.h" 50 #include "ssh.h" 51 #include "ssh2.h" 52 #include "ssherr.h" 53 #include "atomicio.h" 54 #include "krl.h" 55 #include "digest.h" 56 #include "utf8.h" 57 #include "authfd.h" 58 #include "sshsig.h" 59 #include "ssh-sk.h" 60 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */ 61 #include "cipher.h" 62 63 #ifdef ENABLE_PKCS11 64 #include "ssh-pkcs11.h" 65 #endif 66 67 #ifdef WITH_OPENSSL 68 # define DEFAULT_KEY_TYPE_NAME "rsa" 69 #else 70 # define DEFAULT_KEY_TYPE_NAME "ed25519" 71 #endif 72 73 /* 74 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be 75 * overridden on the command line. 76 * 77 * These values, with the exception of DSA, provide security equivalent to at 78 * least 128 bits of security according to NIST Special Publication 800-57: 79 * Recommendation for Key Management Part 1 rev 4 section 5.6.1. 80 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for 81 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only 82 * SHA1 we limit the DSA key size 1k bits. 83 */ 84 #define DEFAULT_BITS 3072 85 #define DEFAULT_BITS_DSA 1024 86 #define DEFAULT_BITS_ECDSA 256 87 88 static int quiet = 0; 89 90 /* Flag indicating that we just want to see the key fingerprint */ 91 static int print_fingerprint = 0; 92 static int print_bubblebabble = 0; 93 94 /* Hash algorithm to use for fingerprints. */ 95 static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 96 97 /* The identity file name, given on the command line or entered by the user. */ 98 static char identity_file[PATH_MAX]; 99 static int have_identity = 0; 100 101 /* This is set to the passphrase if given on the command line. */ 102 static char *identity_passphrase = NULL; 103 104 /* This is set to the new passphrase if given on the command line. */ 105 static char *identity_new_passphrase = NULL; 106 107 /* Key type when certifying */ 108 static u_int cert_key_type = SSH2_CERT_TYPE_USER; 109 110 /* "key ID" of signed key */ 111 static char *cert_key_id = NULL; 112 113 /* Comma-separated list of principal names for certifying keys */ 114 static char *cert_principals = NULL; 115 116 /* Validity period for certificates */ 117 static u_int64_t cert_valid_from = 0; 118 static u_int64_t cert_valid_to = ~0ULL; 119 120 /* Certificate options */ 121 #define CERTOPT_X_FWD (1) 122 #define CERTOPT_AGENT_FWD (1<<1) 123 #define CERTOPT_PORT_FWD (1<<2) 124 #define CERTOPT_PTY (1<<3) 125 #define CERTOPT_USER_RC (1<<4) 126 #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5) 127 #define CERTOPT_REQUIRE_VERIFY (1<<6) 128 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \ 129 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC) 130 static u_int32_t certflags_flags = CERTOPT_DEFAULT; 131 static char *certflags_command = NULL; 132 static char *certflags_src_addr = NULL; 133 134 /* Arbitrary extensions specified by user */ 135 struct cert_ext { 136 char *key; 137 char *val; 138 int crit; 139 }; 140 static struct cert_ext *cert_ext; 141 static size_t ncert_ext; 142 143 /* Conversion to/from various formats */ 144 enum { 145 FMT_RFC4716, 146 FMT_PKCS8, 147 FMT_PEM 148 } convert_format = FMT_RFC4716; 149 150 static const char *key_type_name = NULL; 151 152 /* Load key from this PKCS#11 provider */ 153 static char *pkcs11provider = NULL; 154 155 /* FIDO/U2F provider to use */ 156 static const char *sk_provider = NULL; 157 158 /* Format for writing private keys */ 159 static int private_key_format = SSHKEY_PRIVATE_OPENSSH; 160 161 /* Cipher for new-format private keys */ 162 static char *openssh_format_cipher = NULL; 163 164 /* Number of KDF rounds to derive new format keys. */ 165 static int rounds = 0; 166 167 /* argv0 */ 168 extern char *__progname; 169 170 static char hostname[NI_MAXHOST]; 171 172 #ifdef WITH_OPENSSL 173 /* moduli.c */ 174 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *); 175 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long, 176 unsigned long); 177 #endif 178 179 static void 180 type_bits_valid(int type, const char *name, u_int32_t *bitsp) 181 { 182 if (type == KEY_UNSPEC) 183 fatal("unknown key type %s", key_type_name); 184 if (*bitsp == 0) { 185 #ifdef WITH_OPENSSL 186 int nid; 187 188 switch(type) { 189 case KEY_DSA: 190 *bitsp = DEFAULT_BITS_DSA; 191 break; 192 case KEY_ECDSA: 193 if (name != NULL && 194 (nid = sshkey_ecdsa_nid_from_name(name)) > 0) 195 *bitsp = sshkey_curve_nid_to_bits(nid); 196 if (*bitsp == 0) 197 *bitsp = DEFAULT_BITS_ECDSA; 198 break; 199 case KEY_RSA: 200 *bitsp = DEFAULT_BITS; 201 break; 202 } 203 #endif 204 } 205 #ifdef WITH_OPENSSL 206 switch (type) { 207 case KEY_DSA: 208 if (*bitsp != 1024) 209 fatal("Invalid DSA key length: must be 1024 bits"); 210 break; 211 case KEY_RSA: 212 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE) 213 fatal("Invalid RSA key length: minimum is %d bits", 214 SSH_RSA_MINIMUM_MODULUS_SIZE); 215 else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS) 216 fatal("Invalid RSA key length: maximum is %d bits", 217 OPENSSL_RSA_MAX_MODULUS_BITS); 218 break; 219 case KEY_ECDSA: 220 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1) 221 fatal("Invalid ECDSA key length: valid lengths are " 222 "256, 384 or 521 bits"); 223 } 224 #endif 225 } 226 227 /* 228 * Checks whether a file exists and, if so, asks the user whether they wish 229 * to overwrite it. 230 * Returns nonzero if the file does not already exist or if the user agrees to 231 * overwrite, or zero otherwise. 232 */ 233 static int 234 confirm_overwrite(const char *filename) 235 { 236 char yesno[3]; 237 struct stat st; 238 239 if (stat(filename, &st) != 0) 240 return 1; 241 printf("%s already exists.\n", filename); 242 printf("Overwrite (y/n)? "); 243 fflush(stdout); 244 if (fgets(yesno, sizeof(yesno), stdin) == NULL) 245 return 0; 246 if (yesno[0] != 'y' && yesno[0] != 'Y') 247 return 0; 248 return 1; 249 } 250 251 static void 252 ask_filename(struct passwd *pw, const char *prompt) 253 { 254 char buf[1024]; 255 const char *name = NULL; 256 257 if (key_type_name == NULL) 258 name = _PATH_SSH_CLIENT_ID_RSA; 259 else { 260 switch (sshkey_type_from_name(key_type_name)) { 261 case KEY_DSA_CERT: 262 case KEY_DSA: 263 name = _PATH_SSH_CLIENT_ID_DSA; 264 break; 265 case KEY_ECDSA_CERT: 266 case KEY_ECDSA: 267 name = _PATH_SSH_CLIENT_ID_ECDSA; 268 break; 269 case KEY_ECDSA_SK_CERT: 270 case KEY_ECDSA_SK: 271 name = _PATH_SSH_CLIENT_ID_ECDSA_SK; 272 break; 273 case KEY_RSA_CERT: 274 case KEY_RSA: 275 name = _PATH_SSH_CLIENT_ID_RSA; 276 break; 277 case KEY_ED25519: 278 case KEY_ED25519_CERT: 279 name = _PATH_SSH_CLIENT_ID_ED25519; 280 break; 281 case KEY_ED25519_SK: 282 case KEY_ED25519_SK_CERT: 283 name = _PATH_SSH_CLIENT_ID_ED25519_SK; 284 break; 285 case KEY_XMSS: 286 case KEY_XMSS_CERT: 287 name = _PATH_SSH_CLIENT_ID_XMSS; 288 break; 289 default: 290 fatal("bad key type"); 291 } 292 } 293 snprintf(identity_file, sizeof(identity_file), 294 "%s/%s", pw->pw_dir, name); 295 printf("%s (%s): ", prompt, identity_file); 296 fflush(stdout); 297 if (fgets(buf, sizeof(buf), stdin) == NULL) 298 exit(1); 299 buf[strcspn(buf, "\n")] = '\0'; 300 if (strcmp(buf, "") != 0) 301 strlcpy(identity_file, buf, sizeof(identity_file)); 302 have_identity = 1; 303 } 304 305 static struct sshkey * 306 load_identity(const char *filename, char **commentp) 307 { 308 char *pass; 309 struct sshkey *prv; 310 int r; 311 312 if (commentp != NULL) 313 *commentp = NULL; 314 if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0) 315 return prv; 316 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) 317 fatal_r(r, "Load key \"%s\"", filename); 318 if (identity_passphrase) 319 pass = xstrdup(identity_passphrase); 320 else 321 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN); 322 r = sshkey_load_private(filename, pass, &prv, commentp); 323 freezero(pass, strlen(pass)); 324 if (r != 0) 325 fatal_r(r, "Load key \"%s\"", filename); 326 return prv; 327 } 328 329 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----" 330 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----" 331 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----" 332 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb 333 334 #ifdef WITH_OPENSSL 335 __dead static void 336 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k) 337 { 338 struct sshbuf *b; 339 char comment[61], *b64; 340 int r; 341 342 if ((b = sshbuf_new()) == NULL) 343 fatal_f("sshbuf_new failed"); 344 if ((r = sshkey_putb(k, b)) != 0) 345 fatal_fr(r, "put key"); 346 if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL) 347 fatal_f("sshbuf_dtob64_string failed"); 348 349 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */ 350 snprintf(comment, sizeof(comment), 351 "%u-bit %s, converted by %s@%s from OpenSSH", 352 sshkey_size(k), sshkey_type(k), 353 pw->pw_name, hostname); 354 355 sshkey_free(k); 356 sshbuf_free(b); 357 358 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN); 359 fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64); 360 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END); 361 free(b64); 362 exit(0); 363 } 364 365 __dead static void 366 do_convert_to_pkcs8(struct sshkey *k) 367 { 368 switch (sshkey_type_plain(k->type)) { 369 case KEY_RSA: 370 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa)) 371 fatal("PEM_write_RSA_PUBKEY failed"); 372 break; 373 case KEY_DSA: 374 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa)) 375 fatal("PEM_write_DSA_PUBKEY failed"); 376 break; 377 case KEY_ECDSA: 378 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa)) 379 fatal("PEM_write_EC_PUBKEY failed"); 380 break; 381 default: 382 fatal_f("unsupported key type %s", sshkey_type(k)); 383 } 384 exit(0); 385 } 386 387 __dead static void 388 do_convert_to_pem(struct sshkey *k) 389 { 390 switch (sshkey_type_plain(k->type)) { 391 case KEY_RSA: 392 if (!PEM_write_RSAPublicKey(stdout, k->rsa)) 393 fatal("PEM_write_RSAPublicKey failed"); 394 break; 395 case KEY_DSA: 396 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa)) 397 fatal("PEM_write_DSA_PUBKEY failed"); 398 break; 399 case KEY_ECDSA: 400 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa)) 401 fatal("PEM_write_EC_PUBKEY failed"); 402 break; 403 default: 404 fatal_f("unsupported key type %s", sshkey_type(k)); 405 } 406 exit(0); 407 } 408 409 __dead static void 410 do_convert_to(struct passwd *pw) 411 { 412 struct sshkey *k; 413 struct stat st; 414 int r; 415 416 if (!have_identity) 417 ask_filename(pw, "Enter file in which the key is"); 418 if (stat(identity_file, &st) == -1) 419 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 420 if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0) 421 k = load_identity(identity_file, NULL); 422 switch (convert_format) { 423 case FMT_RFC4716: 424 do_convert_to_ssh2(pw, k); 425 break; 426 case FMT_PKCS8: 427 do_convert_to_pkcs8(k); 428 break; 429 case FMT_PEM: 430 do_convert_to_pem(k); 431 break; 432 default: 433 fatal_f("unknown key format %d", convert_format); 434 } 435 exit(0); 436 } 437 438 /* 439 * This is almost exactly the bignum1 encoding, but with 32 bit for length 440 * instead of 16. 441 */ 442 static void 443 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value) 444 { 445 u_int bytes, bignum_bits; 446 int r; 447 448 if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0) 449 fatal_fr(r, "parse"); 450 bytes = (bignum_bits + 7) / 8; 451 if (sshbuf_len(b) < bytes) 452 fatal_f("input buffer too small: need %d have %zu", 453 bytes, sshbuf_len(b)); 454 if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL) 455 fatal_f("BN_bin2bn failed"); 456 if ((r = sshbuf_consume(b, bytes)) != 0) 457 fatal_fr(r, "consume"); 458 } 459 460 static struct sshkey * 461 do_convert_private_ssh2(struct sshbuf *b) 462 { 463 struct sshkey *key = NULL; 464 char *type, *cipher; 465 const char *alg = NULL; 466 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345"; 467 int r, rlen, ktype; 468 u_int magic, i1, i2, i3, i4; 469 size_t slen; 470 u_long e; 471 BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL; 472 BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL; 473 BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL; 474 BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL; 475 476 if ((r = sshbuf_get_u32(b, &magic)) != 0) 477 fatal_fr(r, "parse magic"); 478 479 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) { 480 error("bad magic 0x%x != 0x%x", magic, 481 SSH_COM_PRIVATE_KEY_MAGIC); 482 return NULL; 483 } 484 if ((r = sshbuf_get_u32(b, &i1)) != 0 || 485 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 || 486 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 || 487 (r = sshbuf_get_u32(b, &i2)) != 0 || 488 (r = sshbuf_get_u32(b, &i3)) != 0 || 489 (r = sshbuf_get_u32(b, &i4)) != 0) 490 fatal_fr(r, "parse"); 491 debug("ignore (%d %d %d %d)", i1, i2, i3, i4); 492 if (strcmp(cipher, "none") != 0) { 493 error("unsupported cipher %s", cipher); 494 free(cipher); 495 free(type); 496 return NULL; 497 } 498 free(cipher); 499 500 if (strstr(type, "dsa")) { 501 ktype = KEY_DSA; 502 } else if (strstr(type, "rsa")) { 503 ktype = KEY_RSA; 504 } else { 505 free(type); 506 return NULL; 507 } 508 if ((key = sshkey_new(ktype)) == NULL) 509 fatal("sshkey_new failed"); 510 free(type); 511 512 switch (key->type) { 513 case KEY_DSA: 514 if ((dsa_p = BN_new()) == NULL || 515 (dsa_q = BN_new()) == NULL || 516 (dsa_g = BN_new()) == NULL || 517 (dsa_pub_key = BN_new()) == NULL || 518 (dsa_priv_key = BN_new()) == NULL) 519 fatal_f("BN_new"); 520 buffer_get_bignum_bits(b, dsa_p); 521 buffer_get_bignum_bits(b, dsa_g); 522 buffer_get_bignum_bits(b, dsa_q); 523 buffer_get_bignum_bits(b, dsa_pub_key); 524 buffer_get_bignum_bits(b, dsa_priv_key); 525 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g)) 526 fatal_f("DSA_set0_pqg failed"); 527 dsa_p = dsa_q = dsa_g = NULL; /* transferred */ 528 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key)) 529 fatal_f("DSA_set0_key failed"); 530 dsa_pub_key = dsa_priv_key = NULL; /* transferred */ 531 break; 532 case KEY_RSA: 533 if ((r = sshbuf_get_u8(b, &e1)) != 0 || 534 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) || 535 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0)) 536 fatal_fr(r, "parse RSA"); 537 e = e1; 538 debug("e %lx", e); 539 if (e < 30) { 540 e <<= 8; 541 e += e2; 542 debug("e %lx", e); 543 e <<= 8; 544 e += e3; 545 debug("e %lx", e); 546 } 547 if ((rsa_e = BN_new()) == NULL) 548 fatal_f("BN_new"); 549 if (!BN_set_word(rsa_e, e)) { 550 BN_clear_free(rsa_e); 551 sshkey_free(key); 552 return NULL; 553 } 554 if ((rsa_n = BN_new()) == NULL || 555 (rsa_d = BN_new()) == NULL || 556 (rsa_p = BN_new()) == NULL || 557 (rsa_q = BN_new()) == NULL || 558 (rsa_iqmp = BN_new()) == NULL) 559 fatal_f("BN_new"); 560 buffer_get_bignum_bits(b, rsa_d); 561 buffer_get_bignum_bits(b, rsa_n); 562 buffer_get_bignum_bits(b, rsa_iqmp); 563 buffer_get_bignum_bits(b, rsa_q); 564 buffer_get_bignum_bits(b, rsa_p); 565 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d)) 566 fatal_f("RSA_set0_key failed"); 567 rsa_n = rsa_e = rsa_d = NULL; /* transferred */ 568 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q)) 569 fatal_f("RSA_set0_factors failed"); 570 rsa_p = rsa_q = NULL; /* transferred */ 571 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0) 572 fatal_fr(r, "generate RSA parameters"); 573 BN_clear_free(rsa_iqmp); 574 alg = "rsa-sha2-256"; 575 break; 576 } 577 rlen = sshbuf_len(b); 578 if (rlen != 0) 579 error_f("remaining bytes in key blob %d", rlen); 580 581 /* try the key */ 582 if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data), 583 alg, NULL, NULL, 0)) != 0) 584 error_fr(r, "signing with converted key failed"); 585 else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data), 586 alg, 0, NULL)) != 0) 587 error_fr(r, "verification with converted key failed"); 588 if (r != 0) { 589 sshkey_free(key); 590 free(sig); 591 return NULL; 592 } 593 free(sig); 594 return key; 595 } 596 597 static int 598 get_line(FILE *fp, char *line, size_t len) 599 { 600 int c; 601 size_t pos = 0; 602 603 line[0] = '\0'; 604 while ((c = fgetc(fp)) != EOF) { 605 if (pos >= len - 1) 606 fatal("input line too long."); 607 switch (c) { 608 case '\r': 609 c = fgetc(fp); 610 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) 611 fatal("unget: %s", strerror(errno)); 612 return pos; 613 case '\n': 614 return pos; 615 } 616 line[pos++] = c; 617 line[pos] = '\0'; 618 } 619 /* We reached EOF */ 620 return -1; 621 } 622 623 static void 624 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private) 625 { 626 int r, blen, escaped = 0; 627 u_int len; 628 char line[1024]; 629 struct sshbuf *buf; 630 char encoded[8096]; 631 FILE *fp; 632 633 if ((buf = sshbuf_new()) == NULL) 634 fatal("sshbuf_new failed"); 635 if ((fp = fopen(identity_file, "r")) == NULL) 636 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 637 encoded[0] = '\0'; 638 while ((blen = get_line(fp, line, sizeof(line))) != -1) { 639 if (blen > 0 && line[blen - 1] == '\\') 640 escaped++; 641 if (strncmp(line, "----", 4) == 0 || 642 strstr(line, ": ") != NULL) { 643 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL) 644 *private = 1; 645 if (strstr(line, " END ") != NULL) { 646 break; 647 } 648 /* fprintf(stderr, "ignore: %s", line); */ 649 continue; 650 } 651 if (escaped) { 652 escaped--; 653 /* fprintf(stderr, "escaped: %s", line); */ 654 continue; 655 } 656 strlcat(encoded, line, sizeof(encoded)); 657 } 658 len = strlen(encoded); 659 if (((len % 4) == 3) && 660 (encoded[len-1] == '=') && 661 (encoded[len-2] == '=') && 662 (encoded[len-3] == '=')) 663 encoded[len-3] = '\0'; 664 if ((r = sshbuf_b64tod(buf, encoded)) != 0) 665 fatal_fr(r, "base64 decode"); 666 if (*private) { 667 if ((*k = do_convert_private_ssh2(buf)) == NULL) 668 fatal_f("private key conversion failed"); 669 } else if ((r = sshkey_fromb(buf, k)) != 0) 670 fatal_fr(r, "parse key"); 671 sshbuf_free(buf); 672 fclose(fp); 673 } 674 675 static void 676 do_convert_from_pkcs8(struct sshkey **k, int *private) 677 { 678 EVP_PKEY *pubkey; 679 FILE *fp; 680 681 if ((fp = fopen(identity_file, "r")) == NULL) 682 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 683 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) { 684 fatal_f("%s is not a recognised public key format", 685 identity_file); 686 } 687 fclose(fp); 688 switch (EVP_PKEY_base_id(pubkey)) { 689 case EVP_PKEY_RSA: 690 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL) 691 fatal("sshkey_new failed"); 692 (*k)->type = KEY_RSA; 693 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey); 694 break; 695 case EVP_PKEY_DSA: 696 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL) 697 fatal("sshkey_new failed"); 698 (*k)->type = KEY_DSA; 699 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey); 700 break; 701 case EVP_PKEY_EC: 702 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL) 703 fatal("sshkey_new failed"); 704 (*k)->type = KEY_ECDSA; 705 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey); 706 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa); 707 break; 708 default: 709 fatal_f("unsupported pubkey type %d", 710 EVP_PKEY_base_id(pubkey)); 711 } 712 EVP_PKEY_free(pubkey); 713 return; 714 } 715 716 static void 717 do_convert_from_pem(struct sshkey **k, int *private) 718 { 719 FILE *fp; 720 RSA *rsa; 721 722 if ((fp = fopen(identity_file, "r")) == NULL) 723 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 724 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) { 725 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL) 726 fatal("sshkey_new failed"); 727 (*k)->type = KEY_RSA; 728 (*k)->rsa = rsa; 729 fclose(fp); 730 return; 731 } 732 fatal_f("unrecognised raw private key format"); 733 } 734 735 __dead static void 736 do_convert_from(struct passwd *pw) 737 { 738 struct sshkey *k = NULL; 739 int r, private = 0, ok = 0; 740 struct stat st; 741 742 if (!have_identity) 743 ask_filename(pw, "Enter file in which the key is"); 744 if (stat(identity_file, &st) == -1) 745 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 746 747 switch (convert_format) { 748 case FMT_RFC4716: 749 do_convert_from_ssh2(pw, &k, &private); 750 break; 751 case FMT_PKCS8: 752 do_convert_from_pkcs8(&k, &private); 753 break; 754 case FMT_PEM: 755 do_convert_from_pem(&k, &private); 756 break; 757 default: 758 fatal_f("unknown key format %d", convert_format); 759 } 760 761 if (!private) { 762 if ((r = sshkey_write(k, stdout)) == 0) 763 ok = 1; 764 if (ok) 765 fprintf(stdout, "\n"); 766 } else { 767 switch (k->type) { 768 case KEY_DSA: 769 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, 770 NULL, 0, NULL, NULL); 771 break; 772 case KEY_ECDSA: 773 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL, 774 NULL, 0, NULL, NULL); 775 break; 776 case KEY_RSA: 777 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, 778 NULL, 0, NULL, NULL); 779 break; 780 default: 781 fatal_f("unsupported key type %s", sshkey_type(k)); 782 } 783 } 784 785 if (!ok) 786 fatal("key write failed"); 787 sshkey_free(k); 788 exit(0); 789 } 790 #endif 791 792 __dead static void 793 do_print_public(struct passwd *pw) 794 { 795 struct sshkey *prv; 796 struct stat st; 797 int r; 798 char *comment = NULL; 799 800 if (!have_identity) 801 ask_filename(pw, "Enter file in which the key is"); 802 if (stat(identity_file, &st) == -1) 803 fatal("%s: %s", identity_file, strerror(errno)); 804 prv = load_identity(identity_file, &comment); 805 if ((r = sshkey_write(prv, stdout)) != 0) 806 fatal_fr(r, "write key"); 807 if (comment != NULL && *comment != '\0') 808 fprintf(stdout, " %s", comment); 809 fprintf(stdout, "\n"); 810 if (sshkey_is_sk(prv)) { 811 debug("sk_application: \"%s\", sk_flags 0x%02x", 812 prv->sk_application, prv->sk_flags); 813 } 814 sshkey_free(prv); 815 free(comment); 816 exit(0); 817 } 818 819 __dead static void 820 do_download(struct passwd *pw) 821 { 822 #ifdef ENABLE_PKCS11 823 struct sshkey **keys = NULL; 824 int i, nkeys; 825 enum sshkey_fp_rep rep; 826 int fptype; 827 char *fp, *ra, **comments = NULL; 828 829 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash; 830 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT; 831 832 pkcs11_init(1); 833 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments); 834 if (nkeys <= 0) 835 fatal("cannot read public key from pkcs11"); 836 for (i = 0; i < nkeys; i++) { 837 if (print_fingerprint) { 838 fp = sshkey_fingerprint(keys[i], fptype, rep); 839 ra = sshkey_fingerprint(keys[i], fingerprint_hash, 840 SSH_FP_RANDOMART); 841 if (fp == NULL || ra == NULL) 842 fatal_f("sshkey_fingerprint fail"); 843 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]), 844 fp, sshkey_type(keys[i])); 845 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE) 846 printf("%s\n", ra); 847 free(ra); 848 free(fp); 849 } else { 850 (void) sshkey_write(keys[i], stdout); /* XXX check */ 851 fprintf(stdout, "%s%s\n", 852 *(comments[i]) == '\0' ? "" : " ", comments[i]); 853 } 854 free(comments[i]); 855 sshkey_free(keys[i]); 856 } 857 free(comments); 858 free(keys); 859 pkcs11_terminate(); 860 exit(0); 861 #else 862 fatal("no pkcs11 support"); 863 #endif /* ENABLE_PKCS11 */ 864 } 865 866 static struct sshkey * 867 try_read_key(char **cpp) 868 { 869 struct sshkey *ret; 870 int r; 871 872 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL) 873 fatal("sshkey_new failed"); 874 if ((r = sshkey_read(ret, cpp)) == 0) 875 return ret; 876 /* Not a key */ 877 sshkey_free(ret); 878 return NULL; 879 } 880 881 static void 882 fingerprint_one_key(const struct sshkey *public, const char *comment) 883 { 884 char *fp = NULL, *ra = NULL; 885 enum sshkey_fp_rep rep; 886 int fptype; 887 888 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash; 889 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT; 890 fp = sshkey_fingerprint(public, fptype, rep); 891 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART); 892 if (fp == NULL || ra == NULL) 893 fatal_f("sshkey_fingerprint failed"); 894 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp, 895 comment ? comment : "no comment", sshkey_type(public)); 896 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE) 897 printf("%s\n", ra); 898 free(ra); 899 free(fp); 900 } 901 902 static void 903 fingerprint_private(const char *path) 904 { 905 struct stat st; 906 char *comment = NULL; 907 struct sshkey *privkey = NULL, *pubkey = NULL; 908 int r; 909 910 if (stat(identity_file, &st) == -1) 911 fatal("%s: %s", path, strerror(errno)); 912 if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0) 913 debug_r(r, "load public \"%s\"", path); 914 if (pubkey == NULL || comment == NULL || *comment == '\0') { 915 free(comment); 916 if ((r = sshkey_load_private(path, NULL, 917 &privkey, &comment)) != 0) 918 debug_r(r, "load private \"%s\"", path); 919 } 920 if (pubkey == NULL && privkey == NULL) 921 fatal("%s is not a key file.", path); 922 923 fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment); 924 sshkey_free(pubkey); 925 sshkey_free(privkey); 926 free(comment); 927 } 928 929 __dead static void 930 do_fingerprint(struct passwd *pw) 931 { 932 FILE *f; 933 struct sshkey *public = NULL; 934 char *comment = NULL, *cp, *ep, *line = NULL; 935 size_t linesize = 0; 936 int i, invalid = 1; 937 const char *path; 938 u_long lnum = 0; 939 940 if (!have_identity) 941 ask_filename(pw, "Enter file in which the key is"); 942 path = identity_file; 943 944 if (strcmp(identity_file, "-") == 0) { 945 f = stdin; 946 path = "(stdin)"; 947 } else if ((f = fopen(path, "r")) == NULL) 948 fatal("%s: %s: %s", __progname, path, strerror(errno)); 949 950 while (getline(&line, &linesize, f) != -1) { 951 lnum++; 952 cp = line; 953 cp[strcspn(cp, "\n")] = '\0'; 954 /* Trim leading space and comments */ 955 cp = line + strspn(line, " \t"); 956 if (*cp == '#' || *cp == '\0') 957 continue; 958 959 /* 960 * Input may be plain keys, private keys, authorized_keys 961 * or known_hosts. 962 */ 963 964 /* 965 * Try private keys first. Assume a key is private if 966 * "SSH PRIVATE KEY" appears on the first line and we're 967 * not reading from stdin (XXX support private keys on stdin). 968 */ 969 if (lnum == 1 && strcmp(identity_file, "-") != 0 && 970 strstr(cp, "PRIVATE KEY") != NULL) { 971 free(line); 972 fclose(f); 973 fingerprint_private(path); 974 exit(0); 975 } 976 977 /* 978 * If it's not a private key, then this must be prepared to 979 * accept a public key prefixed with a hostname or options. 980 * Try a bare key first, otherwise skip the leading stuff. 981 */ 982 if ((public = try_read_key(&cp)) == NULL) { 983 i = strtol(cp, &ep, 10); 984 if (i == 0 || ep == NULL || 985 (*ep != ' ' && *ep != '\t')) { 986 int quoted = 0; 987 988 comment = cp; 989 for (; *cp && (quoted || (*cp != ' ' && 990 *cp != '\t')); cp++) { 991 if (*cp == '\\' && cp[1] == '"') 992 cp++; /* Skip both */ 993 else if (*cp == '"') 994 quoted = !quoted; 995 } 996 if (!*cp) 997 continue; 998 *cp++ = '\0'; 999 } 1000 } 1001 /* Retry after parsing leading hostname/key options */ 1002 if (public == NULL && (public = try_read_key(&cp)) == NULL) { 1003 debug("%s:%lu: not a public key", path, lnum); 1004 continue; 1005 } 1006 1007 /* Find trailing comment, if any */ 1008 for (; *cp == ' ' || *cp == '\t'; cp++) 1009 ; 1010 if (*cp != '\0' && *cp != '#') 1011 comment = cp; 1012 1013 fingerprint_one_key(public, comment); 1014 sshkey_free(public); 1015 invalid = 0; /* One good key in the file is sufficient */ 1016 } 1017 fclose(f); 1018 free(line); 1019 1020 if (invalid) 1021 fatal("%s is not a public key file.", path); 1022 exit(0); 1023 } 1024 1025 static void 1026 do_gen_all_hostkeys(struct passwd *pw) 1027 { 1028 struct { 1029 const char *key_type; 1030 const char *key_type_display; 1031 const char *path; 1032 } key_types[] = { 1033 #ifdef WITH_OPENSSL 1034 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE }, 1035 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE }, 1036 #endif /* WITH_OPENSSL */ 1037 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE }, 1038 #ifdef WITH_XMSS 1039 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE }, 1040 #endif /* WITH_XMSS */ 1041 { NULL, NULL, NULL } 1042 }; 1043 1044 u_int32_t bits = 0; 1045 int first = 0; 1046 struct stat st; 1047 struct sshkey *private, *public; 1048 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file; 1049 int i, type, fd, r; 1050 1051 for (i = 0; key_types[i].key_type; i++) { 1052 public = private = NULL; 1053 prv_tmp = pub_tmp = prv_file = pub_file = NULL; 1054 1055 xasprintf(&prv_file, "%s%s", 1056 identity_file, key_types[i].path); 1057 1058 /* Check whether private key exists and is not zero-length */ 1059 if (stat(prv_file, &st) == 0) { 1060 if (st.st_size != 0) 1061 goto next; 1062 } else if (errno != ENOENT) { 1063 error("Could not stat %s: %s", key_types[i].path, 1064 strerror(errno)); 1065 goto failnext; 1066 } 1067 1068 /* 1069 * Private key doesn't exist or is invalid; proceed with 1070 * key generation. 1071 */ 1072 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX", 1073 identity_file, key_types[i].path); 1074 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX", 1075 identity_file, key_types[i].path); 1076 xasprintf(&pub_file, "%s%s.pub", 1077 identity_file, key_types[i].path); 1078 1079 if (first == 0) { 1080 first = 1; 1081 printf("%s: generating new host keys: ", __progname); 1082 } 1083 printf("%s ", key_types[i].key_type_display); 1084 fflush(stdout); 1085 type = sshkey_type_from_name(key_types[i].key_type); 1086 if ((fd = mkstemp(prv_tmp)) == -1) { 1087 error("Could not save your private key in %s: %s", 1088 prv_tmp, strerror(errno)); 1089 goto failnext; 1090 } 1091 (void)close(fd); /* just using mkstemp() to reserve a name */ 1092 bits = 0; 1093 type_bits_valid(type, NULL, &bits); 1094 if ((r = sshkey_generate(type, bits, &private)) != 0) { 1095 error_r(r, "sshkey_generate failed"); 1096 goto failnext; 1097 } 1098 if ((r = sshkey_from_private(private, &public)) != 0) 1099 fatal_fr(r, "sshkey_from_private"); 1100 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, 1101 hostname); 1102 if ((r = sshkey_save_private(private, prv_tmp, "", 1103 comment, private_key_format, openssh_format_cipher, 1104 rounds)) != 0) { 1105 error_r(r, "Saving key \"%s\" failed", prv_tmp); 1106 goto failnext; 1107 } 1108 if ((fd = mkstemp(pub_tmp)) == -1) { 1109 error("Could not save your public key in %s: %s", 1110 pub_tmp, strerror(errno)); 1111 goto failnext; 1112 } 1113 (void)fchmod(fd, 0644); 1114 (void)close(fd); 1115 if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) { 1116 error_r(r, "Unable to save public key to %s", 1117 identity_file); 1118 goto failnext; 1119 } 1120 1121 /* Rename temporary files to their permanent locations. */ 1122 if (rename(pub_tmp, pub_file) != 0) { 1123 error("Unable to move %s into position: %s", 1124 pub_file, strerror(errno)); 1125 goto failnext; 1126 } 1127 if (rename(prv_tmp, prv_file) != 0) { 1128 error("Unable to move %s into position: %s", 1129 key_types[i].path, strerror(errno)); 1130 failnext: 1131 first = 0; 1132 goto next; 1133 } 1134 next: 1135 sshkey_free(private); 1136 sshkey_free(public); 1137 free(prv_tmp); 1138 free(pub_tmp); 1139 free(prv_file); 1140 free(pub_file); 1141 } 1142 if (first != 0) 1143 printf("\n"); 1144 } 1145 1146 struct known_hosts_ctx { 1147 const char *host; /* Hostname searched for in find/delete case */ 1148 FILE *out; /* Output file, stdout for find_hosts case */ 1149 int has_unhashed; /* When hashing, original had unhashed hosts */ 1150 int found_key; /* For find/delete, host was found */ 1151 int invalid; /* File contained invalid items; don't delete */ 1152 int hash_hosts; /* Hash hostnames as we go */ 1153 int find_host; /* Search for specific hostname */ 1154 int delete_host; /* Delete host from known_hosts */ 1155 }; 1156 1157 static int 1158 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx) 1159 { 1160 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx; 1161 char *hashed, *cp, *hosts, *ohosts; 1162 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts); 1163 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM; 1164 1165 switch (l->status) { 1166 case HKF_STATUS_OK: 1167 case HKF_STATUS_MATCHED: 1168 /* 1169 * Don't hash hosts already already hashed, with wildcard 1170 * characters or a CA/revocation marker. 1171 */ 1172 if (was_hashed || has_wild || l->marker != MRK_NONE) { 1173 fprintf(ctx->out, "%s\n", l->line); 1174 if (has_wild && !ctx->find_host) { 1175 logit("%s:%lu: ignoring host name " 1176 "with wildcard: %.64s", l->path, 1177 l->linenum, l->hosts); 1178 } 1179 return 0; 1180 } 1181 /* 1182 * Split any comma-separated hostnames from the host list, 1183 * hash and store separately. 1184 */ 1185 ohosts = hosts = xstrdup(l->hosts); 1186 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') { 1187 lowercase(cp); 1188 if ((hashed = host_hash(cp, NULL, 0)) == NULL) 1189 fatal("hash_host failed"); 1190 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey); 1191 free(hashed); 1192 ctx->has_unhashed = 1; 1193 } 1194 free(ohosts); 1195 return 0; 1196 case HKF_STATUS_INVALID: 1197 /* Retain invalid lines, but mark file as invalid. */ 1198 ctx->invalid = 1; 1199 logit("%s:%lu: invalid line", l->path, l->linenum); 1200 /* FALLTHROUGH */ 1201 default: 1202 fprintf(ctx->out, "%s\n", l->line); 1203 return 0; 1204 } 1205 /* NOTREACHED */ 1206 return -1; 1207 } 1208 1209 static int 1210 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx) 1211 { 1212 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx; 1213 enum sshkey_fp_rep rep; 1214 int fptype; 1215 char *fp = NULL, *ra = NULL; 1216 1217 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash; 1218 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT; 1219 1220 if (l->status == HKF_STATUS_MATCHED) { 1221 if (ctx->delete_host) { 1222 if (l->marker != MRK_NONE) { 1223 /* Don't remove CA and revocation lines */ 1224 fprintf(ctx->out, "%s\n", l->line); 1225 } else { 1226 /* 1227 * Hostname matches and has no CA/revoke 1228 * marker, delete it by *not* writing the 1229 * line to ctx->out. 1230 */ 1231 ctx->found_key = 1; 1232 if (!quiet) 1233 printf("# Host %s found: line %lu\n", 1234 ctx->host, l->linenum); 1235 } 1236 return 0; 1237 } else if (ctx->find_host) { 1238 ctx->found_key = 1; 1239 if (!quiet) { 1240 printf("# Host %s found: line %lu %s\n", 1241 ctx->host, 1242 l->linenum, l->marker == MRK_CA ? "CA" : 1243 (l->marker == MRK_REVOKE ? "REVOKED" : "")); 1244 } 1245 if (ctx->hash_hosts) 1246 known_hosts_hash(l, ctx); 1247 else if (print_fingerprint) { 1248 fp = sshkey_fingerprint(l->key, fptype, rep); 1249 ra = sshkey_fingerprint(l->key, 1250 fingerprint_hash, SSH_FP_RANDOMART); 1251 if (fp == NULL || ra == NULL) 1252 fatal_f("sshkey_fingerprint failed"); 1253 mprintf("%s %s %s%s%s\n", ctx->host, 1254 sshkey_type(l->key), fp, 1255 l->comment[0] ? " " : "", 1256 l->comment); 1257 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE) 1258 printf("%s\n", ra); 1259 free(ra); 1260 free(fp); 1261 } else 1262 fprintf(ctx->out, "%s\n", l->line); 1263 return 0; 1264 } 1265 } else if (ctx->delete_host) { 1266 /* Retain non-matching hosts when deleting */ 1267 if (l->status == HKF_STATUS_INVALID) { 1268 ctx->invalid = 1; 1269 logit("%s:%lu: invalid line", l->path, l->linenum); 1270 } 1271 fprintf(ctx->out, "%s\n", l->line); 1272 } 1273 return 0; 1274 } 1275 1276 __dead static void 1277 do_known_hosts(struct passwd *pw, const char *name, int find_host, 1278 int delete_host, int hash_hosts) 1279 { 1280 char *cp, tmp[PATH_MAX], old[PATH_MAX]; 1281 int r, fd, oerrno, inplace = 0; 1282 struct known_hosts_ctx ctx; 1283 u_int foreach_options; 1284 struct stat sb; 1285 1286 if (!have_identity) { 1287 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid); 1288 if (strlcpy(identity_file, cp, sizeof(identity_file)) >= 1289 sizeof(identity_file)) 1290 fatal("Specified known hosts path too long"); 1291 free(cp); 1292 have_identity = 1; 1293 } 1294 if (stat(identity_file, &sb) != 0) 1295 fatal("Cannot stat %s: %s", identity_file, strerror(errno)); 1296 1297 memset(&ctx, 0, sizeof(ctx)); 1298 ctx.out = stdout; 1299 ctx.host = name; 1300 ctx.hash_hosts = hash_hosts; 1301 ctx.find_host = find_host; 1302 ctx.delete_host = delete_host; 1303 1304 /* 1305 * Find hosts goes to stdout, hash and deletions happen in-place 1306 * A corner case is ssh-keygen -HF foo, which should go to stdout 1307 */ 1308 if (!find_host && (hash_hosts || delete_host)) { 1309 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) || 1310 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) || 1311 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) || 1312 strlcat(old, ".old", sizeof(old)) >= sizeof(old)) 1313 fatal("known_hosts path too long"); 1314 umask(077); 1315 if ((fd = mkstemp(tmp)) == -1) 1316 fatal("mkstemp: %s", strerror(errno)); 1317 if ((ctx.out = fdopen(fd, "w")) == NULL) { 1318 oerrno = errno; 1319 unlink(tmp); 1320 fatal("fdopen: %s", strerror(oerrno)); 1321 } 1322 (void)fchmod(fd, sb.st_mode & 0644); 1323 inplace = 1; 1324 } 1325 /* XXX support identity_file == "-" for stdin */ 1326 foreach_options = find_host ? HKF_WANT_MATCH : 0; 1327 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0; 1328 if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ? 1329 known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL, 1330 foreach_options, 0)) != 0) { 1331 if (inplace) 1332 unlink(tmp); 1333 fatal_fr(r, "hostkeys_foreach"); 1334 } 1335 1336 if (inplace) 1337 fclose(ctx.out); 1338 1339 if (ctx.invalid) { 1340 error("%s is not a valid known_hosts file.", identity_file); 1341 if (inplace) { 1342 error("Not replacing existing known_hosts " 1343 "file because of errors"); 1344 unlink(tmp); 1345 } 1346 exit(1); 1347 } else if (delete_host && !ctx.found_key) { 1348 logit("Host %s not found in %s", name, identity_file); 1349 if (inplace) 1350 unlink(tmp); 1351 } else if (inplace) { 1352 /* Backup existing file */ 1353 if (unlink(old) == -1 && errno != ENOENT) 1354 fatal("unlink %.100s: %s", old, strerror(errno)); 1355 if (link(identity_file, old) == -1) 1356 fatal("link %.100s to %.100s: %s", identity_file, old, 1357 strerror(errno)); 1358 /* Move new one into place */ 1359 if (rename(tmp, identity_file) == -1) { 1360 error("rename\"%s\" to \"%s\": %s", tmp, identity_file, 1361 strerror(errno)); 1362 unlink(tmp); 1363 unlink(old); 1364 exit(1); 1365 } 1366 1367 printf("%s updated.\n", identity_file); 1368 printf("Original contents retained as %s\n", old); 1369 if (ctx.has_unhashed) { 1370 logit("WARNING: %s contains unhashed entries", old); 1371 logit("Delete this file to ensure privacy " 1372 "of hostnames"); 1373 } 1374 } 1375 1376 exit (find_host && !ctx.found_key); 1377 } 1378 1379 /* 1380 * Perform changing a passphrase. The argument is the passwd structure 1381 * for the current user. 1382 */ 1383 __dead static void 1384 do_change_passphrase(struct passwd *pw) 1385 { 1386 char *comment; 1387 char *old_passphrase, *passphrase1, *passphrase2; 1388 struct stat st; 1389 struct sshkey *private; 1390 int r; 1391 1392 if (!have_identity) 1393 ask_filename(pw, "Enter file in which the key is"); 1394 if (stat(identity_file, &st) == -1) 1395 fatal("%s: %s", identity_file, strerror(errno)); 1396 /* Try to load the file with empty passphrase. */ 1397 r = sshkey_load_private(identity_file, "", &private, &comment); 1398 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) { 1399 if (identity_passphrase) 1400 old_passphrase = xstrdup(identity_passphrase); 1401 else 1402 old_passphrase = 1403 read_passphrase("Enter old passphrase: ", 1404 RP_ALLOW_STDIN); 1405 r = sshkey_load_private(identity_file, old_passphrase, 1406 &private, &comment); 1407 freezero(old_passphrase, strlen(old_passphrase)); 1408 if (r != 0) 1409 goto badkey; 1410 } else if (r != 0) { 1411 badkey: 1412 fatal_r(r, "Failed to load key %s", identity_file); 1413 } 1414 if (comment) 1415 mprintf("Key has comment '%s'\n", comment); 1416 1417 /* Ask the new passphrase (twice). */ 1418 if (identity_new_passphrase) { 1419 passphrase1 = xstrdup(identity_new_passphrase); 1420 passphrase2 = NULL; 1421 } else { 1422 passphrase1 = 1423 read_passphrase("Enter new passphrase (empty for no " 1424 "passphrase): ", RP_ALLOW_STDIN); 1425 passphrase2 = read_passphrase("Enter same passphrase again: ", 1426 RP_ALLOW_STDIN); 1427 1428 /* Verify that they are the same. */ 1429 if (strcmp(passphrase1, passphrase2) != 0) { 1430 explicit_bzero(passphrase1, strlen(passphrase1)); 1431 explicit_bzero(passphrase2, strlen(passphrase2)); 1432 free(passphrase1); 1433 free(passphrase2); 1434 printf("Pass phrases do not match. Try again.\n"); 1435 exit(1); 1436 } 1437 /* Destroy the other copy. */ 1438 freezero(passphrase2, strlen(passphrase2)); 1439 } 1440 1441 /* Save the file using the new passphrase. */ 1442 if ((r = sshkey_save_private(private, identity_file, passphrase1, 1443 comment, private_key_format, openssh_format_cipher, rounds)) != 0) { 1444 error_r(r, "Saving key \"%s\" failed", identity_file); 1445 freezero(passphrase1, strlen(passphrase1)); 1446 sshkey_free(private); 1447 free(comment); 1448 exit(1); 1449 } 1450 /* Destroy the passphrase and the copy of the key in memory. */ 1451 freezero(passphrase1, strlen(passphrase1)); 1452 sshkey_free(private); /* Destroys contents */ 1453 free(comment); 1454 1455 printf("Your identification has been saved with the new passphrase.\n"); 1456 exit(0); 1457 } 1458 1459 /* 1460 * Print the SSHFP RR. 1461 */ 1462 static int 1463 do_print_resource_record(struct passwd *pw, const char *fname, 1464 const char *hname, 1465 int print_generic, char * const *opts, size_t nopts) 1466 { 1467 struct sshkey *public; 1468 char *comment = NULL; 1469 struct stat st; 1470 int r, hash = -1; 1471 size_t i; 1472 1473 for (i = 0; i < nopts; i++) { 1474 if (strncasecmp(opts[i], "hashalg=", 8) == 0) { 1475 if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1) 1476 fatal("Unsupported hash algorithm"); 1477 } else { 1478 error("Invalid option \"%s\"", opts[i]); 1479 return SSH_ERR_INVALID_ARGUMENT; 1480 } 1481 } 1482 if (fname == NULL) 1483 fatal_f("no filename"); 1484 if (stat(fname, &st) == -1) { 1485 if (errno == ENOENT) 1486 return 0; 1487 fatal("%s: %s", fname, strerror(errno)); 1488 } 1489 if ((r = sshkey_load_public(fname, &public, &comment)) != 0) 1490 fatal_r(r, "Failed to read v2 public key from \"%s\"", fname); 1491 export_dns_rr(hname, public, stdout, print_generic, hash); 1492 sshkey_free(public); 1493 free(comment); 1494 return 1; 1495 } 1496 1497 /* 1498 * Change the comment of a private key file. 1499 */ 1500 __dead static void 1501 do_change_comment(struct passwd *pw, const char *identity_comment) 1502 { 1503 char new_comment[1024], *comment, *passphrase; 1504 struct sshkey *private; 1505 struct sshkey *public; 1506 struct stat st; 1507 int r; 1508 1509 if (!have_identity) 1510 ask_filename(pw, "Enter file in which the key is"); 1511 if (stat(identity_file, &st) == -1) 1512 fatal("%s: %s", identity_file, strerror(errno)); 1513 if ((r = sshkey_load_private(identity_file, "", 1514 &private, &comment)) == 0) 1515 passphrase = xstrdup(""); 1516 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) 1517 fatal_r(r, "Cannot load private key \"%s\"", identity_file); 1518 else { 1519 if (identity_passphrase) 1520 passphrase = xstrdup(identity_passphrase); 1521 else if (identity_new_passphrase) 1522 passphrase = xstrdup(identity_new_passphrase); 1523 else 1524 passphrase = read_passphrase("Enter passphrase: ", 1525 RP_ALLOW_STDIN); 1526 /* Try to load using the passphrase. */ 1527 if ((r = sshkey_load_private(identity_file, passphrase, 1528 &private, &comment)) != 0) { 1529 freezero(passphrase, strlen(passphrase)); 1530 fatal_r(r, "Cannot load private key \"%s\"", 1531 identity_file); 1532 } 1533 } 1534 1535 if (private->type != KEY_ED25519 && private->type != KEY_XMSS && 1536 private_key_format != SSHKEY_PRIVATE_OPENSSH) { 1537 error("Comments are only supported for keys stored in " 1538 "the new format (-o)."); 1539 explicit_bzero(passphrase, strlen(passphrase)); 1540 sshkey_free(private); 1541 exit(1); 1542 } 1543 if (comment) 1544 printf("Old comment: %s\n", comment); 1545 else 1546 printf("No existing comment\n"); 1547 1548 if (identity_comment) { 1549 strlcpy(new_comment, identity_comment, sizeof(new_comment)); 1550 } else { 1551 printf("New comment: "); 1552 fflush(stdout); 1553 if (!fgets(new_comment, sizeof(new_comment), stdin)) { 1554 explicit_bzero(passphrase, strlen(passphrase)); 1555 sshkey_free(private); 1556 exit(1); 1557 } 1558 new_comment[strcspn(new_comment, "\n")] = '\0'; 1559 } 1560 if (comment != NULL && strcmp(comment, new_comment) == 0) { 1561 printf("No change to comment\n"); 1562 free(passphrase); 1563 sshkey_free(private); 1564 free(comment); 1565 exit(0); 1566 } 1567 1568 /* Save the file using the new passphrase. */ 1569 if ((r = sshkey_save_private(private, identity_file, passphrase, 1570 new_comment, private_key_format, openssh_format_cipher, 1571 rounds)) != 0) { 1572 error_r(r, "Saving key \"%s\" failed", identity_file); 1573 freezero(passphrase, strlen(passphrase)); 1574 sshkey_free(private); 1575 free(comment); 1576 exit(1); 1577 } 1578 freezero(passphrase, strlen(passphrase)); 1579 if ((r = sshkey_from_private(private, &public)) != 0) 1580 fatal_fr(r, "sshkey_from_private"); 1581 sshkey_free(private); 1582 1583 strlcat(identity_file, ".pub", sizeof(identity_file)); 1584 if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0) 1585 fatal_r(r, "Unable to save public key to %s", identity_file); 1586 sshkey_free(public); 1587 free(comment); 1588 1589 if (strlen(new_comment) > 0) 1590 printf("Comment '%s' applied\n", new_comment); 1591 else 1592 printf("Comment removed\n"); 1593 1594 exit(0); 1595 } 1596 1597 static void 1598 cert_ext_add(const char *key, const char *value, int iscrit) 1599 { 1600 cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext)); 1601 cert_ext[ncert_ext].key = xstrdup(key); 1602 cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value); 1603 cert_ext[ncert_ext].crit = iscrit; 1604 ncert_ext++; 1605 } 1606 1607 /* qsort(3) comparison function for certificate extensions */ 1608 static int 1609 cert_ext_cmp(const void *_a, const void *_b) 1610 { 1611 const struct cert_ext *a = (const struct cert_ext *)_a; 1612 const struct cert_ext *b = (const struct cert_ext *)_b; 1613 int r; 1614 1615 if (a->crit != b->crit) 1616 return (a->crit < b->crit) ? -1 : 1; 1617 if ((r = strcmp(a->key, b->key)) != 0) 1618 return r; 1619 if ((a->val == NULL) != (b->val == NULL)) 1620 return (a->val == NULL) ? -1 : 1; 1621 if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0) 1622 return r; 1623 return 0; 1624 } 1625 1626 #define OPTIONS_CRITICAL 1 1627 #define OPTIONS_EXTENSIONS 2 1628 static void 1629 prepare_options_buf(struct sshbuf *c, int which) 1630 { 1631 struct sshbuf *b; 1632 size_t i; 1633 int r; 1634 const struct cert_ext *ext; 1635 1636 if ((b = sshbuf_new()) == NULL) 1637 fatal_f("sshbuf_new failed"); 1638 sshbuf_reset(c); 1639 for (i = 0; i < ncert_ext; i++) { 1640 ext = &cert_ext[i]; 1641 if ((ext->crit && (which & OPTIONS_EXTENSIONS)) || 1642 (!ext->crit && (which & OPTIONS_CRITICAL))) 1643 continue; 1644 if (ext->val == NULL) { 1645 /* flag option */ 1646 debug3_f("%s", ext->key); 1647 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 || 1648 (r = sshbuf_put_string(c, NULL, 0)) != 0) 1649 fatal_fr(r, "prepare flag"); 1650 } else { 1651 /* key/value option */ 1652 debug3_f("%s=%s", ext->key, ext->val); 1653 sshbuf_reset(b); 1654 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 || 1655 (r = sshbuf_put_cstring(b, ext->val)) != 0 || 1656 (r = sshbuf_put_stringb(c, b)) != 0) 1657 fatal_fr(r, "prepare k/v"); 1658 } 1659 } 1660 sshbuf_free(b); 1661 } 1662 1663 static void 1664 finalise_cert_exts(void) 1665 { 1666 /* critical options */ 1667 if (certflags_command != NULL) 1668 cert_ext_add("force-command", certflags_command, 1); 1669 if (certflags_src_addr != NULL) 1670 cert_ext_add("source-address", certflags_src_addr, 1); 1671 if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0) 1672 cert_ext_add("verify-required", NULL, 1); 1673 /* extensions */ 1674 if ((certflags_flags & CERTOPT_X_FWD) != 0) 1675 cert_ext_add("permit-X11-forwarding", NULL, 0); 1676 if ((certflags_flags & CERTOPT_AGENT_FWD) != 0) 1677 cert_ext_add("permit-agent-forwarding", NULL, 0); 1678 if ((certflags_flags & CERTOPT_PORT_FWD) != 0) 1679 cert_ext_add("permit-port-forwarding", NULL, 0); 1680 if ((certflags_flags & CERTOPT_PTY) != 0) 1681 cert_ext_add("permit-pty", NULL, 0); 1682 if ((certflags_flags & CERTOPT_USER_RC) != 0) 1683 cert_ext_add("permit-user-rc", NULL, 0); 1684 if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0) 1685 cert_ext_add("no-touch-required", NULL, 0); 1686 /* order lexically by key */ 1687 if (ncert_ext > 0) 1688 qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp); 1689 } 1690 1691 static struct sshkey * 1692 load_pkcs11_key(char *path) 1693 { 1694 #ifdef ENABLE_PKCS11 1695 struct sshkey **keys = NULL, *public, *private = NULL; 1696 int r, i, nkeys; 1697 1698 if ((r = sshkey_load_public(path, &public, NULL)) != 0) 1699 fatal_r(r, "Couldn't load CA public key \"%s\"", path); 1700 1701 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, 1702 &keys, NULL); 1703 debug3_f("%d keys", nkeys); 1704 if (nkeys <= 0) 1705 fatal("cannot read public key from pkcs11"); 1706 for (i = 0; i < nkeys; i++) { 1707 if (sshkey_equal_public(public, keys[i])) { 1708 private = keys[i]; 1709 continue; 1710 } 1711 sshkey_free(keys[i]); 1712 } 1713 free(keys); 1714 sshkey_free(public); 1715 return private; 1716 #else 1717 fatal("no pkcs11 support"); 1718 #endif /* ENABLE_PKCS11 */ 1719 } 1720 1721 /* Signer for sshkey_certify_custom that uses the agent */ 1722 static int 1723 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp, 1724 const u_char *data, size_t datalen, 1725 const char *alg, const char *provider, const char *pin, 1726 u_int compat, void *ctx) 1727 { 1728 int *agent_fdp = (int *)ctx; 1729 1730 return ssh_agent_sign(*agent_fdp, key, sigp, lenp, 1731 data, datalen, alg, compat); 1732 } 1733 1734 __dead static void 1735 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent, 1736 unsigned long long cert_serial, int cert_serial_autoinc, 1737 int argc, char **argv) 1738 { 1739 int r, i, found, agent_fd = -1; 1740 u_int n; 1741 struct sshkey *ca, *public; 1742 char valid[64], *otmp, *tmp, *cp, *out, *comment; 1743 char *ca_fp = NULL, **plist = NULL, *pin = NULL; 1744 struct ssh_identitylist *agent_ids; 1745 size_t j; 1746 struct notifier_ctx *notifier = NULL; 1747 1748 #ifdef ENABLE_PKCS11 1749 pkcs11_init(1); 1750 #endif 1751 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid); 1752 if (pkcs11provider != NULL) { 1753 /* If a PKCS#11 token was specified then try to use it */ 1754 if ((ca = load_pkcs11_key(tmp)) == NULL) 1755 fatal("No PKCS#11 key matching %s found", ca_key_path); 1756 } else if (prefer_agent) { 1757 /* 1758 * Agent signature requested. Try to use agent after making 1759 * sure the public key specified is actually present in the 1760 * agent. 1761 */ 1762 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0) 1763 fatal_r(r, "Cannot load CA public key %s", tmp); 1764 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) 1765 fatal_r(r, "Cannot use public key for CA signature"); 1766 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0) 1767 fatal_r(r, "Retrieve agent key list"); 1768 found = 0; 1769 for (j = 0; j < agent_ids->nkeys; j++) { 1770 if (sshkey_equal(ca, agent_ids->keys[j])) { 1771 found = 1; 1772 break; 1773 } 1774 } 1775 if (!found) 1776 fatal("CA key %s not found in agent", tmp); 1777 ssh_free_identitylist(agent_ids); 1778 ca->flags |= SSHKEY_FLAG_EXT; 1779 } else { 1780 /* CA key is assumed to be a private key on the filesystem */ 1781 ca = load_identity(tmp, NULL); 1782 if (sshkey_is_sk(ca) && 1783 (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) { 1784 if ((pin = read_passphrase("Enter PIN for CA key: ", 1785 RP_ALLOW_STDIN)) == NULL) 1786 fatal_f("couldn't read PIN"); 1787 } 1788 } 1789 free(tmp); 1790 1791 if (key_type_name != NULL) { 1792 if (sshkey_type_from_name(key_type_name) != ca->type) { 1793 fatal("CA key type %s doesn't match specified %s", 1794 sshkey_ssh_name(ca), key_type_name); 1795 } 1796 } else if (ca->type == KEY_RSA) { 1797 /* Default to a good signature algorithm */ 1798 key_type_name = "rsa-sha2-512"; 1799 } 1800 ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT); 1801 1802 finalise_cert_exts(); 1803 for (i = 0; i < argc; i++) { 1804 /* Split list of principals */ 1805 n = 0; 1806 if (cert_principals != NULL) { 1807 otmp = tmp = xstrdup(cert_principals); 1808 plist = NULL; 1809 for (; (cp = strsep(&tmp, ",")) != NULL; n++) { 1810 plist = xreallocarray(plist, n + 1, sizeof(*plist)); 1811 if (*(plist[n] = xstrdup(cp)) == '\0') 1812 fatal("Empty principal name"); 1813 } 1814 free(otmp); 1815 } 1816 if (n > SSHKEY_CERT_MAX_PRINCIPALS) 1817 fatal("Too many certificate principals specified"); 1818 1819 tmp = tilde_expand_filename(argv[i], pw->pw_uid); 1820 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0) 1821 fatal_r(r, "load pubkey \"%s\"", tmp); 1822 if (sshkey_is_cert(public)) 1823 fatal_f("key \"%s\" type %s cannot be certified", 1824 tmp, sshkey_type(public)); 1825 1826 /* Prepare certificate to sign */ 1827 if ((r = sshkey_to_certified(public)) != 0) 1828 fatal_r(r, "Could not upgrade key %s to certificate", tmp); 1829 public->cert->type = cert_key_type; 1830 public->cert->serial = (u_int64_t)cert_serial; 1831 public->cert->key_id = xstrdup(cert_key_id); 1832 public->cert->nprincipals = n; 1833 public->cert->principals = plist; 1834 public->cert->valid_after = cert_valid_from; 1835 public->cert->valid_before = cert_valid_to; 1836 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL); 1837 prepare_options_buf(public->cert->extensions, 1838 OPTIONS_EXTENSIONS); 1839 if ((r = sshkey_from_private(ca, 1840 &public->cert->signature_key)) != 0) 1841 fatal_r(r, "sshkey_from_private (ca key)"); 1842 1843 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) { 1844 if ((r = sshkey_certify_custom(public, ca, 1845 key_type_name, sk_provider, NULL, agent_signer, 1846 &agent_fd)) != 0) 1847 fatal_r(r, "Couldn't certify %s via agent", tmp); 1848 } else { 1849 if (sshkey_is_sk(ca) && 1850 (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) { 1851 notifier = notify_start(0, 1852 "Confirm user presence for key %s %s", 1853 sshkey_type(ca), ca_fp); 1854 } 1855 r = sshkey_certify(public, ca, key_type_name, 1856 sk_provider, pin); 1857 notify_complete(notifier, "User presence confirmed"); 1858 if (r != 0) 1859 fatal_r(r, "Couldn't certify key %s", tmp); 1860 } 1861 1862 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0) 1863 *cp = '\0'; 1864 xasprintf(&out, "%s-cert.pub", tmp); 1865 free(tmp); 1866 1867 if ((r = sshkey_save_public(public, out, comment)) != 0) { 1868 fatal_r(r, "Unable to save public key to %s", 1869 identity_file); 1870 } 1871 1872 if (!quiet) { 1873 sshkey_format_cert_validity(public->cert, 1874 valid, sizeof(valid)); 1875 logit("Signed %s key %s: id \"%s\" serial %llu%s%s " 1876 "valid %s", sshkey_cert_type(public), 1877 out, public->cert->key_id, 1878 (unsigned long long)public->cert->serial, 1879 cert_principals != NULL ? " for " : "", 1880 cert_principals != NULL ? cert_principals : "", 1881 valid); 1882 } 1883 1884 sshkey_free(public); 1885 free(out); 1886 if (cert_serial_autoinc) 1887 cert_serial++; 1888 } 1889 if (pin != NULL) 1890 freezero(pin, strlen(pin)); 1891 free(ca_fp); 1892 #ifdef ENABLE_PKCS11 1893 pkcs11_terminate(); 1894 #endif 1895 exit(0); 1896 } 1897 1898 static u_int64_t 1899 parse_relative_time(const char *s, time_t now) 1900 { 1901 int64_t mul, secs; 1902 1903 mul = *s == '-' ? -1 : 1; 1904 1905 if ((secs = convtime(s + 1)) == -1) 1906 fatal("Invalid relative certificate time %s", s); 1907 if (mul == -1 && secs > now) 1908 fatal("Certificate time %s cannot be represented", s); 1909 return now + (u_int64_t)(secs * mul); 1910 } 1911 1912 static void 1913 parse_hex_u64(const char *s, uint64_t *up) 1914 { 1915 char *ep; 1916 unsigned long long ull; 1917 1918 errno = 0; 1919 ull = strtoull(s, &ep, 16); 1920 if (*s == '\0' || *ep != '\0') 1921 fatal("Invalid certificate time: not a number"); 1922 if (errno == ERANGE && ull == ULONG_MAX) 1923 fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time"); 1924 *up = (uint64_t)ull; 1925 } 1926 1927 static void 1928 parse_cert_times(char *timespec) 1929 { 1930 char *from, *to; 1931 time_t now = time(NULL); 1932 int64_t secs; 1933 1934 /* +timespec relative to now */ 1935 if (*timespec == '+' && strchr(timespec, ':') == NULL) { 1936 if ((secs = convtime(timespec + 1)) == -1) 1937 fatal("Invalid relative certificate life %s", timespec); 1938 cert_valid_to = now + secs; 1939 /* 1940 * Backdate certificate one minute to avoid problems on hosts 1941 * with poorly-synchronised clocks. 1942 */ 1943 cert_valid_from = ((now - 59)/ 60) * 60; 1944 return; 1945 } 1946 1947 /* 1948 * from:to, where 1949 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always" 1950 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever" 1951 */ 1952 from = xstrdup(timespec); 1953 to = strchr(from, ':'); 1954 if (to == NULL || from == to || *(to + 1) == '\0') 1955 fatal("Invalid certificate life specification %s", timespec); 1956 *to++ = '\0'; 1957 1958 if (*from == '-' || *from == '+') 1959 cert_valid_from = parse_relative_time(from, now); 1960 else if (strcmp(from, "always") == 0) 1961 cert_valid_from = 0; 1962 else if (strncmp(from, "0x", 2) == 0) 1963 parse_hex_u64(from, &cert_valid_from); 1964 else if (parse_absolute_time(from, &cert_valid_from) != 0) 1965 fatal("Invalid from time \"%s\"", from); 1966 1967 if (*to == '-' || *to == '+') 1968 cert_valid_to = parse_relative_time(to, now); 1969 else if (strcmp(to, "forever") == 0) 1970 cert_valid_to = ~(u_int64_t)0; 1971 else if (strncmp(to, "0x", 2) == 0) 1972 parse_hex_u64(to, &cert_valid_to); 1973 else if (parse_absolute_time(to, &cert_valid_to) != 0) 1974 fatal("Invalid to time \"%s\"", to); 1975 1976 if (cert_valid_to <= cert_valid_from) 1977 fatal("Empty certificate validity interval"); 1978 free(from); 1979 } 1980 1981 static void 1982 add_cert_option(char *opt) 1983 { 1984 char *val, *cp; 1985 int iscrit = 0; 1986 1987 if (strcasecmp(opt, "clear") == 0) 1988 certflags_flags = 0; 1989 else if (strcasecmp(opt, "no-x11-forwarding") == 0) 1990 certflags_flags &= ~CERTOPT_X_FWD; 1991 else if (strcasecmp(opt, "permit-x11-forwarding") == 0) 1992 certflags_flags |= CERTOPT_X_FWD; 1993 else if (strcasecmp(opt, "no-agent-forwarding") == 0) 1994 certflags_flags &= ~CERTOPT_AGENT_FWD; 1995 else if (strcasecmp(opt, "permit-agent-forwarding") == 0) 1996 certflags_flags |= CERTOPT_AGENT_FWD; 1997 else if (strcasecmp(opt, "no-port-forwarding") == 0) 1998 certflags_flags &= ~CERTOPT_PORT_FWD; 1999 else if (strcasecmp(opt, "permit-port-forwarding") == 0) 2000 certflags_flags |= CERTOPT_PORT_FWD; 2001 else if (strcasecmp(opt, "no-pty") == 0) 2002 certflags_flags &= ~CERTOPT_PTY; 2003 else if (strcasecmp(opt, "permit-pty") == 0) 2004 certflags_flags |= CERTOPT_PTY; 2005 else if (strcasecmp(opt, "no-user-rc") == 0) 2006 certflags_flags &= ~CERTOPT_USER_RC; 2007 else if (strcasecmp(opt, "permit-user-rc") == 0) 2008 certflags_flags |= CERTOPT_USER_RC; 2009 else if (strcasecmp(opt, "touch-required") == 0) 2010 certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE; 2011 else if (strcasecmp(opt, "no-touch-required") == 0) 2012 certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE; 2013 else if (strcasecmp(opt, "no-verify-required") == 0) 2014 certflags_flags &= ~CERTOPT_REQUIRE_VERIFY; 2015 else if (strcasecmp(opt, "verify-required") == 0) 2016 certflags_flags |= CERTOPT_REQUIRE_VERIFY; 2017 else if (strncasecmp(opt, "force-command=", 14) == 0) { 2018 val = opt + 14; 2019 if (*val == '\0') 2020 fatal("Empty force-command option"); 2021 if (certflags_command != NULL) 2022 fatal("force-command already specified"); 2023 certflags_command = xstrdup(val); 2024 } else if (strncasecmp(opt, "source-address=", 15) == 0) { 2025 val = opt + 15; 2026 if (*val == '\0') 2027 fatal("Empty source-address option"); 2028 if (certflags_src_addr != NULL) 2029 fatal("source-address already specified"); 2030 if (addr_match_cidr_list(NULL, val) != 0) 2031 fatal("Invalid source-address list"); 2032 certflags_src_addr = xstrdup(val); 2033 } else if (strncasecmp(opt, "extension:", 10) == 0 || 2034 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) { 2035 val = xstrdup(strchr(opt, ':') + 1); 2036 if ((cp = strchr(val, '=')) != NULL) 2037 *cp++ = '\0'; 2038 cert_ext_add(val, cp, iscrit); 2039 free(val); 2040 } else 2041 fatal("Unsupported certificate option \"%s\"", opt); 2042 } 2043 2044 static void 2045 show_options(struct sshbuf *optbuf, int in_critical) 2046 { 2047 char *name, *arg, *hex; 2048 struct sshbuf *options, *option = NULL; 2049 int r; 2050 2051 if ((options = sshbuf_fromb(optbuf)) == NULL) 2052 fatal_f("sshbuf_fromb failed"); 2053 while (sshbuf_len(options) != 0) { 2054 sshbuf_free(option); 2055 option = NULL; 2056 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 || 2057 (r = sshbuf_froms(options, &option)) != 0) 2058 fatal_fr(r, "parse option"); 2059 printf(" %s", name); 2060 if (!in_critical && 2061 (strcmp(name, "permit-X11-forwarding") == 0 || 2062 strcmp(name, "permit-agent-forwarding") == 0 || 2063 strcmp(name, "permit-port-forwarding") == 0 || 2064 strcmp(name, "permit-pty") == 0 || 2065 strcmp(name, "permit-user-rc") == 0 || 2066 strcmp(name, "no-touch-required") == 0)) { 2067 printf("\n"); 2068 } else if (in_critical && 2069 (strcmp(name, "force-command") == 0 || 2070 strcmp(name, "source-address") == 0)) { 2071 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0) 2072 fatal_fr(r, "parse critical"); 2073 printf(" %s\n", arg); 2074 free(arg); 2075 } else if (in_critical && 2076 strcmp(name, "verify-required") == 0) { 2077 printf("\n"); 2078 } else if (sshbuf_len(option) > 0) { 2079 hex = sshbuf_dtob16(option); 2080 printf(" UNKNOWN OPTION: %s (len %zu)\n", 2081 hex, sshbuf_len(option)); 2082 sshbuf_reset(option); 2083 free(hex); 2084 } else 2085 printf(" UNKNOWN FLAG OPTION\n"); 2086 free(name); 2087 if (sshbuf_len(option) != 0) 2088 fatal("Option corrupt: extra data at end"); 2089 } 2090 sshbuf_free(option); 2091 sshbuf_free(options); 2092 } 2093 2094 static void 2095 print_cert(struct sshkey *key) 2096 { 2097 char valid[64], *key_fp, *ca_fp; 2098 u_int i; 2099 2100 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT); 2101 ca_fp = sshkey_fingerprint(key->cert->signature_key, 2102 fingerprint_hash, SSH_FP_DEFAULT); 2103 if (key_fp == NULL || ca_fp == NULL) 2104 fatal_f("sshkey_fingerprint fail"); 2105 sshkey_format_cert_validity(key->cert, valid, sizeof(valid)); 2106 2107 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key), 2108 sshkey_cert_type(key)); 2109 printf(" Public key: %s %s\n", sshkey_type(key), key_fp); 2110 printf(" Signing CA: %s %s (using %s)\n", 2111 sshkey_type(key->cert->signature_key), ca_fp, 2112 key->cert->signature_type); 2113 printf(" Key ID: \"%s\"\n", key->cert->key_id); 2114 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial); 2115 printf(" Valid: %s\n", valid); 2116 printf(" Principals: "); 2117 if (key->cert->nprincipals == 0) 2118 printf("(none)\n"); 2119 else { 2120 for (i = 0; i < key->cert->nprincipals; i++) 2121 printf("\n %s", 2122 key->cert->principals[i]); 2123 printf("\n"); 2124 } 2125 printf(" Critical Options: "); 2126 if (sshbuf_len(key->cert->critical) == 0) 2127 printf("(none)\n"); 2128 else { 2129 printf("\n"); 2130 show_options(key->cert->critical, 1); 2131 } 2132 printf(" Extensions: "); 2133 if (sshbuf_len(key->cert->extensions) == 0) 2134 printf("(none)\n"); 2135 else { 2136 printf("\n"); 2137 show_options(key->cert->extensions, 0); 2138 } 2139 } 2140 2141 __dead static void 2142 do_show_cert(struct passwd *pw) 2143 { 2144 struct sshkey *key = NULL; 2145 struct stat st; 2146 int r, is_stdin = 0, ok = 0; 2147 FILE *f; 2148 char *cp, *line = NULL; 2149 const char *path; 2150 size_t linesize = 0; 2151 u_long lnum = 0; 2152 2153 if (!have_identity) 2154 ask_filename(pw, "Enter file in which the key is"); 2155 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1) 2156 fatal("%s: %s: %s", __progname, identity_file, strerror(errno)); 2157 2158 path = identity_file; 2159 if (strcmp(path, "-") == 0) { 2160 f = stdin; 2161 path = "(stdin)"; 2162 is_stdin = 1; 2163 } else if ((f = fopen(identity_file, "r")) == NULL) 2164 fatal("fopen %s: %s", identity_file, strerror(errno)); 2165 2166 while (getline(&line, &linesize, f) != -1) { 2167 lnum++; 2168 sshkey_free(key); 2169 key = NULL; 2170 /* Trim leading space and comments */ 2171 cp = line + strspn(line, " \t"); 2172 if (*cp == '#' || *cp == '\0') 2173 continue; 2174 if ((key = sshkey_new(KEY_UNSPEC)) == NULL) 2175 fatal("sshkey_new"); 2176 if ((r = sshkey_read(key, &cp)) != 0) { 2177 error_r(r, "%s:%lu: invalid key", path, lnum); 2178 continue; 2179 } 2180 if (!sshkey_is_cert(key)) { 2181 error("%s:%lu is not a certificate", path, lnum); 2182 continue; 2183 } 2184 ok = 1; 2185 if (!is_stdin && lnum == 1) 2186 printf("%s:\n", path); 2187 else 2188 printf("%s:%lu:\n", path, lnum); 2189 print_cert(key); 2190 } 2191 free(line); 2192 sshkey_free(key); 2193 fclose(f); 2194 exit(ok ? 0 : 1); 2195 } 2196 2197 static void 2198 load_krl(const char *path, struct ssh_krl **krlp) 2199 { 2200 struct sshbuf *krlbuf; 2201 int r; 2202 2203 if ((r = sshbuf_load_file(path, &krlbuf)) != 0) 2204 fatal_r(r, "Unable to load KRL %s", path); 2205 /* XXX check sigs */ 2206 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 || 2207 *krlp == NULL) 2208 fatal_r(r, "Invalid KRL file %s", path); 2209 sshbuf_free(krlbuf); 2210 } 2211 2212 static void 2213 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp, 2214 const char *file, u_long lnum) 2215 { 2216 char *tmp; 2217 size_t tlen; 2218 struct sshbuf *b; 2219 int r; 2220 2221 if (strncmp(cp, "SHA256:", 7) != 0) 2222 fatal("%s:%lu: unsupported hash algorithm", file, lnum); 2223 cp += 7; 2224 2225 /* 2226 * OpenSSH base64 hashes omit trailing '=' 2227 * characters; put them back for decode. 2228 */ 2229 tlen = strlen(cp); 2230 tmp = xmalloc(tlen + 4 + 1); 2231 strlcpy(tmp, cp, tlen + 1); 2232 while ((tlen % 4) != 0) { 2233 tmp[tlen++] = '='; 2234 tmp[tlen] = '\0'; 2235 } 2236 if ((b = sshbuf_new()) == NULL) 2237 fatal_f("sshbuf_new failed"); 2238 if ((r = sshbuf_b64tod(b, tmp)) != 0) 2239 fatal_r(r, "%s:%lu: decode hash failed", file, lnum); 2240 free(tmp); 2241 *lenp = sshbuf_len(b); 2242 *blobp = xmalloc(*lenp); 2243 memcpy(*blobp, sshbuf_ptr(b), *lenp); 2244 sshbuf_free(b); 2245 } 2246 2247 static void 2248 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca, 2249 const struct sshkey *ca, struct ssh_krl *krl) 2250 { 2251 struct sshkey *key = NULL; 2252 u_long lnum = 0; 2253 char *path, *cp, *ep, *line = NULL; 2254 u_char *blob = NULL; 2255 size_t blen = 0, linesize = 0; 2256 unsigned long long serial, serial2; 2257 int i, was_explicit_key, was_sha1, was_sha256, was_hash, r; 2258 FILE *krl_spec; 2259 2260 path = tilde_expand_filename(file, pw->pw_uid); 2261 if (strcmp(path, "-") == 0) { 2262 krl_spec = stdin; 2263 free(path); 2264 path = xstrdup("(standard input)"); 2265 } else if ((krl_spec = fopen(path, "r")) == NULL) 2266 fatal("fopen %s: %s", path, strerror(errno)); 2267 2268 if (!quiet) 2269 printf("Revoking from %s\n", path); 2270 while (getline(&line, &linesize, krl_spec) != -1) { 2271 lnum++; 2272 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0; 2273 cp = line + strspn(line, " \t"); 2274 /* Trim trailing space, comments and strip \n */ 2275 for (i = 0, r = -1; cp[i] != '\0'; i++) { 2276 if (cp[i] == '#' || cp[i] == '\n') { 2277 cp[i] = '\0'; 2278 break; 2279 } 2280 if (cp[i] == ' ' || cp[i] == '\t') { 2281 /* Remember the start of a span of whitespace */ 2282 if (r == -1) 2283 r = i; 2284 } else 2285 r = -1; 2286 } 2287 if (r != -1) 2288 cp[r] = '\0'; 2289 if (*cp == '\0') 2290 continue; 2291 if (strncasecmp(cp, "serial:", 7) == 0) { 2292 if (ca == NULL && !wild_ca) { 2293 fatal("revoking certificates by serial number " 2294 "requires specification of a CA key"); 2295 } 2296 cp += 7; 2297 cp = cp + strspn(cp, " \t"); 2298 errno = 0; 2299 serial = strtoull(cp, &ep, 0); 2300 if (*cp == '\0' || (*ep != '\0' && *ep != '-')) 2301 fatal("%s:%lu: invalid serial \"%s\"", 2302 path, lnum, cp); 2303 if (errno == ERANGE && serial == ULLONG_MAX) 2304 fatal("%s:%lu: serial out of range", 2305 path, lnum); 2306 serial2 = serial; 2307 if (*ep == '-') { 2308 cp = ep + 1; 2309 errno = 0; 2310 serial2 = strtoull(cp, &ep, 0); 2311 if (*cp == '\0' || *ep != '\0') 2312 fatal("%s:%lu: invalid serial \"%s\"", 2313 path, lnum, cp); 2314 if (errno == ERANGE && serial2 == ULLONG_MAX) 2315 fatal("%s:%lu: serial out of range", 2316 path, lnum); 2317 if (serial2 <= serial) 2318 fatal("%s:%lu: invalid serial range " 2319 "%llu:%llu", path, lnum, 2320 (unsigned long long)serial, 2321 (unsigned long long)serial2); 2322 } 2323 if (ssh_krl_revoke_cert_by_serial_range(krl, 2324 ca, serial, serial2) != 0) { 2325 fatal_f("revoke serial failed"); 2326 } 2327 } else if (strncasecmp(cp, "id:", 3) == 0) { 2328 if (ca == NULL && !wild_ca) { 2329 fatal("revoking certificates by key ID " 2330 "requires specification of a CA key"); 2331 } 2332 cp += 3; 2333 cp = cp + strspn(cp, " \t"); 2334 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0) 2335 fatal_f("revoke key ID failed"); 2336 } else if (strncasecmp(cp, "hash:", 5) == 0) { 2337 cp += 5; 2338 cp = cp + strspn(cp, " \t"); 2339 hash_to_blob(cp, &blob, &blen, file, lnum); 2340 r = ssh_krl_revoke_key_sha256(krl, blob, blen); 2341 if (r != 0) 2342 fatal_fr(r, "revoke key failed"); 2343 } else { 2344 if (strncasecmp(cp, "key:", 4) == 0) { 2345 cp += 4; 2346 cp = cp + strspn(cp, " \t"); 2347 was_explicit_key = 1; 2348 } else if (strncasecmp(cp, "sha1:", 5) == 0) { 2349 cp += 5; 2350 cp = cp + strspn(cp, " \t"); 2351 was_sha1 = 1; 2352 } else if (strncasecmp(cp, "sha256:", 7) == 0) { 2353 cp += 7; 2354 cp = cp + strspn(cp, " \t"); 2355 was_sha256 = 1; 2356 /* 2357 * Just try to process the line as a key. 2358 * Parsing will fail if it isn't. 2359 */ 2360 } 2361 if ((key = sshkey_new(KEY_UNSPEC)) == NULL) 2362 fatal("sshkey_new"); 2363 if ((r = sshkey_read(key, &cp)) != 0) 2364 fatal_r(r, "%s:%lu: invalid key", path, lnum); 2365 if (was_explicit_key) 2366 r = ssh_krl_revoke_key_explicit(krl, key); 2367 else if (was_sha1) { 2368 if (sshkey_fingerprint_raw(key, 2369 SSH_DIGEST_SHA1, &blob, &blen) != 0) { 2370 fatal("%s:%lu: fingerprint failed", 2371 file, lnum); 2372 } 2373 r = ssh_krl_revoke_key_sha1(krl, blob, blen); 2374 } else if (was_sha256) { 2375 if (sshkey_fingerprint_raw(key, 2376 SSH_DIGEST_SHA256, &blob, &blen) != 0) { 2377 fatal("%s:%lu: fingerprint failed", 2378 file, lnum); 2379 } 2380 r = ssh_krl_revoke_key_sha256(krl, blob, blen); 2381 } else 2382 r = ssh_krl_revoke_key(krl, key); 2383 if (r != 0) 2384 fatal_fr(r, "revoke key failed"); 2385 freezero(blob, blen); 2386 blob = NULL; 2387 blen = 0; 2388 sshkey_free(key); 2389 } 2390 } 2391 if (strcmp(path, "-") != 0) 2392 fclose(krl_spec); 2393 free(line); 2394 free(path); 2395 } 2396 2397 static void 2398 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path, 2399 unsigned long long krl_version, const char *krl_comment, 2400 int argc, char **argv) 2401 { 2402 struct ssh_krl *krl; 2403 struct stat sb; 2404 struct sshkey *ca = NULL; 2405 int i, r, wild_ca = 0; 2406 char *tmp; 2407 struct sshbuf *kbuf; 2408 2409 if (*identity_file == '\0') 2410 fatal("KRL generation requires an output file"); 2411 if (stat(identity_file, &sb) == -1) { 2412 if (errno != ENOENT) 2413 fatal("Cannot access KRL \"%s\": %s", 2414 identity_file, strerror(errno)); 2415 if (updating) 2416 fatal("KRL \"%s\" does not exist", identity_file); 2417 } 2418 if (ca_key_path != NULL) { 2419 if (strcasecmp(ca_key_path, "none") == 0) 2420 wild_ca = 1; 2421 else { 2422 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid); 2423 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0) 2424 fatal_r(r, "Cannot load CA public key %s", tmp); 2425 free(tmp); 2426 } 2427 } 2428 2429 if (updating) 2430 load_krl(identity_file, &krl); 2431 else if ((krl = ssh_krl_init()) == NULL) 2432 fatal("couldn't create KRL"); 2433 2434 if (krl_version != 0) 2435 ssh_krl_set_version(krl, krl_version); 2436 if (krl_comment != NULL) 2437 ssh_krl_set_comment(krl, krl_comment); 2438 2439 for (i = 0; i < argc; i++) 2440 update_krl_from_file(pw, argv[i], wild_ca, ca, krl); 2441 2442 if ((kbuf = sshbuf_new()) == NULL) 2443 fatal("sshbuf_new failed"); 2444 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0) 2445 fatal("Couldn't generate KRL"); 2446 if ((r = sshbuf_write_file(identity_file, kbuf)) != 0) 2447 fatal("write %s: %s", identity_file, strerror(errno)); 2448 sshbuf_free(kbuf); 2449 ssh_krl_free(krl); 2450 sshkey_free(ca); 2451 } 2452 2453 __dead static void 2454 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv) 2455 { 2456 int i, r, ret = 0; 2457 char *comment; 2458 struct ssh_krl *krl; 2459 struct sshkey *k; 2460 2461 if (*identity_file == '\0') 2462 fatal("KRL checking requires an input file"); 2463 load_krl(identity_file, &krl); 2464 if (print_krl) 2465 krl_dump(krl, stdout); 2466 for (i = 0; i < argc; i++) { 2467 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0) 2468 fatal_r(r, "Cannot load public key %s", argv[i]); 2469 r = ssh_krl_check_key(krl, k); 2470 printf("%s%s%s%s: %s\n", argv[i], 2471 *comment ? " (" : "", comment, *comment ? ")" : "", 2472 r == 0 ? "ok" : "REVOKED"); 2473 if (r != 0) 2474 ret = 1; 2475 sshkey_free(k); 2476 free(comment); 2477 } 2478 ssh_krl_free(krl); 2479 exit(ret); 2480 } 2481 2482 static struct sshkey * 2483 load_sign_key(const char *keypath, const struct sshkey *pubkey) 2484 { 2485 size_t i, slen, plen = strlen(keypath); 2486 char *privpath = xstrdup(keypath); 2487 static const char * const suffixes[] = { "-cert.pub", ".pub", NULL }; 2488 struct sshkey *ret = NULL, *privkey = NULL; 2489 int r, waspub = 0; 2490 struct stat st; 2491 2492 /* 2493 * If passed a public key filename, then try to locate the corresponding 2494 * private key. This lets us specify certificates on the command-line 2495 * and have ssh-keygen find the appropriate private key. 2496 */ 2497 for (i = 0; suffixes[i]; i++) { 2498 slen = strlen(suffixes[i]); 2499 if (plen <= slen || 2500 strcmp(privpath + plen - slen, suffixes[i]) != 0) 2501 continue; 2502 privpath[plen - slen] = '\0'; 2503 debug_f("%s looks like a public key, using private key " 2504 "path %s instead", keypath, privpath); 2505 waspub = 1; 2506 } 2507 if (waspub && stat(privpath, &st) != 0 && errno == ENOENT) 2508 fatal("No private key found for public key \"%s\"", keypath); 2509 if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 && 2510 (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) { 2511 debug_fr(r, "load private key \"%s\"", privpath); 2512 fatal("No private key found for \"%s\"", privpath); 2513 } else if (privkey == NULL) 2514 privkey = load_identity(privpath, NULL); 2515 2516 if (!sshkey_equal_public(pubkey, privkey)) { 2517 error("Public key %s doesn't match private %s", 2518 keypath, privpath); 2519 goto done; 2520 } 2521 if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) { 2522 /* 2523 * Graft the certificate onto the private key to make 2524 * it capable of signing. 2525 */ 2526 if ((r = sshkey_to_certified(privkey)) != 0) { 2527 error_fr(r, "sshkey_to_certified"); 2528 goto done; 2529 } 2530 if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) { 2531 error_fr(r, "sshkey_cert_copy"); 2532 goto done; 2533 } 2534 } 2535 /* success */ 2536 ret = privkey; 2537 privkey = NULL; 2538 done: 2539 sshkey_free(privkey); 2540 free(privpath); 2541 return ret; 2542 } 2543 2544 static int 2545 sign_one(struct sshkey *signkey, const char *filename, int fd, 2546 const char *sig_namespace, const char *hashalg, sshsig_signer *signer, 2547 void *signer_ctx) 2548 { 2549 struct sshbuf *sigbuf = NULL, *abuf = NULL; 2550 int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno; 2551 char *wfile = NULL, *asig = NULL, *fp = NULL; 2552 char *pin = NULL, *prompt = NULL; 2553 2554 if (!quiet) { 2555 if (fd == STDIN_FILENO) 2556 fprintf(stderr, "Signing data on standard input\n"); 2557 else 2558 fprintf(stderr, "Signing file %s\n", filename); 2559 } 2560 if (signer == NULL && sshkey_is_sk(signkey)) { 2561 if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) { 2562 xasprintf(&prompt, "Enter PIN for %s key: ", 2563 sshkey_type(signkey)); 2564 if ((pin = read_passphrase(prompt, 2565 RP_ALLOW_STDIN)) == NULL) 2566 fatal_f("couldn't read PIN"); 2567 } 2568 if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) { 2569 if ((fp = sshkey_fingerprint(signkey, fingerprint_hash, 2570 SSH_FP_DEFAULT)) == NULL) 2571 fatal_f("fingerprint failed"); 2572 fprintf(stderr, "Confirm user presence for key %s %s\n", 2573 sshkey_type(signkey), fp); 2574 free(fp); 2575 } 2576 } 2577 if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin, 2578 fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) { 2579 error_r(r, "Signing %s failed", filename); 2580 goto out; 2581 } 2582 if ((r = sshsig_armor(sigbuf, &abuf)) != 0) { 2583 error_fr(r, "sshsig_armor"); 2584 goto out; 2585 } 2586 if ((asig = sshbuf_dup_string(abuf)) == NULL) { 2587 error_f("buffer error"); 2588 r = SSH_ERR_ALLOC_FAIL; 2589 goto out; 2590 } 2591 2592 if (fd == STDIN_FILENO) { 2593 fputs(asig, stdout); 2594 fflush(stdout); 2595 } else { 2596 xasprintf(&wfile, "%s.sig", filename); 2597 if (confirm_overwrite(wfile)) { 2598 if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC, 2599 0666)) == -1) { 2600 oerrno = errno; 2601 error("Cannot open %s: %s", 2602 wfile, strerror(errno)); 2603 errno = oerrno; 2604 r = SSH_ERR_SYSTEM_ERROR; 2605 goto out; 2606 } 2607 if (atomicio(vwrite, wfd, asig, 2608 strlen(asig)) != strlen(asig)) { 2609 oerrno = errno; 2610 error("Cannot write to %s: %s", 2611 wfile, strerror(errno)); 2612 errno = oerrno; 2613 r = SSH_ERR_SYSTEM_ERROR; 2614 goto out; 2615 } 2616 if (!quiet) { 2617 fprintf(stderr, "Write signature to %s\n", 2618 wfile); 2619 } 2620 } 2621 } 2622 /* success */ 2623 r = 0; 2624 out: 2625 free(wfile); 2626 free(prompt); 2627 free(asig); 2628 if (pin != NULL) 2629 freezero(pin, strlen(pin)); 2630 sshbuf_free(abuf); 2631 sshbuf_free(sigbuf); 2632 if (wfd != -1) 2633 close(wfd); 2634 return r; 2635 } 2636 2637 static int 2638 sig_process_opts(char * const *opts, size_t nopts, char **hashalgp, 2639 uint64_t *verify_timep, int *print_pubkey) 2640 { 2641 size_t i; 2642 time_t now; 2643 2644 if (verify_timep != NULL) 2645 *verify_timep = 0; 2646 if (print_pubkey != NULL) 2647 *print_pubkey = 0; 2648 if (hashalgp != NULL) 2649 *hashalgp = NULL; 2650 for (i = 0; i < nopts; i++) { 2651 if (hashalgp != NULL && 2652 strncasecmp(opts[i], "hashalg=", 8) == 0) { 2653 *hashalgp = xstrdup(opts[i] + 8); 2654 } else if (verify_timep && 2655 strncasecmp(opts[i], "verify-time=", 12) == 0) { 2656 if (parse_absolute_time(opts[i] + 12, 2657 verify_timep) != 0 || *verify_timep == 0) { 2658 error("Invalid \"verify-time\" option"); 2659 return SSH_ERR_INVALID_ARGUMENT; 2660 } 2661 } else if (print_pubkey && 2662 strcasecmp(opts[i], "print-pubkey") == 0) { 2663 *print_pubkey = 1; 2664 } else { 2665 error("Invalid option \"%s\"", opts[i]); 2666 return SSH_ERR_INVALID_ARGUMENT; 2667 } 2668 } 2669 if (verify_timep && *verify_timep == 0) { 2670 if ((now = time(NULL)) < 0) { 2671 error("Time is before epoch"); 2672 return SSH_ERR_INVALID_ARGUMENT; 2673 } 2674 *verify_timep = (uint64_t)now; 2675 } 2676 return 0; 2677 } 2678 2679 2680 static int 2681 sig_sign(const char *keypath, const char *sig_namespace, int require_agent, 2682 int argc, char **argv, char * const *opts, size_t nopts) 2683 { 2684 int i, fd = -1, r, ret = -1; 2685 int agent_fd = -1; 2686 struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL; 2687 sshsig_signer *signer = NULL; 2688 char *hashalg = NULL; 2689 2690 /* Check file arguments. */ 2691 for (i = 0; i < argc; i++) { 2692 if (strcmp(argv[i], "-") != 0) 2693 continue; 2694 if (i > 0 || argc > 1) 2695 fatal("Cannot sign mix of paths and standard input"); 2696 } 2697 2698 if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0) 2699 goto done; /* error already logged */ 2700 2701 if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) { 2702 error_r(r, "Couldn't load public key %s", keypath); 2703 goto done; 2704 } 2705 2706 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { 2707 if (require_agent) 2708 fatal("Couldn't get agent socket"); 2709 debug_r(r, "Couldn't get agent socket"); 2710 } else { 2711 if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0) 2712 signer = agent_signer; 2713 else { 2714 if (require_agent) 2715 fatal("Couldn't find key in agent"); 2716 debug_r(r, "Couldn't find key in agent"); 2717 } 2718 } 2719 2720 if (signer == NULL) { 2721 /* Not using agent - try to load private key */ 2722 if ((privkey = load_sign_key(keypath, pubkey)) == NULL) 2723 goto done; 2724 signkey = privkey; 2725 } else { 2726 /* Will use key in agent */ 2727 signkey = pubkey; 2728 } 2729 2730 if (argc == 0) { 2731 if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO, 2732 sig_namespace, hashalg, signer, &agent_fd)) != 0) 2733 goto done; 2734 } else { 2735 for (i = 0; i < argc; i++) { 2736 if (strcmp(argv[i], "-") == 0) 2737 fd = STDIN_FILENO; 2738 else if ((fd = open(argv[i], O_RDONLY)) == -1) { 2739 error("Cannot open %s for signing: %s", 2740 argv[i], strerror(errno)); 2741 goto done; 2742 } 2743 if ((r = sign_one(signkey, argv[i], fd, sig_namespace, 2744 hashalg, signer, &agent_fd)) != 0) 2745 goto done; 2746 if (fd != STDIN_FILENO) 2747 close(fd); 2748 fd = -1; 2749 } 2750 } 2751 2752 ret = 0; 2753 done: 2754 if (fd != -1 && fd != STDIN_FILENO) 2755 close(fd); 2756 sshkey_free(pubkey); 2757 sshkey_free(privkey); 2758 free(hashalg); 2759 return ret; 2760 } 2761 2762 static int 2763 sig_verify(const char *signature, const char *sig_namespace, 2764 const char *principal, const char *allowed_keys, const char *revoked_keys, 2765 char * const *opts, size_t nopts) 2766 { 2767 int r, ret = -1; 2768 int print_pubkey = 0; 2769 struct sshbuf *sigbuf = NULL, *abuf = NULL; 2770 struct sshkey *sign_key = NULL; 2771 char *fp = NULL; 2772 struct sshkey_sig_details *sig_details = NULL; 2773 uint64_t verify_time = 0; 2774 2775 if (sig_process_opts(opts, nopts, NULL, &verify_time, 2776 &print_pubkey) != 0) 2777 goto done; /* error already logged */ 2778 2779 memset(&sig_details, 0, sizeof(sig_details)); 2780 if ((r = sshbuf_load_file(signature, &abuf)) != 0) { 2781 error_r(r, "Couldn't read signature file"); 2782 goto done; 2783 } 2784 2785 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) { 2786 error_fr(r, "sshsig_armor"); 2787 goto done; 2788 } 2789 if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace, 2790 &sign_key, &sig_details)) != 0) 2791 goto done; /* sshsig_verify() prints error */ 2792 2793 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash, 2794 SSH_FP_DEFAULT)) == NULL) 2795 fatal_f("sshkey_fingerprint failed"); 2796 debug("Valid (unverified) signature from key %s", fp); 2797 if (sig_details != NULL) { 2798 debug2_f("signature details: counter = %u, flags = 0x%02x", 2799 sig_details->sk_counter, sig_details->sk_flags); 2800 } 2801 free(fp); 2802 fp = NULL; 2803 2804 if (revoked_keys != NULL) { 2805 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) { 2806 debug3_fr(r, "sshkey_check_revoked"); 2807 goto done; 2808 } 2809 } 2810 2811 if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys, 2812 sign_key, principal, sig_namespace, verify_time)) != 0) { 2813 debug3_fr(r, "sshsig_check_allowed_keys"); 2814 goto done; 2815 } 2816 /* success */ 2817 ret = 0; 2818 done: 2819 if (!quiet) { 2820 if (ret == 0) { 2821 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash, 2822 SSH_FP_DEFAULT)) == NULL) 2823 fatal_f("sshkey_fingerprint failed"); 2824 if (principal == NULL) { 2825 printf("Good \"%s\" signature with %s key %s\n", 2826 sig_namespace, sshkey_type(sign_key), fp); 2827 2828 } else { 2829 printf("Good \"%s\" signature for %s with %s key %s\n", 2830 sig_namespace, principal, 2831 sshkey_type(sign_key), fp); 2832 } 2833 } else { 2834 printf("Could not verify signature.\n"); 2835 } 2836 } 2837 /* Print the signature key if requested */ 2838 if (ret == 0 && print_pubkey && sign_key != NULL) { 2839 if ((r = sshkey_write(sign_key, stdout)) == 0) 2840 fputc('\n', stdout); 2841 else { 2842 error_r(r, "Could not print public key.\n"); 2843 ret = -1; 2844 } 2845 } 2846 sshbuf_free(sigbuf); 2847 sshbuf_free(abuf); 2848 sshkey_free(sign_key); 2849 sshkey_sig_details_free(sig_details); 2850 free(fp); 2851 return ret; 2852 } 2853 2854 static int 2855 sig_find_principals(const char *signature, const char *allowed_keys, 2856 char * const *opts, size_t nopts) 2857 { 2858 int r, ret = -1; 2859 struct sshbuf *sigbuf = NULL, *abuf = NULL; 2860 struct sshkey *sign_key = NULL; 2861 char *principals = NULL, *cp, *tmp; 2862 uint64_t verify_time = 0; 2863 2864 if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0) 2865 goto done; /* error already logged */ 2866 2867 if ((r = sshbuf_load_file(signature, &abuf)) != 0) { 2868 error_r(r, "Couldn't read signature file"); 2869 goto done; 2870 } 2871 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) { 2872 error_fr(r, "sshsig_armor"); 2873 goto done; 2874 } 2875 if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) { 2876 error_fr(r, "sshsig_get_pubkey"); 2877 goto done; 2878 } 2879 if ((r = sshsig_find_principals(allowed_keys, sign_key, 2880 verify_time, &principals)) != 0) { 2881 if (r != SSH_ERR_KEY_NOT_FOUND) 2882 error_fr(r, "sshsig_find_principal"); 2883 goto done; 2884 } 2885 ret = 0; 2886 done: 2887 if (ret == 0 ) { 2888 /* Emit matching principals one per line */ 2889 tmp = principals; 2890 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0') 2891 puts(cp); 2892 } else { 2893 fprintf(stderr, "No principal matched.\n"); 2894 } 2895 sshbuf_free(sigbuf); 2896 sshbuf_free(abuf); 2897 sshkey_free(sign_key); 2898 free(principals); 2899 return ret; 2900 } 2901 2902 static int 2903 sig_match_principals(const char *allowed_keys, char *principal, 2904 char * const *opts, size_t nopts) 2905 { 2906 int r; 2907 char **principals = NULL; 2908 size_t i, nprincipals = 0; 2909 2910 if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0) 2911 return r; /* error already logged */ 2912 2913 if ((r = sshsig_match_principals(allowed_keys, principal, 2914 &principals, &nprincipals)) != 0) { 2915 debug_f("match: %s", ssh_err(r)); 2916 fprintf(stderr, "No principal matched.\n"); 2917 return r; 2918 } 2919 for (i = 0; i < nprincipals; i++) { 2920 printf("%s\n", principals[i]); 2921 free(principals[i]); 2922 } 2923 free(principals); 2924 2925 return 0; 2926 } 2927 2928 static void 2929 do_moduli_gen(const char *out_file, char **opts, size_t nopts) 2930 { 2931 #ifdef WITH_OPENSSL 2932 /* Moduli generation/screening */ 2933 u_int32_t memory = 0; 2934 BIGNUM *start = NULL; 2935 int moduli_bits = 0; 2936 FILE *out; 2937 size_t i; 2938 const char *errstr; 2939 2940 /* Parse options */ 2941 for (i = 0; i < nopts; i++) { 2942 if (strncmp(opts[i], "memory=", 7) == 0) { 2943 memory = (u_int32_t)strtonum(opts[i]+7, 1, 2944 UINT_MAX, &errstr); 2945 if (errstr) { 2946 fatal("Memory limit is %s: %s", 2947 errstr, opts[i]+7); 2948 } 2949 } else if (strncmp(opts[i], "start=", 6) == 0) { 2950 /* XXX - also compare length against bits */ 2951 if (BN_hex2bn(&start, opts[i]+6) == 0) 2952 fatal("Invalid start point."); 2953 } else if (strncmp(opts[i], "bits=", 5) == 0) { 2954 moduli_bits = (int)strtonum(opts[i]+5, 1, 2955 INT_MAX, &errstr); 2956 if (errstr) { 2957 fatal("Invalid number: %s (%s)", 2958 opts[i]+12, errstr); 2959 } 2960 } else { 2961 fatal("Option \"%s\" is unsupported for moduli " 2962 "generation", opts[i]); 2963 } 2964 } 2965 2966 if ((out = fopen(out_file, "w")) == NULL) { 2967 fatal("Couldn't open modulus candidate file \"%s\": %s", 2968 out_file, strerror(errno)); 2969 } 2970 setvbuf(out, NULL, _IOLBF, 0); 2971 2972 if (moduli_bits == 0) 2973 moduli_bits = DEFAULT_BITS; 2974 if (gen_candidates(out, memory, moduli_bits, start) != 0) 2975 fatal("modulus candidate generation failed"); 2976 #else /* WITH_OPENSSL */ 2977 fatal("Moduli generation is not supported"); 2978 #endif /* WITH_OPENSSL */ 2979 } 2980 2981 static void 2982 do_moduli_screen(const char *out_file, char **opts, size_t nopts) 2983 { 2984 #ifdef WITH_OPENSSL 2985 /* Moduli generation/screening */ 2986 char *checkpoint = NULL; 2987 u_int32_t generator_wanted = 0; 2988 unsigned long start_lineno = 0, lines_to_process = 0; 2989 int prime_tests = 0; 2990 FILE *out, *in = stdin; 2991 size_t i; 2992 const char *errstr; 2993 2994 /* Parse options */ 2995 for (i = 0; i < nopts; i++) { 2996 if (strncmp(opts[i], "lines=", 6) == 0) { 2997 lines_to_process = strtoul(opts[i]+6, NULL, 10); 2998 } else if (strncmp(opts[i], "start-line=", 11) == 0) { 2999 start_lineno = strtoul(opts[i]+11, NULL, 10); 3000 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) { 3001 free(checkpoint); 3002 checkpoint = xstrdup(opts[i]+11); 3003 } else if (strncmp(opts[i], "generator=", 10) == 0) { 3004 generator_wanted = (u_int32_t)strtonum( 3005 opts[i]+10, 1, UINT_MAX, &errstr); 3006 if (errstr != NULL) { 3007 fatal("Generator invalid: %s (%s)", 3008 opts[i]+10, errstr); 3009 } 3010 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) { 3011 prime_tests = (int)strtonum(opts[i]+12, 1, 3012 INT_MAX, &errstr); 3013 if (errstr) { 3014 fatal("Invalid number: %s (%s)", 3015 opts[i]+12, errstr); 3016 } 3017 } else { 3018 fatal("Option \"%s\" is unsupported for moduli " 3019 "screening", opts[i]); 3020 } 3021 } 3022 3023 if (have_identity && strcmp(identity_file, "-") != 0) { 3024 if ((in = fopen(identity_file, "r")) == NULL) { 3025 fatal("Couldn't open modulus candidate " 3026 "file \"%s\": %s", identity_file, 3027 strerror(errno)); 3028 } 3029 } 3030 3031 if ((out = fopen(out_file, "a")) == NULL) { 3032 fatal("Couldn't open moduli file \"%s\": %s", 3033 out_file, strerror(errno)); 3034 } 3035 setvbuf(out, NULL, _IOLBF, 0); 3036 if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests, 3037 generator_wanted, checkpoint, 3038 start_lineno, lines_to_process) != 0) 3039 fatal("modulus screening failed"); 3040 if (in != stdin) 3041 (void)fclose(in); 3042 free(checkpoint); 3043 #else /* WITH_OPENSSL */ 3044 fatal("Moduli screening is not supported"); 3045 #endif /* WITH_OPENSSL */ 3046 } 3047 3048 /* Read and confirm a passphrase */ 3049 static char * 3050 read_check_passphrase(const char *prompt1, const char *prompt2, 3051 const char *retry_prompt) 3052 { 3053 char *passphrase1, *passphrase2; 3054 3055 for (;;) { 3056 passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN); 3057 passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN); 3058 if (strcmp(passphrase1, passphrase2) == 0) { 3059 freezero(passphrase2, strlen(passphrase2)); 3060 return passphrase1; 3061 } 3062 /* The passphrases do not match. Clear them and retry. */ 3063 freezero(passphrase1, strlen(passphrase1)); 3064 freezero(passphrase2, strlen(passphrase2)); 3065 fputs(retry_prompt, stdout); 3066 fputc('\n', stdout); 3067 fflush(stdout); 3068 } 3069 /* NOTREACHED */ 3070 return NULL; 3071 } 3072 3073 static char * 3074 private_key_passphrase(void) 3075 { 3076 if (identity_passphrase) 3077 return xstrdup(identity_passphrase); 3078 if (identity_new_passphrase) 3079 return xstrdup(identity_new_passphrase); 3080 3081 return read_check_passphrase( 3082 "Enter passphrase (empty for no passphrase): ", 3083 "Enter same passphrase again: ", 3084 "Passphrases do not match. Try again."); 3085 } 3086 3087 static char * 3088 sk_suffix(const char *application, const uint8_t *user, size_t userlen) 3089 { 3090 char *ret, *cp; 3091 size_t slen, i; 3092 3093 /* Trim off URL-like preamble */ 3094 if (strncmp(application, "ssh://", 6) == 0) 3095 ret = xstrdup(application + 6); 3096 else if (strncmp(application, "ssh:", 4) == 0) 3097 ret = xstrdup(application + 4); 3098 else 3099 ret = xstrdup(application); 3100 3101 /* Count trailing zeros in user */ 3102 for (i = 0; i < userlen; i++) { 3103 if (user[userlen - i - 1] != 0) 3104 break; 3105 } 3106 if (i >= userlen) 3107 return ret; /* user-id was default all-zeros */ 3108 3109 /* Append user-id, escaping non-UTF-8 characters */ 3110 slen = userlen - i; 3111 if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1) 3112 fatal_f("asmprintf failed"); 3113 /* Don't emit a user-id that contains path or control characters */ 3114 if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL || 3115 strchr(cp, '\\') != NULL) { 3116 free(cp); 3117 cp = tohex(user, slen); 3118 } 3119 xextendf(&ret, "_", "%s", cp); 3120 free(cp); 3121 return ret; 3122 } 3123 3124 static int 3125 do_download_sk(const char *skprovider, const char *device) 3126 { 3127 struct sshsk_resident_key **srks; 3128 size_t nsrks, i; 3129 int r, ret = -1; 3130 char *fp, *pin = NULL, *pass = NULL, *path, *pubpath; 3131 const char *ext; 3132 struct sshkey *key; 3133 3134 if (skprovider == NULL) 3135 fatal("Cannot download keys without provider"); 3136 3137 pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN); 3138 if (!quiet) { 3139 printf("You may need to touch your authenticator " 3140 "to authorize key download.\n"); 3141 } 3142 if ((r = sshsk_load_resident(skprovider, device, pin, 0, 3143 &srks, &nsrks)) != 0) { 3144 if (pin != NULL) 3145 freezero(pin, strlen(pin)); 3146 error_r(r, "Unable to load resident keys"); 3147 return -1; 3148 } 3149 if (nsrks == 0) 3150 logit("No keys to download"); 3151 if (pin != NULL) 3152 freezero(pin, strlen(pin)); 3153 3154 for (i = 0; i < nsrks; i++) { 3155 key = srks[i]->key; 3156 if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) { 3157 error("Unsupported key type %s (%d)", 3158 sshkey_type(key), key->type); 3159 continue; 3160 } 3161 if ((fp = sshkey_fingerprint(key, fingerprint_hash, 3162 SSH_FP_DEFAULT)) == NULL) 3163 fatal_f("sshkey_fingerprint failed"); 3164 debug_f("key %zu: %s %s %s (flags 0x%02x)", i, 3165 sshkey_type(key), fp, key->sk_application, key->sk_flags); 3166 ext = sk_suffix(key->sk_application, 3167 srks[i]->user_id, srks[i]->user_id_len); 3168 xasprintf(&path, "id_%s_rk%s%s", 3169 key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk", 3170 *ext == '\0' ? "" : "_", ext); 3171 3172 /* If the file already exists, ask the user to confirm. */ 3173 if (!confirm_overwrite(path)) { 3174 free(path); 3175 break; 3176 } 3177 3178 /* Save the key with the application string as the comment */ 3179 if (pass == NULL) 3180 pass = private_key_passphrase(); 3181 if ((r = sshkey_save_private(key, path, pass, 3182 key->sk_application, private_key_format, 3183 openssh_format_cipher, rounds)) != 0) { 3184 error_r(r, "Saving key \"%s\" failed", path); 3185 free(path); 3186 break; 3187 } 3188 if (!quiet) { 3189 printf("Saved %s key%s%s to %s\n", sshkey_type(key), 3190 *ext != '\0' ? " " : "", 3191 *ext != '\0' ? key->sk_application : "", 3192 path); 3193 } 3194 3195 /* Save public key too */ 3196 xasprintf(&pubpath, "%s.pub", path); 3197 free(path); 3198 if ((r = sshkey_save_public(key, pubpath, 3199 key->sk_application)) != 0) { 3200 error_r(r, "Saving public key \"%s\" failed", pubpath); 3201 free(pubpath); 3202 break; 3203 } 3204 free(pubpath); 3205 } 3206 3207 if (i >= nsrks) 3208 ret = 0; /* success */ 3209 if (pass != NULL) 3210 freezero(pass, strlen(pass)); 3211 sshsk_free_resident_keys(srks, nsrks); 3212 return ret; 3213 } 3214 3215 static void 3216 save_attestation(struct sshbuf *attest, const char *path) 3217 { 3218 mode_t omask; 3219 int r; 3220 3221 if (path == NULL) 3222 return; /* nothing to do */ 3223 if (attest == NULL || sshbuf_len(attest) == 0) 3224 fatal("Enrollment did not return attestation data"); 3225 omask = umask(077); 3226 r = sshbuf_write_file(path, attest); 3227 umask(omask); 3228 if (r != 0) 3229 fatal_r(r, "Unable to write attestation data \"%s\"", path); 3230 if (!quiet) 3231 printf("Your FIDO attestation certificate has been saved in " 3232 "%s\n", path); 3233 } 3234 3235 static int 3236 confirm_sk_overwrite(const char *application, const char *user) 3237 { 3238 char yesno[3]; 3239 3240 printf("A resident key scoped to '%s' with user id '%s' already " 3241 "exists.\n", application == NULL ? "ssh:" : application, 3242 user == NULL ? "null" : user); 3243 printf("Overwrite key in token (y/n)? "); 3244 fflush(stdout); 3245 if (fgets(yesno, sizeof(yesno), stdin) == NULL) 3246 return 0; 3247 if (yesno[0] != 'y' && yesno[0] != 'Y') 3248 return 0; 3249 return 1; 3250 } 3251 3252 __dead static void 3253 usage(void) 3254 { 3255 fprintf(stderr, 3256 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n" 3257 " [-m format] [-N new_passphrase] [-O option]\n" 3258 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n" 3259 " [-w provider] [-Z cipher]\n" 3260 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n" 3261 " [-P old_passphrase] [-Z cipher]\n" 3262 #ifdef WITH_OPENSSL 3263 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n" 3264 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n" 3265 #endif 3266 " ssh-keygen -y [-f input_keyfile]\n" 3267 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n" 3268 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n" 3269 " ssh-keygen -B [-f input_keyfile]\n"); 3270 #ifdef ENABLE_PKCS11 3271 fprintf(stderr, 3272 " ssh-keygen -D pkcs11\n"); 3273 #endif 3274 fprintf(stderr, 3275 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n" 3276 " ssh-keygen -H [-f known_hosts_file]\n" 3277 " ssh-keygen -K [-a rounds] [-w provider]\n" 3278 " ssh-keygen -R hostname [-f known_hosts_file]\n" 3279 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n" 3280 #ifdef WITH_OPENSSL 3281 " ssh-keygen -M generate [-O option] output_file\n" 3282 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n" 3283 #endif 3284 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n" 3285 " [-n principals] [-O option] [-V validity_interval]\n" 3286 " [-z serial_number] file ...\n" 3287 " ssh-keygen -L [-f input_keyfile]\n" 3288 " ssh-keygen -A [-a rounds] [-f prefix_path]\n" 3289 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n" 3290 " file ...\n" 3291 " ssh-keygen -Q [-l] -f krl_file [file ...]\n" 3292 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n" 3293 " ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n" 3294 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n" 3295 " ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n" 3296 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n" 3297 " -n namespace -s signature_file [-r krl_file] [-O option]\n"); 3298 exit(1); 3299 } 3300 3301 /* 3302 * Main program for key management. 3303 */ 3304 int 3305 main(int argc, char **argv) 3306 { 3307 char comment[1024], *passphrase = NULL; 3308 char *rr_hostname = NULL, *ep, *fp, *ra; 3309 struct sshkey *private, *public; 3310 struct passwd *pw; 3311 int r, opt, type; 3312 int change_passphrase = 0, change_comment = 0, show_cert = 0; 3313 int find_host = 0, delete_host = 0, hash_hosts = 0; 3314 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0; 3315 int prefer_agent = 0, convert_to = 0, convert_from = 0; 3316 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0; 3317 int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0; 3318 unsigned long long cert_serial = 0; 3319 char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL; 3320 char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL; 3321 char *sk_attestation_path = NULL; 3322 struct sshbuf *challenge = NULL, *attest = NULL; 3323 size_t i, nopts = 0; 3324 u_int32_t bits = 0; 3325 uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD; 3326 const char *errstr; 3327 int log_level = SYSLOG_LEVEL_INFO; 3328 char *sign_op = NULL; 3329 3330 extern int optind; 3331 extern char *optarg; 3332 3333 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 3334 sanitise_stdfd(); 3335 3336 #ifdef WITH_OPENSSL 3337 OpenSSL_add_all_algorithms(); 3338 #endif 3339 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1); 3340 3341 setlocale(LC_CTYPE, ""); 3342 3343 /* we need this for the home * directory. */ 3344 pw = getpwuid(getuid()); 3345 if (!pw) 3346 fatal("No user exists for uid %lu", (u_long)getuid()); 3347 pw = pwcopy(pw); 3348 if (gethostname(hostname, sizeof(hostname)) == -1) 3349 fatal("gethostname: %s", strerror(errno)); 3350 3351 sk_provider = getenv("SSH_SK_PROVIDER"); 3352 3353 /* Remaining characters: dGjJSTWx */ 3354 while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy" 3355 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:" 3356 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) { 3357 switch (opt) { 3358 case 'A': 3359 gen_all_hostkeys = 1; 3360 break; 3361 case 'b': 3362 bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX, 3363 &errstr); 3364 if (errstr) 3365 fatal("Bits has bad value %s (%s)", 3366 optarg, errstr); 3367 break; 3368 case 'E': 3369 fingerprint_hash = ssh_digest_alg_by_name(optarg); 3370 if (fingerprint_hash == -1) 3371 fatal("Invalid hash algorithm \"%s\"", optarg); 3372 break; 3373 case 'F': 3374 find_host = 1; 3375 rr_hostname = optarg; 3376 break; 3377 case 'H': 3378 hash_hosts = 1; 3379 break; 3380 case 'I': 3381 cert_key_id = optarg; 3382 break; 3383 case 'R': 3384 delete_host = 1; 3385 rr_hostname = optarg; 3386 break; 3387 case 'L': 3388 show_cert = 1; 3389 break; 3390 case 'l': 3391 print_fingerprint = 1; 3392 break; 3393 case 'B': 3394 print_bubblebabble = 1; 3395 break; 3396 case 'm': 3397 if (strcasecmp(optarg, "RFC4716") == 0 || 3398 strcasecmp(optarg, "ssh2") == 0) { 3399 convert_format = FMT_RFC4716; 3400 break; 3401 } 3402 if (strcasecmp(optarg, "PKCS8") == 0) { 3403 convert_format = FMT_PKCS8; 3404 private_key_format = SSHKEY_PRIVATE_PKCS8; 3405 break; 3406 } 3407 if (strcasecmp(optarg, "PEM") == 0) { 3408 convert_format = FMT_PEM; 3409 private_key_format = SSHKEY_PRIVATE_PEM; 3410 break; 3411 } 3412 fatal("Unsupported conversion format \"%s\"", optarg); 3413 case 'n': 3414 cert_principals = optarg; 3415 break; 3416 case 'o': 3417 /* no-op; new format is already the default */ 3418 break; 3419 case 'p': 3420 change_passphrase = 1; 3421 break; 3422 case 'c': 3423 change_comment = 1; 3424 break; 3425 case 'f': 3426 if (strlcpy(identity_file, optarg, 3427 sizeof(identity_file)) >= sizeof(identity_file)) 3428 fatal("Identity filename too long"); 3429 have_identity = 1; 3430 break; 3431 case 'g': 3432 print_generic = 1; 3433 break; 3434 case 'K': 3435 download_sk = 1; 3436 break; 3437 case 'P': 3438 identity_passphrase = optarg; 3439 break; 3440 case 'N': 3441 identity_new_passphrase = optarg; 3442 break; 3443 case 'Q': 3444 check_krl = 1; 3445 break; 3446 case 'O': 3447 opts = xrecallocarray(opts, nopts, nopts + 1, 3448 sizeof(*opts)); 3449 opts[nopts++] = xstrdup(optarg); 3450 break; 3451 case 'Z': 3452 openssh_format_cipher = optarg; 3453 if (cipher_by_name(openssh_format_cipher) == NULL) 3454 fatal("Invalid OpenSSH-format cipher '%s'", 3455 openssh_format_cipher); 3456 break; 3457 case 'C': 3458 identity_comment = optarg; 3459 break; 3460 case 'q': 3461 quiet = 1; 3462 break; 3463 case 'e': 3464 /* export key */ 3465 convert_to = 1; 3466 break; 3467 case 'h': 3468 cert_key_type = SSH2_CERT_TYPE_HOST; 3469 certflags_flags = 0; 3470 break; 3471 case 'k': 3472 gen_krl = 1; 3473 break; 3474 case 'i': 3475 case 'X': 3476 /* import key */ 3477 convert_from = 1; 3478 break; 3479 case 'y': 3480 print_public = 1; 3481 break; 3482 case 's': 3483 ca_key_path = optarg; 3484 break; 3485 case 't': 3486 key_type_name = optarg; 3487 break; 3488 case 'D': 3489 pkcs11provider = optarg; 3490 break; 3491 case 'U': 3492 prefer_agent = 1; 3493 break; 3494 case 'u': 3495 update_krl = 1; 3496 break; 3497 case 'v': 3498 if (log_level == SYSLOG_LEVEL_INFO) 3499 log_level = SYSLOG_LEVEL_DEBUG1; 3500 else { 3501 if (log_level >= SYSLOG_LEVEL_DEBUG1 && 3502 log_level < SYSLOG_LEVEL_DEBUG3) 3503 log_level++; 3504 } 3505 break; 3506 case 'r': 3507 rr_hostname = optarg; 3508 break; 3509 case 'a': 3510 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr); 3511 if (errstr) 3512 fatal("Invalid number: %s (%s)", 3513 optarg, errstr); 3514 break; 3515 case 'V': 3516 parse_cert_times(optarg); 3517 break; 3518 case 'Y': 3519 sign_op = optarg; 3520 break; 3521 case 'w': 3522 sk_provider = optarg; 3523 break; 3524 case 'z': 3525 errno = 0; 3526 if (*optarg == '+') { 3527 cert_serial_autoinc = 1; 3528 optarg++; 3529 } 3530 cert_serial = strtoull(optarg, &ep, 10); 3531 if (*optarg < '0' || *optarg > '9' || *ep != '\0' || 3532 (errno == ERANGE && cert_serial == ULLONG_MAX)) 3533 fatal("Invalid serial number \"%s\"", optarg); 3534 break; 3535 case 'M': 3536 if (strcmp(optarg, "generate") == 0) 3537 do_gen_candidates = 1; 3538 else if (strcmp(optarg, "screen") == 0) 3539 do_screen_candidates = 1; 3540 else 3541 fatal("Unsupported moduli option %s", optarg); 3542 break; 3543 default: 3544 usage(); 3545 } 3546 } 3547 3548 if (sk_provider == NULL) 3549 sk_provider = "internal"; 3550 3551 /* reinit */ 3552 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1); 3553 3554 argv += optind; 3555 argc -= optind; 3556 3557 if (sign_op != NULL) { 3558 if (strncmp(sign_op, "find-principals", 15) == 0) { 3559 if (ca_key_path == NULL) { 3560 error("Too few arguments for find-principals:" 3561 "missing signature file"); 3562 exit(1); 3563 } 3564 if (!have_identity) { 3565 error("Too few arguments for find-principals:" 3566 "missing allowed keys file"); 3567 exit(1); 3568 } 3569 return sig_find_principals(ca_key_path, identity_file, 3570 opts, nopts); 3571 } else if (strncmp(sign_op, "match-principals", 16) == 0) { 3572 if (!have_identity) { 3573 error("Too few arguments for match-principals:" 3574 "missing allowed keys file"); 3575 exit(1); 3576 } 3577 if (cert_key_id == NULL) { 3578 error("Too few arguments for match-principals: " 3579 "missing principal ID"); 3580 exit(1); 3581 } 3582 return sig_match_principals(identity_file, cert_key_id, 3583 opts, nopts); 3584 } else if (strncmp(sign_op, "sign", 4) == 0) { 3585 /* NB. cert_principals is actually namespace, via -n */ 3586 if (cert_principals == NULL || 3587 *cert_principals == '\0') { 3588 error("Too few arguments for sign: " 3589 "missing namespace"); 3590 exit(1); 3591 } 3592 if (!have_identity) { 3593 error("Too few arguments for sign: " 3594 "missing key"); 3595 exit(1); 3596 } 3597 return sig_sign(identity_file, cert_principals, 3598 prefer_agent, argc, argv, opts, nopts); 3599 } else if (strncmp(sign_op, "check-novalidate", 16) == 0) { 3600 /* NB. cert_principals is actually namespace, via -n */ 3601 if (cert_principals == NULL || 3602 *cert_principals == '\0') { 3603 error("Too few arguments for check-novalidate: " 3604 "missing namespace"); 3605 exit(1); 3606 } 3607 if (ca_key_path == NULL) { 3608 error("Too few arguments for check-novalidate: " 3609 "missing signature file"); 3610 exit(1); 3611 } 3612 return sig_verify(ca_key_path, cert_principals, 3613 NULL, NULL, NULL, opts, nopts); 3614 } else if (strncmp(sign_op, "verify", 6) == 0) { 3615 /* NB. cert_principals is actually namespace, via -n */ 3616 if (cert_principals == NULL || 3617 *cert_principals == '\0') { 3618 error("Too few arguments for verify: " 3619 "missing namespace"); 3620 exit(1); 3621 } 3622 if (ca_key_path == NULL) { 3623 error("Too few arguments for verify: " 3624 "missing signature file"); 3625 exit(1); 3626 } 3627 if (!have_identity) { 3628 error("Too few arguments for sign: " 3629 "missing allowed keys file"); 3630 exit(1); 3631 } 3632 if (cert_key_id == NULL) { 3633 error("Too few arguments for verify: " 3634 "missing principal identity"); 3635 exit(1); 3636 } 3637 return sig_verify(ca_key_path, cert_principals, 3638 cert_key_id, identity_file, rr_hostname, 3639 opts, nopts); 3640 } 3641 error("Unsupported operation for -Y: \"%s\"", sign_op); 3642 usage(); 3643 /* NOTREACHED */ 3644 } 3645 3646 if (ca_key_path != NULL) { 3647 if (argc < 1 && !gen_krl) { 3648 error("Too few arguments."); 3649 usage(); 3650 } 3651 } else if (argc > 0 && !gen_krl && !check_krl && 3652 !do_gen_candidates && !do_screen_candidates) { 3653 error("Too many arguments."); 3654 usage(); 3655 } 3656 if (change_passphrase && change_comment) { 3657 error("Can only have one of -p and -c."); 3658 usage(); 3659 } 3660 if (print_fingerprint && (delete_host || hash_hosts)) { 3661 error("Cannot use -l with -H or -R."); 3662 usage(); 3663 } 3664 if (gen_krl) { 3665 do_gen_krl(pw, update_krl, ca_key_path, 3666 cert_serial, identity_comment, argc, argv); 3667 return (0); 3668 } 3669 if (check_krl) { 3670 do_check_krl(pw, print_fingerprint, argc, argv); 3671 return (0); 3672 } 3673 if (ca_key_path != NULL) { 3674 if (cert_key_id == NULL) 3675 fatal("Must specify key id (-I) when certifying"); 3676 for (i = 0; i < nopts; i++) 3677 add_cert_option(opts[i]); 3678 do_ca_sign(pw, ca_key_path, prefer_agent, 3679 cert_serial, cert_serial_autoinc, argc, argv); 3680 } 3681 if (show_cert) 3682 do_show_cert(pw); 3683 if (delete_host || hash_hosts || find_host) { 3684 do_known_hosts(pw, rr_hostname, find_host, 3685 delete_host, hash_hosts); 3686 } 3687 if (pkcs11provider != NULL) 3688 do_download(pw); 3689 if (download_sk) { 3690 for (i = 0; i < nopts; i++) { 3691 if (strncasecmp(opts[i], "device=", 7) == 0) { 3692 sk_device = xstrdup(opts[i] + 7); 3693 } else { 3694 fatal("Option \"%s\" is unsupported for " 3695 "FIDO authenticator download", opts[i]); 3696 } 3697 } 3698 return do_download_sk(sk_provider, sk_device); 3699 } 3700 if (print_fingerprint || print_bubblebabble) 3701 do_fingerprint(pw); 3702 if (change_passphrase) 3703 do_change_passphrase(pw); 3704 if (change_comment) 3705 do_change_comment(pw, identity_comment); 3706 #ifdef WITH_OPENSSL 3707 if (convert_to) 3708 do_convert_to(pw); 3709 if (convert_from) 3710 do_convert_from(pw); 3711 #else /* WITH_OPENSSL */ 3712 if (convert_to || convert_from) 3713 fatal("key conversion disabled at compile time"); 3714 #endif /* WITH_OPENSSL */ 3715 if (print_public) 3716 do_print_public(pw); 3717 if (rr_hostname != NULL) { 3718 unsigned int n = 0; 3719 3720 if (have_identity) { 3721 n = do_print_resource_record(pw, identity_file, 3722 rr_hostname, print_generic, opts, nopts); 3723 if (n == 0) 3724 fatal("%s: %s", identity_file, strerror(errno)); 3725 exit(0); 3726 } else { 3727 3728 n += do_print_resource_record(pw, 3729 _PATH_HOST_RSA_KEY_FILE, rr_hostname, 3730 print_generic, opts, nopts); 3731 n += do_print_resource_record(pw, 3732 _PATH_HOST_DSA_KEY_FILE, rr_hostname, 3733 print_generic, opts, nopts); 3734 n += do_print_resource_record(pw, 3735 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname, 3736 print_generic, opts, nopts); 3737 n += do_print_resource_record(pw, 3738 _PATH_HOST_ED25519_KEY_FILE, rr_hostname, 3739 print_generic, opts, nopts); 3740 n += do_print_resource_record(pw, 3741 _PATH_HOST_XMSS_KEY_FILE, rr_hostname, 3742 print_generic, opts, nopts); 3743 if (n == 0) 3744 fatal("no keys found."); 3745 exit(0); 3746 } 3747 } 3748 3749 if (do_gen_candidates || do_screen_candidates) { 3750 if (argc <= 0) 3751 fatal("No output file specified"); 3752 else if (argc > 1) 3753 fatal("Too many output files specified"); 3754 } 3755 if (do_gen_candidates) { 3756 do_moduli_gen(argv[0], opts, nopts); 3757 return 0; 3758 } 3759 if (do_screen_candidates) { 3760 do_moduli_screen(argv[0], opts, nopts); 3761 return 0; 3762 } 3763 3764 if (gen_all_hostkeys) { 3765 do_gen_all_hostkeys(pw); 3766 return (0); 3767 } 3768 3769 if (key_type_name == NULL) 3770 key_type_name = DEFAULT_KEY_TYPE_NAME; 3771 3772 type = sshkey_type_from_name(key_type_name); 3773 type_bits_valid(type, key_type_name, &bits); 3774 3775 if (!quiet) 3776 printf("Generating public/private %s key pair.\n", 3777 key_type_name); 3778 switch (type) { 3779 case KEY_ECDSA_SK: 3780 case KEY_ED25519_SK: 3781 for (i = 0; i < nopts; i++) { 3782 if (strcasecmp(opts[i], "no-touch-required") == 0) { 3783 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD; 3784 } else if (strcasecmp(opts[i], "verify-required") == 0) { 3785 sk_flags |= SSH_SK_USER_VERIFICATION_REQD; 3786 } else if (strcasecmp(opts[i], "resident") == 0) { 3787 sk_flags |= SSH_SK_RESIDENT_KEY; 3788 } else if (strncasecmp(opts[i], "device=", 7) == 0) { 3789 sk_device = xstrdup(opts[i] + 7); 3790 } else if (strncasecmp(opts[i], "user=", 5) == 0) { 3791 sk_user = xstrdup(opts[i] + 5); 3792 } else if (strncasecmp(opts[i], "challenge=", 10) == 0) { 3793 if ((r = sshbuf_load_file(opts[i] + 10, 3794 &challenge)) != 0) { 3795 fatal_r(r, "Unable to load FIDO " 3796 "enrollment challenge \"%s\"", 3797 opts[i] + 10); 3798 } 3799 } else if (strncasecmp(opts[i], 3800 "write-attestation=", 18) == 0) { 3801 sk_attestation_path = opts[i] + 18; 3802 } else if (strncasecmp(opts[i], 3803 "application=", 12) == 0) { 3804 sk_application = xstrdup(opts[i] + 12); 3805 if (strncmp(sk_application, "ssh:", 4) != 0) { 3806 fatal("FIDO application string must " 3807 "begin with \"ssh:\""); 3808 } 3809 } else { 3810 fatal("Option \"%s\" is unsupported for " 3811 "FIDO authenticator enrollment", opts[i]); 3812 } 3813 } 3814 if ((attest = sshbuf_new()) == NULL) 3815 fatal("sshbuf_new failed"); 3816 r = 0; 3817 for (i = 0 ;;) { 3818 if (!quiet) { 3819 printf("You may need to touch your " 3820 "authenticator%s to authorize key " 3821 "generation.\n", 3822 r == 0 ? "" : " again"); 3823 } 3824 fflush(stdout); 3825 r = sshsk_enroll(type, sk_provider, sk_device, 3826 sk_application == NULL ? "ssh:" : sk_application, 3827 sk_user, sk_flags, passphrase, challenge, 3828 &private, attest); 3829 if (r == 0) 3830 break; 3831 if (r == SSH_ERR_KEY_BAD_PERMISSIONS && 3832 (sk_flags & SSH_SK_RESIDENT_KEY) != 0 && 3833 (sk_flags & SSH_SK_FORCE_OPERATION) == 0 && 3834 confirm_sk_overwrite(sk_application, sk_user)) { 3835 sk_flags |= SSH_SK_FORCE_OPERATION; 3836 continue; 3837 } 3838 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) 3839 fatal_r(r, "Key enrollment failed"); 3840 else if (passphrase != NULL) { 3841 error("PIN incorrect"); 3842 freezero(passphrase, strlen(passphrase)); 3843 passphrase = NULL; 3844 } 3845 if (++i >= 3) 3846 fatal("Too many incorrect PINs"); 3847 passphrase = read_passphrase("Enter PIN for " 3848 "authenticator: ", RP_ALLOW_STDIN); 3849 } 3850 if (passphrase != NULL) { 3851 freezero(passphrase, strlen(passphrase)); 3852 passphrase = NULL; 3853 } 3854 break; 3855 default: 3856 if ((r = sshkey_generate(type, bits, &private)) != 0) 3857 fatal("sshkey_generate failed"); 3858 break; 3859 } 3860 if ((r = sshkey_from_private(private, &public)) != 0) 3861 fatal_r(r, "sshkey_from_private"); 3862 3863 if (!have_identity) 3864 ask_filename(pw, "Enter file in which to save the key"); 3865 3866 /* Create ~/.ssh directory if it doesn't already exist. */ 3867 hostfile_create_user_ssh_dir(identity_file, !quiet); 3868 3869 /* If the file already exists, ask the user to confirm. */ 3870 if (!confirm_overwrite(identity_file)) 3871 exit(1); 3872 3873 /* Determine the passphrase for the private key */ 3874 passphrase = private_key_passphrase(); 3875 if (identity_comment) { 3876 strlcpy(comment, identity_comment, sizeof(comment)); 3877 } else { 3878 /* Create default comment field for the passphrase. */ 3879 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname); 3880 } 3881 3882 /* Save the key with the given passphrase and comment. */ 3883 if ((r = sshkey_save_private(private, identity_file, passphrase, 3884 comment, private_key_format, openssh_format_cipher, rounds)) != 0) { 3885 error_r(r, "Saving key \"%s\" failed", identity_file); 3886 freezero(passphrase, strlen(passphrase)); 3887 exit(1); 3888 } 3889 freezero(passphrase, strlen(passphrase)); 3890 sshkey_free(private); 3891 3892 if (!quiet) { 3893 printf("Your identification has been saved in %s\n", 3894 identity_file); 3895 } 3896 3897 strlcat(identity_file, ".pub", sizeof(identity_file)); 3898 if ((r = sshkey_save_public(public, identity_file, comment)) != 0) 3899 fatal_r(r, "Unable to save public key to %s", identity_file); 3900 3901 if (!quiet) { 3902 fp = sshkey_fingerprint(public, fingerprint_hash, 3903 SSH_FP_DEFAULT); 3904 ra = sshkey_fingerprint(public, fingerprint_hash, 3905 SSH_FP_RANDOMART); 3906 if (fp == NULL || ra == NULL) 3907 fatal("sshkey_fingerprint failed"); 3908 printf("Your public key has been saved in %s\n", 3909 identity_file); 3910 printf("The key fingerprint is:\n"); 3911 printf("%s %s\n", fp, comment); 3912 printf("The key's randomart image is:\n"); 3913 printf("%s\n", ra); 3914 free(ra); 3915 free(fp); 3916 } 3917 3918 if (sk_attestation_path != NULL) 3919 save_attestation(attest, sk_attestation_path); 3920 3921 sshbuf_free(attest); 3922 sshkey_free(public); 3923 3924 exit(0); 3925 } 3926