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