1 /* $OpenBSD: ssh-add.c,v 1.155 2020/03/16 02:17:02 dtucker Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Adds an identity to the authentication server, or removes an identity.
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".
14 * SSH2 implementation,
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
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.
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.
40 #include <sys/types.h>
44 # include <openssl/evp.h>
45 # include "openbsd-compat/openssl-compat.h"
65 #include "pathnames.h"
72 extern char *__progname;
74 /* Default files to add */
75 static char *default_files[] = {
77 _PATH_SSH_CLIENT_ID_RSA,
78 _PATH_SSH_CLIENT_ID_DSA,
79 #ifdef OPENSSL_HAS_ECC
80 _PATH_SSH_CLIENT_ID_ECDSA,
81 _PATH_SSH_CLIENT_ID_ECDSA_SK,
83 #endif /* WITH_OPENSSL */
84 _PATH_SSH_CLIENT_ID_ED25519,
85 _PATH_SSH_CLIENT_ID_ED25519_SK,
86 _PATH_SSH_CLIENT_ID_XMSS,
90 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
92 /* Default lifetime (0 == forever) */
93 static long lifetime = 0;
95 /* User has to confirm key use */
96 static int confirm = 0;
98 /* Maximum number of signatures (XMSS) */
99 static u_int maxsign = 0;
100 static u_int minleft = 0;
102 /* we keep a cache of one passphrase */
103 static char *pass = NULL;
108 freezero(pass, strlen(pass));
114 delete_file(int agent_fd, const char *filename, int key_only, int qflag)
116 struct sshkey *public, *cert = NULL;
117 char *certpath = NULL, *comment = NULL;
120 if ((r = sshkey_load_public(filename, &public, &comment)) != 0) {
121 printf("Bad key file %s: %s\n", filename, ssh_err(r));
124 if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
126 fprintf(stderr, "Identity removed: %s (%s)\n",
131 fprintf(stderr, "Could not remove identity \"%s\": %s\n",
132 filename, ssh_err(r));
137 /* Now try to delete the corresponding certificate too */
140 xasprintf(&certpath, "%s-cert.pub", filename);
141 if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
142 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
143 error("Failed to load certificate \"%s\": %s",
144 certpath, ssh_err(r));
148 if (!sshkey_equal_public(cert, public))
149 fatal("Certificate %s does not match private key %s",
152 if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
154 fprintf(stderr, "Identity removed: %s (%s)\n",
159 fprintf(stderr, "Could not remove identity \"%s\": %s\n",
160 certpath, ssh_err(r));
171 /* Send a request to remove all identities. */
173 delete_all(int agent_fd, int qflag)
178 * Since the agent might be forwarded, old or non-OpenSSH, when asked
179 * to remove all keys, attempt to remove both protocol v.1 and v.2
182 if (ssh_remove_all_identities(agent_fd, 2) == 0)
184 /* ignore error-code for ssh1 */
185 ssh_remove_all_identities(agent_fd, 1);
188 fprintf(stderr, "Failed to remove all identities.\n");
190 fprintf(stderr, "All identities removed.\n");
196 add_file(int agent_fd, const char *filename, int key_only, int qflag,
197 const char *skprovider)
199 struct sshkey *private, *cert;
200 char *comment = NULL;
201 char msg[1024], *certpath = NULL;
205 struct sshbuf *keyblob;
206 struct ssh_identitylist *idlist;
208 if (strcmp(filename, "-") == 0) {
210 filename = "(stdin)";
211 } else if ((fd = open(filename, O_RDONLY)) == -1) {
217 * Since we'll try to load a keyfile multiple times, permission errors
218 * will occur multiple times, so check perms first and bail if wrong.
220 if (fd != STDIN_FILENO) {
221 if (sshkey_perm_ok(fd, filename) != 0) {
226 if ((r = sshbuf_load_fd(fd, &keyblob)) != 0) {
227 fprintf(stderr, "Error loading key \"%s\": %s\n",
228 filename, ssh_err(r));
229 sshbuf_free(keyblob);
235 /* At first, try empty passphrase */
236 if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
237 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
238 fprintf(stderr, "Error loading key \"%s\": %s\n",
239 filename, ssh_err(r));
243 if (private == NULL && pass != NULL) {
244 if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
245 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
246 fprintf(stderr, "Error loading key \"%s\": %s\n",
247 filename, ssh_err(r));
251 if (private == NULL) {
252 /* clear passphrase since it did not work */
254 snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
255 filename, confirm ? " (will confirm each use)" : "");
257 pass = read_passphrase(msg, RP_ALLOW_STDIN);
258 if (strcmp(pass, "") == 0)
260 if ((r = sshkey_parse_private_fileblob(keyblob, pass,
261 &private, &comment)) == 0)
263 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
265 "Error loading key \"%s\": %s\n",
266 filename, ssh_err(r));
269 sshbuf_free(keyblob);
273 snprintf(msg, sizeof msg,
274 "Bad passphrase, try again for %s%s: ", filename,
275 confirm ? " (will confirm each use)" : "");
278 if (comment == NULL || *comment == '\0')
279 comment = xstrdup(filename);
280 sshbuf_free(keyblob);
283 if ((r = sshkey_set_filename(private, filename)) != 0) {
284 fprintf(stderr, "Could not add filename to private key: %s (%s)\n",
288 if (maxsign && minleft &&
289 (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) {
290 for (i = 0; i < idlist->nkeys; i++) {
291 if (!sshkey_equal_public(idlist->keys[i], private))
293 left = sshkey_signatures_left(idlist->keys[i]);
294 if (left < minleft) {
296 "Only %d signatures left.\n", left);
299 fprintf(stderr, "Skipping update: ");
300 if (left == minleft) {
302 "required signatures left (%d).\n", left);
305 "more signatures left (%d) than"
306 " required (%d).\n", left, minleft);
308 ssh_free_identitylist(idlist);
311 ssh_free_identitylist(idlist);
314 if (!sshkey_is_sk(private))
315 skprovider = NULL; /* Don't send constraint for other keys */
316 else if (skprovider == NULL) {
317 fprintf(stderr, "Cannot load authenticator-hosted key %s "
318 "without provider\n", filename);
322 if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
323 lifetime, confirm, maxsign, skprovider)) == 0) {
326 fprintf(stderr, "Identity added: %s (%s)\n",
330 "Lifetime set to %ld seconds\n", lifetime);
333 fprintf(stderr, "The user must confirm "
334 "each use of the key\n");
338 fprintf(stderr, "Could not add identity \"%s\": %s\n",
339 filename, ssh_err(r));
342 /* Skip trying to load the cert if requested */
346 /* Now try to add the certificate flavour too */
347 xasprintf(&certpath, "%s-cert.pub", filename);
348 if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
349 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
350 error("Failed to load certificate \"%s\": %s",
351 certpath, ssh_err(r));
355 if (!sshkey_equal_public(cert, private)) {
356 error("Certificate %s does not match private key %s",
362 /* Graft with private bits */
363 if ((r = sshkey_to_certified(private)) != 0) {
364 error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
368 if ((r = sshkey_cert_copy(cert, private)) != 0) {
369 error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
375 if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
376 lifetime, confirm, maxsign, skprovider)) != 0) {
377 error("Certificate %s (%s) add failed: %s", certpath,
378 private->cert->key_id, ssh_err(r));
383 fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
384 private->cert->key_id);
386 fprintf(stderr, "Lifetime set to %ld seconds\n",
390 fprintf(stderr, "The user must confirm each use "
398 sshkey_free(private);
404 update_card(int agent_fd, int add, const char *id, int qflag)
410 if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
411 RP_ALLOW_STDIN)) == NULL)
415 if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
416 lifetime, confirm)) == 0) {
419 fprintf(stderr, "Card %s: %s\n",
420 add ? "added" : "removed", id);
423 fprintf(stderr, "Could not %s card \"%s\": %s\n",
424 add ? "add" : "remove", id, ssh_err(r));
432 test_key(int agent_fd, const char *filename)
434 struct sshkey *key = NULL;
440 if ((r = sshkey_load_public(filename, &key, NULL)) != 0) {
441 error("Couldn't read public key %s: %s", filename, ssh_err(r));
444 arc4random_buf(data, sizeof(data));
445 if ((r = ssh_agent_sign(agent_fd, key, &sig, &slen, data, sizeof(data),
447 error("Agent signature failed for %s: %s",
448 filename, ssh_err(r));
451 if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
452 NULL, 0, NULL)) != 0) {
453 error("Signature verification failed for %s: %s",
454 filename, ssh_err(r));
466 list_identities(int agent_fd, int do_fp)
470 struct ssh_identitylist *idlist;
474 if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
475 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
476 fprintf(stderr, "error fetching identities: %s\n",
479 printf("The agent has no identities.\n");
482 for (i = 0; i < idlist->nkeys; i++) {
484 fp = sshkey_fingerprint(idlist->keys[i],
485 fingerprint_hash, SSH_FP_DEFAULT);
486 printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
487 fp == NULL ? "(null)" : fp, idlist->comments[i],
488 sshkey_type(idlist->keys[i]));
491 if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
492 fprintf(stderr, "sshkey_write: %s\n",
496 fprintf(stdout, " %s", idlist->comments[i]);
497 left = sshkey_signatures_left(idlist->keys[i]);
500 " [signatures left %d]", left);
501 fprintf(stdout, "\n");
504 ssh_free_identitylist(idlist);
509 lock_agent(int agent_fd, int lock)
511 char prompt[100], *p1, *p2;
512 int r, passok = 1, ret = -1;
514 strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
515 p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
517 strlcpy(prompt, "Again: ", sizeof prompt);
518 p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
519 if (strcmp(p1, p2) != 0) {
520 fprintf(stderr, "Passwords do not match.\n");
523 freezero(p2, strlen(p2));
526 if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
527 fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
530 fprintf(stderr, "Failed to %slock agent: %s\n",
531 lock ? "" : "un", ssh_err(r));
534 freezero(p1, strlen(p1));
539 load_resident_keys(int agent_fd, const char *skprovider, int qflag)
541 struct sshkey **keys;
546 pass = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
547 if ((r = sshsk_load_resident(skprovider, NULL, pass,
548 &keys, &nkeys)) != 0) {
549 error("Unable to load resident keys: %s", ssh_err(r));
552 for (i = 0; i < nkeys; i++) {
553 if ((fp = sshkey_fingerprint(keys[i],
554 fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
555 fatal("%s: sshkey_fingerprint failed", __func__);
556 if ((r = ssh_add_identity_constrained(agent_fd, keys[i], "",
557 lifetime, confirm, maxsign, skprovider)) != 0) {
558 error("Unable to add key %s %s",
559 sshkey_type(keys[i]), fp);
567 fprintf(stderr, "Resident identity added: %s %s\n",
568 sshkey_type(keys[i]), fp);
571 "Lifetime set to %ld seconds\n", lifetime);
574 fprintf(stderr, "The user must confirm "
575 "each use of the key\n");
579 sshkey_free(keys[i]);
583 return SSH_ERR_KEY_NOT_FOUND;
584 return ok == 1 ? 0 : ok;
588 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag,
589 const char *skprovider)
592 if (delete_file(agent_fd, file, key_only, qflag) == -1)
595 if (add_file(agent_fd, file, key_only, qflag, skprovider) == -1)
605 "usage: ssh-add [-cDdKkLlqvXx] [-E fingerprint_hash] [-S provider] [-t life]\n"
607 " [-M maxsign] [-m minleft]\n"
610 " ssh-add -s pkcs11\n"
611 " ssh-add -e pkcs11\n"
612 " ssh-add -T pubkey ...\n"
617 main(int argc, char **argv)
622 char *pkcs11provider = NULL, *skprovider = NULL;
623 int r, i, ch, deleting = 0, ret = 0, key_only = 0, do_download = 0;
624 int xflag = 0, lflag = 0, Dflag = 0, qflag = 0, Tflag = 0;
625 SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
626 LogLevel log_level = SYSLOG_LEVEL_INFO;
628 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
631 __progname = ssh_get_progname(argv[0]);
634 log_init(__progname, log_level, log_facility, 1);
636 setvbuf(stdout, NULL, _IOLBF, 0);
638 /* First, get a connection to the authentication agent. */
639 switch (r = ssh_get_authentication_socket(&agent_fd)) {
642 case SSH_ERR_AGENT_NOT_PRESENT:
643 fprintf(stderr, "Could not open a connection to your "
644 "authentication agent.\n");
647 fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
651 skprovider = getenv("SSH_SK_PROVIDER");
653 while ((ch = getopt(argc, argv, "vkKlLcdDTxXE:e:M:m:qs:S:t:")) != -1) {
656 if (log_level == SYSLOG_LEVEL_INFO)
657 log_level = SYSLOG_LEVEL_DEBUG1;
658 else if (log_level < SYSLOG_LEVEL_DEBUG3)
662 fingerprint_hash = ssh_digest_alg_by_name(optarg);
663 if (fingerprint_hash == -1)
664 fatal("Invalid hash algorithm \"%s\"", optarg);
675 fatal("-%c flag already specified", lflag);
681 fatal("-%c flag already specified", xflag);
688 minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL);
696 maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL);
710 pkcs11provider = optarg;
717 pkcs11provider = optarg;
720 if ((lifetime = convtime(optarg)) == -1 ||
721 lifetime < 0 || (u_long)lifetime > UINT32_MAX) {
722 fprintf(stderr, "Invalid lifetime\n");
739 log_init(__progname, log_level, log_facility, 1);
741 if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
742 fatal("Invalid combination of actions");
744 if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
748 if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
752 if (delete_all(agent_fd, qflag) == -1)
757 #ifdef ENABLE_SK_INTERNAL
758 if (skprovider == NULL)
759 skprovider = "internal";
766 fatal("no keys to test");
767 for (r = i = 0; i < argc; i++)
768 r |= test_key(agent_fd, argv[i]);
769 ret = r == 0 ? 0 : 1;
772 if (pkcs11provider != NULL) {
773 if (update_card(agent_fd, !deleting, pkcs11provider,
779 if (skprovider == NULL)
780 fatal("Cannot download keys without provider");
781 if (load_resident_keys(agent_fd, skprovider, qflag) != 0)
791 if ((pw = getpwuid(getuid())) == NULL) {
792 fprintf(stderr, "No user found with uid %u\n",
798 for (i = 0; default_files[i]; i++) {
799 snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
801 if (stat(buf, &st) == -1)
803 if (do_file(agent_fd, deleting, key_only, buf,
804 qflag, skprovider) == -1)
812 for (i = 0; i < argc; i++) {
813 if (do_file(agent_fd, deleting, key_only,
814 argv[i], qflag, skprovider) == -1)
820 ssh_close_authentication_socket(agent_fd);