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