1 /* $OpenBSD: ssh-add.c,v 1.136 2018/09/19 02:03:02 djm Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * Adds an identity to the authentication server, or removes an identity. 7 * 8 * As far as I am concerned, the code I have written for this software 9 * can be used freely for any purpose. Any derived versions of this 10 * software must be clearly marked as such, and if the derived work is 11 * incompatible with the protocol description in the RFC file, it must be 12 * called by a name other than "ssh" or "Secure Shell". 13 * 14 * SSH2 implementation, 15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 16 * 17 * Redistribution and use in source and binary forms, with or without 18 * modification, are permitted provided that the following conditions 19 * are met: 20 * 1. Redistributions of source code must retain the above copyright 21 * notice, this list of conditions and the following disclaimer. 22 * 2. Redistributions in binary form must reproduce the above copyright 23 * notice, this list of conditions and the following disclaimer in the 24 * documentation and/or other materials provided with the distribution. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 */ 37 38 #include <sys/types.h> 39 #include <sys/stat.h> 40 41 #include <openssl/evp.h> 42 43 #include <errno.h> 44 #include <fcntl.h> 45 #include <pwd.h> 46 #include <stdio.h> 47 #include <stdlib.h> 48 #include <string.h> 49 #include <unistd.h> 50 #include <limits.h> 51 52 #include "xmalloc.h" 53 #include "ssh.h" 54 #include "log.h" 55 #include "sshkey.h" 56 #include "sshbuf.h" 57 #include "authfd.h" 58 #include "authfile.h" 59 #include "pathnames.h" 60 #include "misc.h" 61 #include "ssherr.h" 62 #include "digest.h" 63 64 /* argv0 */ 65 extern char *__progname; 66 67 /* Default files to add */ 68 static char *default_files[] = { 69 _PATH_SSH_CLIENT_ID_RSA, 70 _PATH_SSH_CLIENT_ID_DSA, 71 _PATH_SSH_CLIENT_ID_ECDSA, 72 _PATH_SSH_CLIENT_ID_ED25519, 73 _PATH_SSH_CLIENT_ID_XMSS, 74 NULL 75 }; 76 77 static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 78 79 /* Default lifetime (0 == forever) */ 80 static int lifetime = 0; 81 82 /* User has to confirm key use */ 83 static int confirm = 0; 84 85 /* Maximum number of signatures (XMSS) */ 86 static u_int maxsign = 0; 87 static u_int minleft = 0; 88 89 /* we keep a cache of one passphrase */ 90 static char *pass = NULL; 91 static void 92 clear_pass(void) 93 { 94 if (pass) { 95 explicit_bzero(pass, strlen(pass)); 96 free(pass); 97 pass = NULL; 98 } 99 } 100 101 static int 102 delete_file(int agent_fd, const char *filename, int key_only, int qflag) 103 { 104 struct sshkey *public, *cert = NULL; 105 char *certpath = NULL, *comment = NULL; 106 int r, ret = -1; 107 108 if ((r = sshkey_load_public(filename, &public, &comment)) != 0) { 109 printf("Bad key file %s: %s\n", filename, ssh_err(r)); 110 return -1; 111 } 112 if ((r = ssh_remove_identity(agent_fd, public)) == 0) { 113 if (!qflag) { 114 fprintf(stderr, "Identity removed: %s (%s)\n", 115 filename, comment); 116 } 117 ret = 0; 118 } else 119 fprintf(stderr, "Could not remove identity \"%s\": %s\n", 120 filename, ssh_err(r)); 121 122 if (key_only) 123 goto out; 124 125 /* Now try to delete the corresponding certificate too */ 126 free(comment); 127 comment = NULL; 128 xasprintf(&certpath, "%s-cert.pub", filename); 129 if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) { 130 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT) 131 error("Failed to load certificate \"%s\": %s", 132 certpath, ssh_err(r)); 133 goto out; 134 } 135 136 if (!sshkey_equal_public(cert, public)) 137 fatal("Certificate %s does not match private key %s", 138 certpath, filename); 139 140 if ((r = ssh_remove_identity(agent_fd, cert)) == 0) { 141 if (!qflag) { 142 fprintf(stderr, "Identity removed: %s (%s)\n", 143 certpath, comment); 144 } 145 ret = 0; 146 } else 147 fprintf(stderr, "Could not remove identity \"%s\": %s\n", 148 certpath, ssh_err(r)); 149 150 out: 151 sshkey_free(cert); 152 sshkey_free(public); 153 free(certpath); 154 free(comment); 155 156 return ret; 157 } 158 159 /* Send a request to remove all identities. */ 160 static int 161 delete_all(int agent_fd, int qflag) 162 { 163 int ret = -1; 164 165 /* 166 * Since the agent might be forwarded, old or non-OpenSSH, when asked 167 * to remove all keys, attempt to remove both protocol v.1 and v.2 168 * keys. 169 */ 170 if (ssh_remove_all_identities(agent_fd, 2) == 0) 171 ret = 0; 172 /* ignore error-code for ssh1 */ 173 ssh_remove_all_identities(agent_fd, 1); 174 175 if (ret != 0) 176 fprintf(stderr, "Failed to remove all identities.\n"); 177 else if (!qflag) 178 fprintf(stderr, "All identities removed.\n"); 179 180 return ret; 181 } 182 183 static int 184 add_file(int agent_fd, const char *filename, int key_only, int qflag) 185 { 186 struct sshkey *private, *cert; 187 char *comment = NULL; 188 char msg[1024], *certpath = NULL; 189 int r, fd, ret = -1; 190 size_t i; 191 u_int32_t left; 192 struct sshbuf *keyblob; 193 struct ssh_identitylist *idlist; 194 195 if (strcmp(filename, "-") == 0) { 196 fd = STDIN_FILENO; 197 filename = "(stdin)"; 198 } else if ((fd = open(filename, O_RDONLY)) < 0) { 199 perror(filename); 200 return -1; 201 } 202 203 /* 204 * Since we'll try to load a keyfile multiple times, permission errors 205 * will occur multiple times, so check perms first and bail if wrong. 206 */ 207 if (fd != STDIN_FILENO) { 208 if (sshkey_perm_ok(fd, filename) != 0) { 209 close(fd); 210 return -1; 211 } 212 } 213 if ((keyblob = sshbuf_new()) == NULL) 214 fatal("%s: sshbuf_new failed", __func__); 215 if ((r = sshkey_load_file(fd, keyblob)) != 0) { 216 fprintf(stderr, "Error loading key \"%s\": %s\n", 217 filename, ssh_err(r)); 218 sshbuf_free(keyblob); 219 close(fd); 220 return -1; 221 } 222 close(fd); 223 224 /* At first, try empty passphrase */ 225 if ((r = sshkey_parse_private_fileblob(keyblob, "", &private, 226 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) { 227 fprintf(stderr, "Error loading key \"%s\": %s\n", 228 filename, ssh_err(r)); 229 goto fail_load; 230 } 231 /* try last */ 232 if (private == NULL && pass != NULL) { 233 if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private, 234 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) { 235 fprintf(stderr, "Error loading key \"%s\": %s\n", 236 filename, ssh_err(r)); 237 goto fail_load; 238 } 239 } 240 if (private == NULL) { 241 /* clear passphrase since it did not work */ 242 clear_pass(); 243 snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ", 244 filename, confirm ? " (will confirm each use)" : ""); 245 for (;;) { 246 pass = read_passphrase(msg, RP_ALLOW_STDIN); 247 if (strcmp(pass, "") == 0) 248 goto fail_load; 249 if ((r = sshkey_parse_private_fileblob(keyblob, pass, 250 &private, &comment)) == 0) 251 break; 252 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) { 253 fprintf(stderr, 254 "Error loading key \"%s\": %s\n", 255 filename, ssh_err(r)); 256 fail_load: 257 clear_pass(); 258 sshbuf_free(keyblob); 259 return -1; 260 } 261 clear_pass(); 262 snprintf(msg, sizeof msg, 263 "Bad passphrase, try again for %s%s: ", filename, 264 confirm ? " (will confirm each use)" : ""); 265 } 266 } 267 if (comment == NULL || *comment == '\0') 268 comment = xstrdup(filename); 269 sshbuf_free(keyblob); 270 271 /* For XMSS */ 272 if ((r = sshkey_set_filename(private, filename)) != 0) { 273 fprintf(stderr, "Could not add filename to private key: %s (%s)\n", 274 filename, comment); 275 goto out; 276 } 277 if (maxsign && minleft && 278 (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) { 279 for (i = 0; i < idlist->nkeys; i++) { 280 if (!sshkey_equal_public(idlist->keys[i], private)) 281 continue; 282 left = sshkey_signatures_left(idlist->keys[i]); 283 if (left < minleft) { 284 fprintf(stderr, 285 "Only %d signatures left.\n", left); 286 break; 287 } 288 fprintf(stderr, "Skipping update: "); 289 if (left == minleft) { 290 fprintf(stderr, 291 "required signatures left (%d).\n", left); 292 } else { 293 fprintf(stderr, 294 "more signatures left (%d) than" 295 " required (%d).\n", left, minleft); 296 } 297 ssh_free_identitylist(idlist); 298 goto out; 299 } 300 ssh_free_identitylist(idlist); 301 } 302 303 if ((r = ssh_add_identity_constrained(agent_fd, private, comment, 304 lifetime, confirm, maxsign)) == 0) { 305 ret = 0; 306 if (!qflag) { 307 fprintf(stderr, "Identity added: %s (%s)\n", 308 filename, comment); 309 if (lifetime != 0) { 310 fprintf(stderr, 311 "Lifetime set to %d seconds\n", lifetime); 312 } 313 if (confirm != 0) { 314 fprintf(stderr, "The user must confirm " 315 "each use of the key\n"); 316 } 317 } 318 } else { 319 fprintf(stderr, "Could not add identity \"%s\": %s\n", 320 filename, ssh_err(r)); 321 } 322 323 /* Skip trying to load the cert if requested */ 324 if (key_only) 325 goto out; 326 327 /* Now try to add the certificate flavour too */ 328 xasprintf(&certpath, "%s-cert.pub", filename); 329 if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) { 330 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT) 331 error("Failed to load certificate \"%s\": %s", 332 certpath, ssh_err(r)); 333 goto out; 334 } 335 336 if (!sshkey_equal_public(cert, private)) { 337 error("Certificate %s does not match private key %s", 338 certpath, filename); 339 sshkey_free(cert); 340 goto out; 341 } 342 343 /* Graft with private bits */ 344 if ((r = sshkey_to_certified(private)) != 0) { 345 error("%s: sshkey_to_certified: %s", __func__, ssh_err(r)); 346 sshkey_free(cert); 347 goto out; 348 } 349 if ((r = sshkey_cert_copy(cert, private)) != 0) { 350 error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r)); 351 sshkey_free(cert); 352 goto out; 353 } 354 sshkey_free(cert); 355 356 if ((r = ssh_add_identity_constrained(agent_fd, private, comment, 357 lifetime, confirm, maxsign)) != 0) { 358 error("Certificate %s (%s) add failed: %s", certpath, 359 private->cert->key_id, ssh_err(r)); 360 goto out; 361 } 362 /* success */ 363 if (!qflag) { 364 fprintf(stderr, "Certificate added: %s (%s)\n", certpath, 365 private->cert->key_id); 366 if (lifetime != 0) { 367 fprintf(stderr, "Lifetime set to %d seconds\n", 368 lifetime); 369 } 370 if (confirm != 0) { 371 fprintf(stderr, "The user must confirm each use " 372 "of the key\n"); 373 } 374 } 375 376 out: 377 free(certpath); 378 free(comment); 379 sshkey_free(private); 380 381 return ret; 382 } 383 384 static int 385 update_card(int agent_fd, int add, const char *id, int qflag) 386 { 387 char *pin = NULL; 388 int r, ret = -1; 389 390 if (add) { 391 if ((pin = read_passphrase("Enter passphrase for PKCS#11: ", 392 RP_ALLOW_STDIN)) == NULL) 393 return -1; 394 } 395 396 if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin, 397 lifetime, confirm)) == 0) { 398 ret = 0; 399 if (!qflag) { 400 fprintf(stderr, "Card %s: %s\n", 401 add ? "added" : "removed", id); 402 } 403 } else { 404 fprintf(stderr, "Could not %s card \"%s\": %s\n", 405 add ? "add" : "remove", id, ssh_err(r)); 406 ret = -1; 407 } 408 free(pin); 409 return ret; 410 } 411 412 static int 413 list_identities(int agent_fd, int do_fp) 414 { 415 char *fp; 416 int r; 417 struct ssh_identitylist *idlist; 418 u_int32_t left; 419 size_t i; 420 421 if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) { 422 if (r != SSH_ERR_AGENT_NO_IDENTITIES) 423 fprintf(stderr, "error fetching identities: %s\n", 424 ssh_err(r)); 425 else 426 printf("The agent has no identities.\n"); 427 return -1; 428 } 429 for (i = 0; i < idlist->nkeys; i++) { 430 if (do_fp) { 431 fp = sshkey_fingerprint(idlist->keys[i], 432 fingerprint_hash, SSH_FP_DEFAULT); 433 printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]), 434 fp == NULL ? "(null)" : fp, idlist->comments[i], 435 sshkey_type(idlist->keys[i])); 436 free(fp); 437 } else { 438 if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) { 439 fprintf(stderr, "sshkey_write: %s\n", 440 ssh_err(r)); 441 continue; 442 } 443 fprintf(stdout, " %s", idlist->comments[i]); 444 left = sshkey_signatures_left(idlist->keys[i]); 445 if (left > 0) 446 fprintf(stdout, 447 " [signatures left %d]", left); 448 fprintf(stdout, "\n"); 449 } 450 } 451 ssh_free_identitylist(idlist); 452 return 0; 453 } 454 455 static int 456 lock_agent(int agent_fd, int lock) 457 { 458 char prompt[100], *p1, *p2; 459 int r, passok = 1, ret = -1; 460 461 strlcpy(prompt, "Enter lock password: ", sizeof(prompt)); 462 p1 = read_passphrase(prompt, RP_ALLOW_STDIN); 463 if (lock) { 464 strlcpy(prompt, "Again: ", sizeof prompt); 465 p2 = read_passphrase(prompt, RP_ALLOW_STDIN); 466 if (strcmp(p1, p2) != 0) { 467 fprintf(stderr, "Passwords do not match.\n"); 468 passok = 0; 469 } 470 explicit_bzero(p2, strlen(p2)); 471 free(p2); 472 } 473 if (passok) { 474 if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) { 475 fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un"); 476 ret = 0; 477 } else { 478 fprintf(stderr, "Failed to %slock agent: %s\n", 479 lock ? "" : "un", ssh_err(r)); 480 } 481 } 482 explicit_bzero(p1, strlen(p1)); 483 free(p1); 484 return (ret); 485 } 486 487 static int 488 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag) 489 { 490 if (deleting) { 491 if (delete_file(agent_fd, file, key_only, qflag) == -1) 492 return -1; 493 } else { 494 if (add_file(agent_fd, file, key_only, qflag) == -1) 495 return -1; 496 } 497 return 0; 498 } 499 500 static void 501 usage(void) 502 { 503 fprintf(stderr, "usage: %s [options] [file ...]\n", __progname); 504 fprintf(stderr, "Options:\n"); 505 fprintf(stderr, " -l List fingerprints of all identities.\n"); 506 fprintf(stderr, " -E hash Specify hash algorithm used for fingerprints.\n"); 507 fprintf(stderr, " -L List public key parameters of all identities.\n"); 508 fprintf(stderr, " -k Load only keys and not certificates.\n"); 509 fprintf(stderr, " -c Require confirmation to sign using identities\n"); 510 fprintf(stderr, " -m minleft Maxsign is only changed if less than minleft are left (for XMSS)\n"); 511 fprintf(stderr, " -M maxsign Maximum number of signatures allowed (for XMSS)\n"); 512 fprintf(stderr, " -t life Set lifetime (in seconds) when adding identities.\n"); 513 fprintf(stderr, " -d Delete identity.\n"); 514 fprintf(stderr, " -D Delete all identities.\n"); 515 fprintf(stderr, " -x Lock agent.\n"); 516 fprintf(stderr, " -X Unlock agent.\n"); 517 fprintf(stderr, " -s pkcs11 Add keys from PKCS#11 provider.\n"); 518 fprintf(stderr, " -e pkcs11 Remove keys provided by PKCS#11 provider.\n"); 519 fprintf(stderr, " -q Be quiet after a successful operation.\n"); 520 } 521 522 int 523 main(int argc, char **argv) 524 { 525 extern char *optarg; 526 extern int optind; 527 int agent_fd; 528 char *pkcs11provider = NULL; 529 int r, i, ch, deleting = 0, ret = 0, key_only = 0; 530 int xflag = 0, lflag = 0, Dflag = 0, qflag = 0; 531 532 ssh_malloc_init(); /* must be called before any mallocs */ 533 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 534 sanitise_stdfd(); 535 536 OpenSSL_add_all_algorithms(); 537 538 setvbuf(stdout, NULL, _IOLBF, 0); 539 540 /* First, get a connection to the authentication agent. */ 541 switch (r = ssh_get_authentication_socket(&agent_fd)) { 542 case 0: 543 break; 544 case SSH_ERR_AGENT_NOT_PRESENT: 545 fprintf(stderr, "Could not open a connection to your " 546 "authentication agent.\n"); 547 exit(2); 548 default: 549 fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r)); 550 exit(2); 551 } 552 553 while ((ch = getopt(argc, argv, "klLcdDxXE:e:M:m:qs:t:")) != -1) { 554 switch (ch) { 555 case 'E': 556 fingerprint_hash = ssh_digest_alg_by_name(optarg); 557 if (fingerprint_hash == -1) 558 fatal("Invalid hash algorithm \"%s\"", optarg); 559 break; 560 case 'k': 561 key_only = 1; 562 break; 563 case 'l': 564 case 'L': 565 if (lflag != 0) 566 fatal("-%c flag already specified", lflag); 567 lflag = ch; 568 break; 569 case 'x': 570 case 'X': 571 if (xflag != 0) 572 fatal("-%c flag already specified", xflag); 573 xflag = ch; 574 break; 575 case 'c': 576 confirm = 1; 577 break; 578 case 'm': 579 minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL); 580 if (minleft == 0) { 581 usage(); 582 ret = 1; 583 goto done; 584 } 585 break; 586 case 'M': 587 maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL); 588 if (maxsign == 0) { 589 usage(); 590 ret = 1; 591 goto done; 592 } 593 break; 594 case 'd': 595 deleting = 1; 596 break; 597 case 'D': 598 Dflag = 1; 599 break; 600 case 's': 601 pkcs11provider = optarg; 602 break; 603 case 'e': 604 deleting = 1; 605 pkcs11provider = optarg; 606 break; 607 case 't': 608 if ((lifetime = convtime(optarg)) == -1) { 609 fprintf(stderr, "Invalid lifetime\n"); 610 ret = 1; 611 goto done; 612 } 613 break; 614 case 'q': 615 qflag = 1; 616 break; 617 default: 618 usage(); 619 ret = 1; 620 goto done; 621 } 622 } 623 624 if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1) 625 fatal("Invalid combination of actions"); 626 else if (xflag) { 627 if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1) 628 ret = 1; 629 goto done; 630 } else if (lflag) { 631 if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1) 632 ret = 1; 633 goto done; 634 } else if (Dflag) { 635 if (delete_all(agent_fd, qflag) == -1) 636 ret = 1; 637 goto done; 638 } 639 640 argc -= optind; 641 argv += optind; 642 if (pkcs11provider != NULL) { 643 if (update_card(agent_fd, !deleting, pkcs11provider, 644 qflag) == -1) 645 ret = 1; 646 goto done; 647 } 648 if (argc == 0) { 649 char buf[PATH_MAX]; 650 struct passwd *pw; 651 struct stat st; 652 int count = 0; 653 654 if ((pw = getpwuid(getuid())) == NULL) { 655 fprintf(stderr, "No user found with uid %u\n", 656 (u_int)getuid()); 657 ret = 1; 658 goto done; 659 } 660 661 for (i = 0; default_files[i]; i++) { 662 snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir, 663 default_files[i]); 664 if (stat(buf, &st) < 0) 665 continue; 666 if (do_file(agent_fd, deleting, key_only, buf, 667 qflag) == -1) 668 ret = 1; 669 else 670 count++; 671 } 672 if (count == 0) 673 ret = 1; 674 } else { 675 for (i = 0; i < argc; i++) { 676 if (do_file(agent_fd, deleting, key_only, 677 argv[i], qflag) == -1) 678 ret = 1; 679 } 680 } 681 clear_pass(); 682 683 done: 684 ssh_close_authentication_socket(agent_fd); 685 return ret; 686 } 687