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