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