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