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