xref: /freebsd/crypto/openssh/ssh-add.c (revision fe6060f10f634930ff71b7c50291ddc610da2475)
1 /* $OpenBSD: ssh-add.c,v 1.160 2021/04/03 06:18:41 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 "includes.h"
39 
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 
43 #ifdef WITH_OPENSSL
44 # include <openssl/evp.h>
45 # include "openbsd-compat/openssl-compat.h"
46 #endif
47 
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <pwd.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <limits.h>
57 
58 #include "xmalloc.h"
59 #include "ssh.h"
60 #include "log.h"
61 #include "sshkey.h"
62 #include "sshbuf.h"
63 #include "authfd.h"
64 #include "authfile.h"
65 #include "pathnames.h"
66 #include "misc.h"
67 #include "ssherr.h"
68 #include "digest.h"
69 #include "ssh-sk.h"
70 #include "sk-api.h"
71 
72 /* argv0 */
73 extern char *__progname;
74 
75 /* Default files to add */
76 static char *default_files[] = {
77 #ifdef WITH_OPENSSL
78 	_PATH_SSH_CLIENT_ID_RSA,
79 	_PATH_SSH_CLIENT_ID_DSA,
80 #ifdef OPENSSL_HAS_ECC
81 	_PATH_SSH_CLIENT_ID_ECDSA,
82 	_PATH_SSH_CLIENT_ID_ECDSA_SK,
83 #endif
84 #endif /* WITH_OPENSSL */
85 	_PATH_SSH_CLIENT_ID_ED25519,
86 	_PATH_SSH_CLIENT_ID_ED25519_SK,
87 	_PATH_SSH_CLIENT_ID_XMSS,
88 	NULL
89 };
90 
91 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
92 
93 /* Default lifetime (0 == forever) */
94 static int lifetime = 0;
95 
96 /* User has to confirm key use */
97 static int confirm = 0;
98 
99 /* Maximum number of signatures (XMSS) */
100 static u_int maxsign = 0;
101 static u_int minleft = 0;
102 
103 /* we keep a cache of one passphrase */
104 static char *pass = NULL;
105 static void
106 clear_pass(void)
107 {
108 	if (pass) {
109 		freezero(pass, strlen(pass));
110 		pass = NULL;
111 	}
112 }
113 
114 static int
115 delete_one(int agent_fd, const struct sshkey *key, const char *comment,
116     const char *path, int qflag)
117 {
118 	int r;
119 
120 	if ((r = ssh_remove_identity(agent_fd, key)) != 0) {
121 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
122 		    path, ssh_err(r));
123 		return r;
124 	}
125 	if (!qflag) {
126 		fprintf(stderr, "Identity removed: %s %s (%s)\n", path,
127 		    sshkey_type(key), comment);
128 	}
129 	return 0;
130 }
131 
132 static int
133 delete_stdin(int agent_fd, int qflag)
134 {
135 	char *line = NULL, *cp;
136 	size_t linesize = 0;
137 	struct sshkey *key = NULL;
138 	int lnum = 0, r, ret = -1;
139 
140 	while (getline(&line, &linesize, stdin) != -1) {
141 		lnum++;
142 		sshkey_free(key);
143 		key = NULL;
144 		line[strcspn(line, "\n")] = '\0';
145 		cp = line + strspn(line, " \t");
146 		if (*cp == '#' || *cp == '\0')
147 			continue;
148 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
149 			fatal_f("sshkey_new");
150 		if ((r = sshkey_read(key, &cp)) != 0) {
151 			error_r(r, "(stdin):%d: invalid key", lnum);
152 			continue;
153 		}
154 		if (delete_one(agent_fd, key, cp, "(stdin)", qflag) == 0)
155 			ret = 0;
156 	}
157 	sshkey_free(key);
158 	free(line);
159 	return ret;
160 }
161 
162 static int
163 delete_file(int agent_fd, const char *filename, int key_only, int qflag)
164 {
165 	struct sshkey *public, *cert = NULL;
166 	char *certpath = NULL, *comment = NULL;
167 	int r, ret = -1;
168 
169 	if (strcmp(filename, "-") == 0)
170 		return delete_stdin(agent_fd, qflag);
171 
172 	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
173 		printf("Bad key file %s: %s\n", filename, ssh_err(r));
174 		return -1;
175 	}
176 	if (delete_one(agent_fd, public, comment, filename, qflag) == 0)
177 		ret = 0;
178 
179 	if (key_only)
180 		goto out;
181 
182 	/* Now try to delete the corresponding certificate too */
183 	free(comment);
184 	comment = NULL;
185 	xasprintf(&certpath, "%s-cert.pub", filename);
186 	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
187 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
188 			error_r(r, "Failed to load certificate \"%s\"", certpath);
189 		goto out;
190 	}
191 
192 	if (!sshkey_equal_public(cert, public))
193 		fatal("Certificate %s does not match private key %s",
194 		    certpath, filename);
195 
196 	if (delete_one(agent_fd, cert, comment, certpath, qflag) == 0)
197 		ret = 0;
198 
199  out:
200 	sshkey_free(cert);
201 	sshkey_free(public);
202 	free(certpath);
203 	free(comment);
204 
205 	return ret;
206 }
207 
208 /* Send a request to remove all identities. */
209 static int
210 delete_all(int agent_fd, int qflag)
211 {
212 	int ret = -1;
213 
214 	/*
215 	 * Since the agent might be forwarded, old or non-OpenSSH, when asked
216 	 * to remove all keys, attempt to remove both protocol v.1 and v.2
217 	 * keys.
218 	 */
219 	if (ssh_remove_all_identities(agent_fd, 2) == 0)
220 		ret = 0;
221 	/* ignore error-code for ssh1 */
222 	ssh_remove_all_identities(agent_fd, 1);
223 
224 	if (ret != 0)
225 		fprintf(stderr, "Failed to remove all identities.\n");
226 	else if (!qflag)
227 		fprintf(stderr, "All identities removed.\n");
228 
229 	return ret;
230 }
231 
232 static int
233 add_file(int agent_fd, const char *filename, int key_only, int qflag,
234     const char *skprovider)
235 {
236 	struct sshkey *private, *cert;
237 	char *comment = NULL;
238 	char msg[1024], *certpath = NULL;
239 	int r, fd, ret = -1;
240 	size_t i;
241 	u_int32_t left;
242 	struct sshbuf *keyblob;
243 	struct ssh_identitylist *idlist;
244 
245 	if (strcmp(filename, "-") == 0) {
246 		fd = STDIN_FILENO;
247 		filename = "(stdin)";
248 	} else if ((fd = open(filename, O_RDONLY)) == -1) {
249 		perror(filename);
250 		return -1;
251 	}
252 
253 	/*
254 	 * Since we'll try to load a keyfile multiple times, permission errors
255 	 * will occur multiple times, so check perms first and bail if wrong.
256 	 */
257 	if (fd != STDIN_FILENO) {
258 		if (sshkey_perm_ok(fd, filename) != 0) {
259 			close(fd);
260 			return -1;
261 		}
262 	}
263 	if ((r = sshbuf_load_fd(fd, &keyblob)) != 0) {
264 		fprintf(stderr, "Error loading key \"%s\": %s\n",
265 		    filename, ssh_err(r));
266 		sshbuf_free(keyblob);
267 		close(fd);
268 		return -1;
269 	}
270 	close(fd);
271 
272 	/* At first, try empty passphrase */
273 	if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
274 	    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
275 		fprintf(stderr, "Error loading key \"%s\": %s\n",
276 		    filename, ssh_err(r));
277 		goto fail_load;
278 	}
279 	/* try last */
280 	if (private == NULL && pass != NULL) {
281 		if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
282 		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
283 			fprintf(stderr, "Error loading key \"%s\": %s\n",
284 			    filename, ssh_err(r));
285 			goto fail_load;
286 		}
287 	}
288 	if (private == NULL) {
289 		/* clear passphrase since it did not work */
290 		clear_pass();
291 		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
292 		    filename, confirm ? " (will confirm each use)" : "");
293 		for (;;) {
294 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
295 			if (strcmp(pass, "") == 0)
296 				goto fail_load;
297 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
298 			    &private, &comment)) == 0)
299 				break;
300 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
301 				fprintf(stderr,
302 				    "Error loading key \"%s\": %s\n",
303 				    filename, ssh_err(r));
304  fail_load:
305 				clear_pass();
306 				sshbuf_free(keyblob);
307 				return -1;
308 			}
309 			clear_pass();
310 			snprintf(msg, sizeof msg,
311 			    "Bad passphrase, try again for %s%s: ", filename,
312 			    confirm ? " (will confirm each use)" : "");
313 		}
314 	}
315 	if (comment == NULL || *comment == '\0')
316 		comment = xstrdup(filename);
317 	sshbuf_free(keyblob);
318 
319 	/* For XMSS */
320 	if ((r = sshkey_set_filename(private, filename)) != 0) {
321 		fprintf(stderr, "Could not add filename to private key: %s (%s)\n",
322 		    filename, comment);
323 		goto out;
324 	}
325 	if (maxsign && minleft &&
326 	    (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) {
327 		for (i = 0; i < idlist->nkeys; i++) {
328 			if (!sshkey_equal_public(idlist->keys[i], private))
329 				continue;
330 			left = sshkey_signatures_left(idlist->keys[i]);
331 			if (left < minleft) {
332 				fprintf(stderr,
333 				    "Only %d signatures left.\n", left);
334 				break;
335 			}
336 			fprintf(stderr, "Skipping update: ");
337 			if (left == minleft) {
338 				fprintf(stderr,
339 				    "required signatures left (%d).\n", left);
340 			} else {
341 				fprintf(stderr,
342 				    "more signatures left (%d) than"
343 				    " required (%d).\n", left, minleft);
344 			}
345 			ssh_free_identitylist(idlist);
346 			goto out;
347 		}
348 		ssh_free_identitylist(idlist);
349 	}
350 
351 	if (sshkey_is_sk(private)) {
352 		if (skprovider == NULL) {
353 			fprintf(stderr, "Cannot load FIDO key %s "
354 			    "without provider\n", filename);
355 			goto out;
356 		}
357 		if ((private->sk_flags & SSH_SK_USER_VERIFICATION_REQD) != 0) {
358 			fprintf(stderr, "FIDO verify-required key %s is not "
359 			    "currently supported by ssh-agent\n", filename);
360 			goto out;
361 		}
362 	} else {
363 		/* Don't send provider constraint for other keys */
364 		skprovider = NULL;
365 	}
366 
367 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
368 	    lifetime, confirm, maxsign, skprovider)) == 0) {
369 		ret = 0;
370 		if (!qflag) {
371 			fprintf(stderr, "Identity added: %s (%s)\n",
372 			    filename, comment);
373 			if (lifetime != 0) {
374 				fprintf(stderr,
375 				    "Lifetime set to %d seconds\n", lifetime);
376 			}
377 			if (confirm != 0) {
378 				fprintf(stderr, "The user must confirm "
379 				    "each use of the key\n");
380 			}
381 		}
382 	} else {
383 		fprintf(stderr, "Could not add identity \"%s\": %s\n",
384 		    filename, ssh_err(r));
385 	}
386 
387 	/* Skip trying to load the cert if requested */
388 	if (key_only)
389 		goto out;
390 
391 	/* Now try to add the certificate flavour too */
392 	xasprintf(&certpath, "%s-cert.pub", filename);
393 	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
394 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
395 			error_r(r, "Failed to load certificate \"%s\"", certpath);
396 		goto out;
397 	}
398 
399 	if (!sshkey_equal_public(cert, private)) {
400 		error("Certificate %s does not match private key %s",
401 		    certpath, filename);
402 		sshkey_free(cert);
403 		goto out;
404 	}
405 
406 	/* Graft with private bits */
407 	if ((r = sshkey_to_certified(private)) != 0) {
408 		error_fr(r, "sshkey_to_certified");
409 		sshkey_free(cert);
410 		goto out;
411 	}
412 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
413 		error_fr(r, "sshkey_cert_copy");
414 		sshkey_free(cert);
415 		goto out;
416 	}
417 	sshkey_free(cert);
418 
419 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
420 	    lifetime, confirm, maxsign, skprovider)) != 0) {
421 		error_r(r, "Certificate %s (%s) add failed", certpath,
422 		    private->cert->key_id);
423 		goto out;
424 	}
425 	/* success */
426 	if (!qflag) {
427 		fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
428 		    private->cert->key_id);
429 		if (lifetime != 0) {
430 			fprintf(stderr, "Lifetime set to %d seconds\n",
431 			    lifetime);
432 		}
433 		if (confirm != 0) {
434 			fprintf(stderr, "The user must confirm each use "
435 			    "of the key\n");
436 		}
437 	}
438 
439  out:
440 	free(certpath);
441 	free(comment);
442 	sshkey_free(private);
443 
444 	return ret;
445 }
446 
447 static int
448 update_card(int agent_fd, int add, const char *id, int qflag)
449 {
450 	char *pin = NULL;
451 	int r, ret = -1;
452 
453 	if (add) {
454 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
455 		    RP_ALLOW_STDIN)) == NULL)
456 			return -1;
457 	}
458 
459 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
460 	    lifetime, confirm)) == 0) {
461 		ret = 0;
462 		if (!qflag) {
463 			fprintf(stderr, "Card %s: %s\n",
464 			    add ? "added" : "removed", id);
465 		}
466 	} else {
467 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
468 		    add ? "add" : "remove", id, ssh_err(r));
469 		ret = -1;
470 	}
471 	free(pin);
472 	return ret;
473 }
474 
475 static int
476 test_key(int agent_fd, const char *filename)
477 {
478 	struct sshkey *key = NULL;
479 	u_char *sig = NULL;
480 	size_t slen = 0;
481 	int r, ret = -1;
482 	char data[1024];
483 
484 	if ((r = sshkey_load_public(filename, &key, NULL)) != 0) {
485 		error_r(r, "Couldn't read public key %s", filename);
486 		return -1;
487 	}
488 	arc4random_buf(data, sizeof(data));
489 	if ((r = ssh_agent_sign(agent_fd, key, &sig, &slen, data, sizeof(data),
490 	    NULL, 0)) != 0) {
491 		error_r(r, "Agent signature failed for %s", filename);
492 		goto done;
493 	}
494 	if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
495 	    NULL, 0, NULL)) != 0) {
496 		error_r(r, "Signature verification failed for %s", filename);
497 		goto done;
498 	}
499 	/* success */
500 	ret = 0;
501  done:
502 	free(sig);
503 	sshkey_free(key);
504 	return ret;
505 }
506 
507 static int
508 list_identities(int agent_fd, int do_fp)
509 {
510 	char *fp;
511 	int r;
512 	struct ssh_identitylist *idlist;
513 	u_int32_t left;
514 	size_t i;
515 
516 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
517 		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
518 			fprintf(stderr, "error fetching identities: %s\n",
519 			    ssh_err(r));
520 		else
521 			printf("The agent has no identities.\n");
522 		return -1;
523 	}
524 	for (i = 0; i < idlist->nkeys; i++) {
525 		if (do_fp) {
526 			fp = sshkey_fingerprint(idlist->keys[i],
527 			    fingerprint_hash, SSH_FP_DEFAULT);
528 			printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
529 			    fp == NULL ? "(null)" : fp, idlist->comments[i],
530 			    sshkey_type(idlist->keys[i]));
531 			free(fp);
532 		} else {
533 			if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
534 				fprintf(stderr, "sshkey_write: %s\n",
535 				    ssh_err(r));
536 				continue;
537 			}
538 			fprintf(stdout, " %s", idlist->comments[i]);
539 			left = sshkey_signatures_left(idlist->keys[i]);
540 			if (left > 0)
541 				fprintf(stdout,
542 				    " [signatures left %d]", left);
543 			fprintf(stdout, "\n");
544 		}
545 	}
546 	ssh_free_identitylist(idlist);
547 	return 0;
548 }
549 
550 static int
551 lock_agent(int agent_fd, int lock)
552 {
553 	char prompt[100], *p1, *p2;
554 	int r, passok = 1, ret = -1;
555 
556 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
557 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
558 	if (lock) {
559 		strlcpy(prompt, "Again: ", sizeof prompt);
560 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
561 		if (strcmp(p1, p2) != 0) {
562 			fprintf(stderr, "Passwords do not match.\n");
563 			passok = 0;
564 		}
565 		freezero(p2, strlen(p2));
566 	}
567 	if (passok) {
568 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
569 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
570 			ret = 0;
571 		} else {
572 			fprintf(stderr, "Failed to %slock agent: %s\n",
573 			    lock ? "" : "un", ssh_err(r));
574 		}
575 	}
576 	freezero(p1, strlen(p1));
577 	return (ret);
578 }
579 
580 static int
581 load_resident_keys(int agent_fd, const char *skprovider, int qflag)
582 {
583 	struct sshkey **keys;
584 	size_t nkeys, i;
585 	int r, ok = 0;
586 	char *fp;
587 
588 	pass = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
589 	if ((r = sshsk_load_resident(skprovider, NULL, pass,
590 	    &keys, &nkeys)) != 0) {
591 		error_r(r, "Unable to load resident keys");
592 		return r;
593 	}
594 	for (i = 0; i < nkeys; i++) {
595 		if ((fp = sshkey_fingerprint(keys[i],
596 		    fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
597 			fatal_f("sshkey_fingerprint failed");
598 		if ((r = ssh_add_identity_constrained(agent_fd, keys[i], "",
599 		    lifetime, confirm, maxsign, skprovider)) != 0) {
600 			error("Unable to add key %s %s",
601 			    sshkey_type(keys[i]), fp);
602 			free(fp);
603 			ok = r;
604 			continue;
605 		}
606 		if (ok == 0)
607 			ok = 1;
608 		if (!qflag) {
609 			fprintf(stderr, "Resident identity added: %s %s\n",
610 			    sshkey_type(keys[i]), fp);
611 			if (lifetime != 0) {
612 				fprintf(stderr,
613 				    "Lifetime set to %d seconds\n", lifetime);
614 			}
615 			if (confirm != 0) {
616 				fprintf(stderr, "The user must confirm "
617 				    "each use of the key\n");
618 			}
619 		}
620 		free(fp);
621 		sshkey_free(keys[i]);
622 	}
623 	free(keys);
624 	if (nkeys == 0)
625 		return SSH_ERR_KEY_NOT_FOUND;
626 	return ok == 1 ? 0 : ok;
627 }
628 
629 static int
630 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag,
631     const char *skprovider)
632 {
633 	if (deleting) {
634 		if (delete_file(agent_fd, file, key_only, qflag) == -1)
635 			return -1;
636 	} else {
637 		if (add_file(agent_fd, file, key_only, qflag, skprovider) == -1)
638 			return -1;
639 	}
640 	return 0;
641 }
642 
643 static void
644 usage(void)
645 {
646 	fprintf(stderr,
647 "usage: ssh-add [-cDdKkLlqvXx] [-E fingerprint_hash] [-S provider] [-t life]\n"
648 #ifdef WITH_XMSS
649 "               [-M maxsign] [-m minleft]\n"
650 #endif
651 "               [file ...]\n"
652 "       ssh-add -s pkcs11\n"
653 "       ssh-add -e pkcs11\n"
654 "       ssh-add -T pubkey ...\n"
655 	);
656 }
657 
658 int
659 main(int argc, char **argv)
660 {
661 	extern char *optarg;
662 	extern int optind;
663 	int agent_fd;
664 	char *pkcs11provider = NULL, *skprovider = NULL;
665 	int r, i, ch, deleting = 0, ret = 0, key_only = 0, do_download = 0;
666 	int xflag = 0, lflag = 0, Dflag = 0, qflag = 0, Tflag = 0;
667 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
668 	LogLevel log_level = SYSLOG_LEVEL_INFO;
669 
670 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
671 	sanitise_stdfd();
672 
673 	__progname = ssh_get_progname(argv[0]);
674 	seed_rng();
675 
676 	log_init(__progname, log_level, log_facility, 1);
677 
678 	setvbuf(stdout, NULL, _IOLBF, 0);
679 
680 	/* First, get a connection to the authentication agent. */
681 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
682 	case 0:
683 		break;
684 	case SSH_ERR_AGENT_NOT_PRESENT:
685 		fprintf(stderr, "Could not open a connection to your "
686 		    "authentication agent.\n");
687 		exit(2);
688 	default:
689 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
690 		exit(2);
691 	}
692 
693 	skprovider = getenv("SSH_SK_PROVIDER");
694 
695 	while ((ch = getopt(argc, argv, "vkKlLcdDTxXE:e:M:m:qs:S:t:")) != -1) {
696 		switch (ch) {
697 		case 'v':
698 			if (log_level == SYSLOG_LEVEL_INFO)
699 				log_level = SYSLOG_LEVEL_DEBUG1;
700 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
701 				log_level++;
702 			break;
703 		case 'E':
704 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
705 			if (fingerprint_hash == -1)
706 				fatal("Invalid hash algorithm \"%s\"", optarg);
707 			break;
708 		case 'k':
709 			key_only = 1;
710 			break;
711 		case 'K':
712 			do_download = 1;
713 			break;
714 		case 'l':
715 		case 'L':
716 			if (lflag != 0)
717 				fatal("-%c flag already specified", lflag);
718 			lflag = ch;
719 			break;
720 		case 'x':
721 		case 'X':
722 			if (xflag != 0)
723 				fatal("-%c flag already specified", xflag);
724 			xflag = ch;
725 			break;
726 		case 'c':
727 			confirm = 1;
728 			break;
729 		case 'm':
730 			minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL);
731 			if (minleft == 0) {
732 				usage();
733 				ret = 1;
734 				goto done;
735 			}
736 			break;
737 		case 'M':
738 			maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL);
739 			if (maxsign == 0) {
740 				usage();
741 				ret = 1;
742 				goto done;
743 			}
744 			break;
745 		case 'd':
746 			deleting = 1;
747 			break;
748 		case 'D':
749 			Dflag = 1;
750 			break;
751 		case 's':
752 			pkcs11provider = optarg;
753 			break;
754 		case 'S':
755 			skprovider = optarg;
756 			break;
757 		case 'e':
758 			deleting = 1;
759 			pkcs11provider = optarg;
760 			break;
761 		case 't':
762 			if ((lifetime = convtime(optarg)) == -1 ||
763 			    lifetime < 0 || (u_long)lifetime > UINT32_MAX) {
764 				fprintf(stderr, "Invalid lifetime\n");
765 				ret = 1;
766 				goto done;
767 			}
768 			break;
769 		case 'q':
770 			qflag = 1;
771 			break;
772 		case 'T':
773 			Tflag = 1;
774 			break;
775 		default:
776 			usage();
777 			ret = 1;
778 			goto done;
779 		}
780 	}
781 	log_init(__progname, log_level, log_facility, 1);
782 
783 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
784 		fatal("Invalid combination of actions");
785 	else if (xflag) {
786 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
787 			ret = 1;
788 		goto done;
789 	} else if (lflag) {
790 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
791 			ret = 1;
792 		goto done;
793 	} else if (Dflag) {
794 		if (delete_all(agent_fd, qflag) == -1)
795 			ret = 1;
796 		goto done;
797 	}
798 
799 #ifdef ENABLE_SK_INTERNAL
800 	if (skprovider == NULL)
801 		skprovider = "internal";
802 #endif
803 
804 	argc -= optind;
805 	argv += optind;
806 	if (Tflag) {
807 		if (argc <= 0)
808 			fatal("no keys to test");
809 		for (r = i = 0; i < argc; i++)
810 			r |= test_key(agent_fd, argv[i]);
811 		ret = r == 0 ? 0 : 1;
812 		goto done;
813 	}
814 	if (pkcs11provider != NULL) {
815 		if (update_card(agent_fd, !deleting, pkcs11provider,
816 		    qflag) == -1)
817 			ret = 1;
818 		goto done;
819 	}
820 	if (do_download) {
821 		if (skprovider == NULL)
822 			fatal("Cannot download keys without provider");
823 		if (load_resident_keys(agent_fd, skprovider, qflag) != 0)
824 			ret = 1;
825 		goto done;
826 	}
827 	if (argc == 0) {
828 		char buf[PATH_MAX];
829 		struct passwd *pw;
830 		struct stat st;
831 		int count = 0;
832 
833 		if ((pw = getpwuid(getuid())) == NULL) {
834 			fprintf(stderr, "No user found with uid %u\n",
835 			    (u_int)getuid());
836 			ret = 1;
837 			goto done;
838 		}
839 
840 		for (i = 0; default_files[i]; i++) {
841 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
842 			    default_files[i]);
843 			if (stat(buf, &st) == -1)
844 				continue;
845 			if (do_file(agent_fd, deleting, key_only, buf,
846 			    qflag, skprovider) == -1)
847 				ret = 1;
848 			else
849 				count++;
850 		}
851 		if (count == 0)
852 			ret = 1;
853 	} else {
854 		for (i = 0; i < argc; i++) {
855 			if (do_file(agent_fd, deleting, key_only,
856 			    argv[i], qflag, skprovider) == -1)
857 				ret = 1;
858 		}
859 	}
860 done:
861 	clear_pass();
862 	ssh_close_authentication_socket(agent_fd);
863 	return ret;
864 }
865