xref: /freebsd/crypto/openssh/ssh-add.c (revision 2e3f49888ec8851bafb22011533217487764fdb0)
1 /* $OpenBSD: ssh-add.c,v 1.169 2023/12/18 14:46:56 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Adds an identity to the authentication server, or removes an identity.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  * SSH2 implementation,
15  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "includes.h"
39 
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 
43 #ifdef WITH_OPENSSL
44 # include <openssl/evp.h>
45 # include "openbsd-compat/openssl-compat.h"
46 #endif
47 
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <pwd.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <limits.h>
57 
58 #include "xmalloc.h"
59 #include "ssh.h"
60 #include "log.h"
61 #include "sshkey.h"
62 #include "sshbuf.h"
63 #include "authfd.h"
64 #include "authfile.h"
65 #include "pathnames.h"
66 #include "misc.h"
67 #include "ssherr.h"
68 #include "digest.h"
69 #include "ssh-sk.h"
70 #include "sk-api.h"
71 #include "hostfile.h"
72 
73 /* argv0 */
74 extern char *__progname;
75 
76 /* Default files to add */
77 static char *default_files[] = {
78 #ifdef WITH_OPENSSL
79 	_PATH_SSH_CLIENT_ID_RSA,
80 #ifdef OPENSSL_HAS_ECC
81 	_PATH_SSH_CLIENT_ID_ECDSA,
82 	_PATH_SSH_CLIENT_ID_ECDSA_SK,
83 #endif
84 #endif /* WITH_OPENSSL */
85 	_PATH_SSH_CLIENT_ID_ED25519,
86 	_PATH_SSH_CLIENT_ID_ED25519_SK,
87 	_PATH_SSH_CLIENT_ID_XMSS,
88 	_PATH_SSH_CLIENT_ID_DSA,
89 	NULL
90 };
91 
92 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
93 
94 /* Default lifetime (0 == forever) */
95 static int lifetime = 0;
96 
97 /* User has to confirm key use */
98 static int confirm = 0;
99 
100 /* Maximum number of signatures (XMSS) */
101 static u_int maxsign = 0;
102 static u_int minleft = 0;
103 
104 /* we keep a cache of one passphrase */
105 static char *pass = NULL;
106 static void
107 clear_pass(void)
108 {
109 	if (pass) {
110 		freezero(pass, strlen(pass));
111 		pass = NULL;
112 	}
113 }
114 
115 static int
116 delete_one(int agent_fd, const struct sshkey *key, const char *comment,
117     const char *path, int qflag)
118 {
119 	int r;
120 
121 	if ((r = ssh_remove_identity(agent_fd, key)) != 0) {
122 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
123 		    path, ssh_err(r));
124 		return r;
125 	}
126 	if (!qflag) {
127 		fprintf(stderr, "Identity removed: %s %s (%s)\n", path,
128 		    sshkey_type(key), comment ? comment : "no comment");
129 	}
130 	return 0;
131 }
132 
133 static int
134 delete_stdin(int agent_fd, int qflag, int key_only, int cert_only)
135 {
136 	char *line = NULL, *cp;
137 	size_t linesize = 0;
138 	struct sshkey *key = NULL;
139 	int lnum = 0, r, ret = -1;
140 
141 	while (getline(&line, &linesize, stdin) != -1) {
142 		lnum++;
143 		sshkey_free(key);
144 		key = NULL;
145 		line[strcspn(line, "\n")] = '\0';
146 		cp = line + strspn(line, " \t");
147 		if (*cp == '#' || *cp == '\0')
148 			continue;
149 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
150 			fatal_f("sshkey_new");
151 		if ((r = sshkey_read(key, &cp)) != 0) {
152 			error_r(r, "(stdin):%d: invalid key", lnum);
153 			continue;
154 		}
155 		if ((!key_only && !cert_only) ||
156 		    (key_only && !sshkey_is_cert(key)) ||
157 		    (cert_only && sshkey_is_cert(key))) {
158 			if (delete_one(agent_fd, key, cp,
159 			    "(stdin)", qflag) == 0)
160 				ret = 0;
161 		}
162 	}
163 	sshkey_free(key);
164 	free(line);
165 	return ret;
166 }
167 
168 static int
169 delete_file(int agent_fd, const char *filename, int key_only,
170     int cert_only, int qflag)
171 {
172 	struct sshkey *public, *cert = NULL;
173 	char *certpath = NULL, *comment = NULL;
174 	int r, ret = -1;
175 
176 	if (strcmp(filename, "-") == 0)
177 		return delete_stdin(agent_fd, qflag, key_only, cert_only);
178 
179 	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
180 		printf("Bad key file %s: %s\n", filename, ssh_err(r));
181 		return -1;
182 	}
183 	if ((!key_only && !cert_only) ||
184 	    (key_only && !sshkey_is_cert(public)) ||
185 	    (cert_only && sshkey_is_cert(public))) {
186 		if (delete_one(agent_fd, public, comment, filename, qflag) == 0)
187 			ret = 0;
188 	}
189 
190 	if (key_only)
191 		goto out;
192 
193 	/* Now try to delete the corresponding certificate too */
194 	free(comment);
195 	comment = NULL;
196 	xasprintf(&certpath, "%s-cert.pub", filename);
197 	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
198 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
199 			error_r(r, "Failed to load certificate \"%s\"", certpath);
200 		goto out;
201 	}
202 
203 	if (!sshkey_equal_public(cert, public))
204 		fatal("Certificate %s does not match private key %s",
205 		    certpath, filename);
206 
207 	if (delete_one(agent_fd, cert, comment, certpath, qflag) == 0)
208 		ret = 0;
209 
210  out:
211 	sshkey_free(cert);
212 	sshkey_free(public);
213 	free(certpath);
214 	free(comment);
215 
216 	return ret;
217 }
218 
219 /* Send a request to remove all identities. */
220 static int
221 delete_all(int agent_fd, int qflag)
222 {
223 	int ret = -1;
224 
225 	/*
226 	 * Since the agent might be forwarded, old or non-OpenSSH, when asked
227 	 * to remove all keys, attempt to remove both protocol v.1 and v.2
228 	 * keys.
229 	 */
230 	if (ssh_remove_all_identities(agent_fd, 2) == 0)
231 		ret = 0;
232 	/* ignore error-code for ssh1 */
233 	ssh_remove_all_identities(agent_fd, 1);
234 
235 	if (ret != 0)
236 		fprintf(stderr, "Failed to remove all identities.\n");
237 	else if (!qflag)
238 		fprintf(stderr, "All identities removed.\n");
239 
240 	return ret;
241 }
242 
243 static int
244 add_file(int agent_fd, const char *filename, int key_only, int cert_only,
245     int qflag, const char *skprovider,
246     struct dest_constraint **dest_constraints,
247     size_t ndest_constraints)
248 {
249 	struct sshkey *private, *cert;
250 	char *comment = NULL;
251 	char msg[1024], *certpath = NULL;
252 	int r, fd, ret = -1;
253 	size_t i;
254 	u_int32_t left;
255 	struct sshbuf *keyblob;
256 	struct ssh_identitylist *idlist;
257 
258 	if (strcmp(filename, "-") == 0) {
259 		fd = STDIN_FILENO;
260 		filename = "(stdin)";
261 	} else if ((fd = open(filename, O_RDONLY)) == -1) {
262 		perror(filename);
263 		return -1;
264 	}
265 
266 	/*
267 	 * Since we'll try to load a keyfile multiple times, permission errors
268 	 * will occur multiple times, so check perms first and bail if wrong.
269 	 */
270 	if (fd != STDIN_FILENO) {
271 		if (sshkey_perm_ok(fd, filename) != 0) {
272 			close(fd);
273 			return -1;
274 		}
275 	}
276 	if ((r = sshbuf_load_fd(fd, &keyblob)) != 0) {
277 		fprintf(stderr, "Error loading key \"%s\": %s\n",
278 		    filename, ssh_err(r));
279 		sshbuf_free(keyblob);
280 		close(fd);
281 		return -1;
282 	}
283 	close(fd);
284 
285 	/* At first, try empty passphrase */
286 	if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
287 	    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
288 		fprintf(stderr, "Error loading key \"%s\": %s\n",
289 		    filename, ssh_err(r));
290 		goto fail_load;
291 	}
292 	/* try last */
293 	if (private == NULL && pass != NULL) {
294 		if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
295 		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
296 			fprintf(stderr, "Error loading key \"%s\": %s\n",
297 			    filename, ssh_err(r));
298 			goto fail_load;
299 		}
300 	}
301 	if (private == NULL) {
302 		/* clear passphrase since it did not work */
303 		clear_pass();
304 		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
305 		    filename, confirm ? " (will confirm each use)" : "");
306 		for (;;) {
307 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
308 			if (strcmp(pass, "") == 0)
309 				goto fail_load;
310 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
311 			    &private, &comment)) == 0)
312 				break;
313 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
314 				fprintf(stderr,
315 				    "Error loading key \"%s\": %s\n",
316 				    filename, ssh_err(r));
317  fail_load:
318 				clear_pass();
319 				sshbuf_free(keyblob);
320 				return -1;
321 			}
322 			clear_pass();
323 			snprintf(msg, sizeof msg,
324 			    "Bad passphrase, try again for %s%s: ", filename,
325 			    confirm ? " (will confirm each use)" : "");
326 		}
327 	}
328 	if (comment == NULL || *comment == '\0')
329 		comment = xstrdup(filename);
330 	sshbuf_free(keyblob);
331 
332 	/* For XMSS */
333 	if ((r = sshkey_set_filename(private, filename)) != 0) {
334 		fprintf(stderr, "Could not add filename to private key: %s (%s)\n",
335 		    filename, comment);
336 		goto out;
337 	}
338 	if (maxsign && minleft &&
339 	    (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) {
340 		for (i = 0; i < idlist->nkeys; i++) {
341 			if (!sshkey_equal_public(idlist->keys[i], private))
342 				continue;
343 			left = sshkey_signatures_left(idlist->keys[i]);
344 			if (left < minleft) {
345 				fprintf(stderr,
346 				    "Only %d signatures left.\n", left);
347 				break;
348 			}
349 			fprintf(stderr, "Skipping update: ");
350 			if (left == minleft) {
351 				fprintf(stderr,
352 				    "required signatures left (%d).\n", left);
353 			} else {
354 				fprintf(stderr,
355 				    "more signatures left (%d) than"
356 				    " required (%d).\n", left, minleft);
357 			}
358 			ssh_free_identitylist(idlist);
359 			goto out;
360 		}
361 		ssh_free_identitylist(idlist);
362 	}
363 
364 	if (sshkey_is_sk(private)) {
365 		if (skprovider == NULL) {
366 			fprintf(stderr, "Cannot load FIDO key %s "
367 			    "without provider\n", filename);
368 			goto out;
369 		}
370 	} else {
371 		/* Don't send provider constraint for other keys */
372 		skprovider = NULL;
373 	}
374 
375 	if (!cert_only &&
376 	    (r = ssh_add_identity_constrained(agent_fd, private, comment,
377 	    lifetime, confirm, maxsign, skprovider,
378 	    dest_constraints, ndest_constraints)) == 0) {
379 		ret = 0;
380 		if (!qflag) {
381 			fprintf(stderr, "Identity added: %s (%s)\n",
382 			    filename, comment);
383 			if (lifetime != 0) {
384 				fprintf(stderr,
385 				    "Lifetime set to %d seconds\n", lifetime);
386 			}
387 			if (confirm != 0) {
388 				fprintf(stderr, "The user must confirm "
389 				    "each use of the key\n");
390 			}
391 		}
392 	} else {
393 		fprintf(stderr, "Could not add identity \"%s\": %s\n",
394 		    filename, ssh_err(r));
395 	}
396 
397 	/* Skip trying to load the cert if requested */
398 	if (key_only)
399 		goto out;
400 
401 	/* Now try to add the certificate flavour too */
402 	xasprintf(&certpath, "%s-cert.pub", filename);
403 	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
404 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
405 			error_r(r, "Failed to load certificate \"%s\"",
406 			    certpath);
407 		goto out;
408 	}
409 
410 	if (!sshkey_equal_public(cert, private)) {
411 		error("Certificate %s does not match private key %s",
412 		    certpath, filename);
413 		sshkey_free(cert);
414 		goto out;
415 	}
416 
417 	/* Graft with private bits */
418 	if ((r = sshkey_to_certified(private)) != 0) {
419 		error_fr(r, "sshkey_to_certified");
420 		sshkey_free(cert);
421 		goto out;
422 	}
423 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
424 		error_fr(r, "sshkey_cert_copy");
425 		sshkey_free(cert);
426 		goto out;
427 	}
428 	sshkey_free(cert);
429 
430 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
431 	    lifetime, confirm, maxsign, skprovider,
432 	    dest_constraints, ndest_constraints)) != 0) {
433 		error_r(r, "Certificate %s (%s) add failed", certpath,
434 		    private->cert->key_id);
435 		goto out;
436 	}
437 	/* success */
438 	if (!qflag) {
439 		fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
440 		    private->cert->key_id);
441 		if (lifetime != 0) {
442 			fprintf(stderr, "Lifetime set to %d seconds\n",
443 			    lifetime);
444 		}
445 		if (confirm != 0) {
446 			fprintf(stderr, "The user must confirm each use "
447 			    "of the key\n");
448 		}
449 	}
450 
451  out:
452 	free(certpath);
453 	free(comment);
454 	sshkey_free(private);
455 
456 	return ret;
457 }
458 
459 static int
460 update_card(int agent_fd, int add, const char *id, int qflag,
461     int key_only, int cert_only,
462     struct dest_constraint **dest_constraints, size_t ndest_constraints,
463     struct sshkey **certs, size_t ncerts)
464 {
465 	char *pin = NULL;
466 	int r, ret = -1;
467 
468 	if (key_only)
469 		ncerts = 0;
470 
471 	if (add) {
472 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
473 		    RP_ALLOW_STDIN)) == NULL)
474 			return -1;
475 	}
476 
477 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
478 	    lifetime, confirm, dest_constraints, ndest_constraints,
479 	    cert_only, certs, ncerts)) == 0) {
480 		ret = 0;
481 		if (!qflag) {
482 			fprintf(stderr, "Card %s: %s\n",
483 			    add ? "added" : "removed", id);
484 		}
485 	} else {
486 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
487 		    add ? "add" : "remove", id, ssh_err(r));
488 		ret = -1;
489 	}
490 	free(pin);
491 	return ret;
492 }
493 
494 static int
495 test_key(int agent_fd, const char *filename)
496 {
497 	struct sshkey *key = NULL;
498 	u_char *sig = NULL;
499 	const char *alg = NULL;
500 	size_t slen = 0;
501 	int r, ret = -1;
502 	char data[1024];
503 
504 	if ((r = sshkey_load_public(filename, &key, NULL)) != 0) {
505 		error_r(r, "Couldn't read public key %s", filename);
506 		return -1;
507 	}
508 	if (sshkey_type_plain(key->type) == KEY_RSA)
509 		alg = "rsa-sha2-256";
510 	arc4random_buf(data, sizeof(data));
511 	if ((r = ssh_agent_sign(agent_fd, key, &sig, &slen, data, sizeof(data),
512 	    alg, 0)) != 0) {
513 		error_r(r, "Agent signature failed for %s", filename);
514 		goto done;
515 	}
516 	if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
517 	    alg, 0, NULL)) != 0) {
518 		error_r(r, "Signature verification failed for %s", filename);
519 		goto done;
520 	}
521 	/* success */
522 	ret = 0;
523  done:
524 	free(sig);
525 	sshkey_free(key);
526 	return ret;
527 }
528 
529 static int
530 list_identities(int agent_fd, int do_fp)
531 {
532 	char *fp;
533 	int r;
534 	struct ssh_identitylist *idlist;
535 	u_int32_t left;
536 	size_t i;
537 
538 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
539 		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
540 			fprintf(stderr, "error fetching identities: %s\n",
541 			    ssh_err(r));
542 		else
543 			printf("The agent has no identities.\n");
544 		return -1;
545 	}
546 	for (i = 0; i < idlist->nkeys; i++) {
547 		if (do_fp) {
548 			fp = sshkey_fingerprint(idlist->keys[i],
549 			    fingerprint_hash, SSH_FP_DEFAULT);
550 			printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
551 			    fp == NULL ? "(null)" : fp, idlist->comments[i],
552 			    sshkey_type(idlist->keys[i]));
553 			free(fp);
554 		} else {
555 			if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
556 				fprintf(stderr, "sshkey_write: %s\n",
557 				    ssh_err(r));
558 				continue;
559 			}
560 			fprintf(stdout, " %s", idlist->comments[i]);
561 			left = sshkey_signatures_left(idlist->keys[i]);
562 			if (left > 0)
563 				fprintf(stdout,
564 				    " [signatures left %d]", left);
565 			fprintf(stdout, "\n");
566 		}
567 	}
568 	ssh_free_identitylist(idlist);
569 	return 0;
570 }
571 
572 static int
573 lock_agent(int agent_fd, int lock)
574 {
575 	char prompt[100], *p1, *p2;
576 	int r, passok = 1, ret = -1;
577 
578 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
579 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
580 	if (lock) {
581 		strlcpy(prompt, "Again: ", sizeof prompt);
582 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
583 		if (strcmp(p1, p2) != 0) {
584 			fprintf(stderr, "Passwords do not match.\n");
585 			passok = 0;
586 		}
587 		freezero(p2, strlen(p2));
588 	}
589 	if (passok) {
590 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
591 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
592 			ret = 0;
593 		} else {
594 			fprintf(stderr, "Failed to %slock agent: %s\n",
595 			    lock ? "" : "un", ssh_err(r));
596 		}
597 	}
598 	freezero(p1, strlen(p1));
599 	return (ret);
600 }
601 
602 static int
603 load_resident_keys(int agent_fd, const char *skprovider, int qflag,
604     struct dest_constraint **dest_constraints, size_t ndest_constraints)
605 {
606 	struct sshsk_resident_key **srks;
607 	size_t nsrks, i;
608 	struct sshkey *key;
609 	int r, ok = 0;
610 	char *fp;
611 
612 	pass = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
613 	if ((r = sshsk_load_resident(skprovider, NULL, pass, 0,
614 	    &srks, &nsrks)) != 0) {
615 		error_r(r, "Unable to load resident keys");
616 		return r;
617 	}
618 	for (i = 0; i < nsrks; i++) {
619 		key = srks[i]->key;
620 		if ((fp = sshkey_fingerprint(key,
621 		    fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
622 			fatal_f("sshkey_fingerprint failed");
623 		if ((r = ssh_add_identity_constrained(agent_fd, key, "",
624 		    lifetime, confirm, maxsign, skprovider,
625 		    dest_constraints, ndest_constraints)) != 0) {
626 			error("Unable to add key %s %s",
627 			    sshkey_type(key), fp);
628 			free(fp);
629 			ok = r;
630 			continue;
631 		}
632 		if (ok == 0)
633 			ok = 1;
634 		if (!qflag) {
635 			fprintf(stderr, "Resident identity added: %s %s\n",
636 			    sshkey_type(key), fp);
637 			if (lifetime != 0) {
638 				fprintf(stderr,
639 				    "Lifetime set to %d seconds\n", lifetime);
640 			}
641 			if (confirm != 0) {
642 				fprintf(stderr, "The user must confirm "
643 				    "each use of the key\n");
644 			}
645 		}
646 		free(fp);
647 	}
648 	sshsk_free_resident_keys(srks, nsrks);
649 	if (nsrks == 0)
650 		return SSH_ERR_KEY_NOT_FOUND;
651 	return ok == 1 ? 0 : ok;
652 }
653 
654 static int
655 do_file(int agent_fd, int deleting, int key_only, int cert_only,
656     char *file, int qflag, const char *skprovider,
657     struct dest_constraint **dest_constraints, size_t ndest_constraints)
658 {
659 	if (deleting) {
660 		if (delete_file(agent_fd, file, key_only,
661 		    cert_only, qflag) == -1)
662 			return -1;
663 	} else {
664 		if (add_file(agent_fd, file, key_only, cert_only, qflag,
665 		    skprovider, dest_constraints, ndest_constraints) == -1)
666 			return -1;
667 	}
668 	return 0;
669 }
670 
671 /* Append string 's' to a NULL-terminated array of strings */
672 static void
673 stringlist_append(char ***listp, const char *s)
674 {
675 	size_t i = 0;
676 
677 	if (*listp == NULL)
678 		*listp = xcalloc(2, sizeof(**listp));
679 	else {
680 		for (i = 0; (*listp)[i] != NULL; i++)
681 			; /* count */
682 		*listp = xrecallocarray(*listp, i + 1, i + 2, sizeof(**listp));
683 	}
684 	(*listp)[i] = xstrdup(s);
685 }
686 
687 static void
688 parse_dest_constraint_hop(const char *s, struct dest_constraint_hop *dch,
689     char **hostkey_files)
690 {
691 	char *user = NULL, *host, *os, *path;
692 	size_t i;
693 	struct hostkeys *hostkeys;
694 	const struct hostkey_entry *hke;
695 	int r, want_ca;
696 
697 	memset(dch, '\0', sizeof(*dch));
698 	os = xstrdup(s);
699 	if ((host = strchr(os, '@')) == NULL)
700 		host = os;
701 	else {
702 		*host++ = '\0';
703 		user = os;
704 	}
705 	cleanhostname(host);
706 	/* Trivial case: username@ (all hosts) */
707 	if (*host == '\0') {
708 		if (user == NULL) {
709 			fatal("Invalid key destination constraint \"%s\": "
710 			    "does not specify user or host", s);
711 		}
712 		dch->user = xstrdup(user);
713 		/* other fields left blank */
714 		free(os);
715 		return;
716 	}
717 	if (hostkey_files == NULL)
718 		fatal_f("no hostkey files");
719 	/* Otherwise we need to look up the keys for this hostname */
720 	hostkeys = init_hostkeys();
721 	for (i = 0; hostkey_files[i]; i++) {
722 		path = tilde_expand_filename(hostkey_files[i], getuid());
723 		debug2_f("looking up host keys for \"%s\" in %s", host, path);
724                 load_hostkeys(hostkeys, host, path, 0);
725 		free(path);
726 	}
727 	dch->user = user == NULL ? NULL : xstrdup(user);
728 	dch->hostname = xstrdup(host);
729 	for (i = 0; i < hostkeys->num_entries; i++) {
730 		hke = hostkeys->entries + i;
731 		want_ca = hke->marker == MRK_CA;
732 		if (hke->marker != MRK_NONE && !want_ca)
733 			continue;
734 		debug3_f("%s%s%s: adding %s %skey from %s:%lu as key %u",
735 		    user == NULL ? "": user, user == NULL ? "" : "@",
736 		    host, sshkey_type(hke->key), want_ca ? "CA " : "",
737 		    hke->file, hke->line, dch->nkeys);
738 		dch->keys = xrecallocarray(dch->keys, dch->nkeys,
739 		    dch->nkeys + 1, sizeof(*dch->keys));
740 		dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
741 		    dch->nkeys + 1, sizeof(*dch->key_is_ca));
742 		if ((r = sshkey_from_private(hke->key,
743 		    &(dch->keys[dch->nkeys]))) != 0)
744 			fatal_fr(r, "sshkey_from_private");
745 		dch->key_is_ca[dch->nkeys] = want_ca;
746 		dch->nkeys++;
747 	}
748 	if (dch->nkeys == 0)
749 		fatal("No host keys found for destination \"%s\"", host);
750 	free_hostkeys(hostkeys);
751 	free(os);
752 	return;
753 }
754 
755 static void
756 parse_dest_constraint(const char *s, struct dest_constraint ***dcp,
757     size_t *ndcp, char **hostkey_files)
758 {
759 	struct dest_constraint *dc;
760 	char *os, *cp;
761 
762 	dc = xcalloc(1, sizeof(*dc));
763 	os = xstrdup(s);
764 	if ((cp = strchr(os, '>')) == NULL) {
765 		/* initial hop; no 'from' hop specified */
766 		parse_dest_constraint_hop(os, &dc->to, hostkey_files);
767 	} else {
768 		/* two hops specified */
769 		*(cp++) = '\0';
770 		parse_dest_constraint_hop(os, &dc->from, hostkey_files);
771 		parse_dest_constraint_hop(cp, &dc->to, hostkey_files);
772 		if (dc->from.user != NULL) {
773 			fatal("Invalid key constraint %s: cannot specify "
774 			    "user on 'from' host", os);
775 		}
776 	}
777 	/* XXX eliminate or error on duplicates */
778 	debug2_f("constraint %zu: %s%s%s (%u keys) > %s%s%s (%u keys)", *ndcp,
779 	    dc->from.user ? dc->from.user : "", dc->from.user ? "@" : "",
780 	    dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
781 	    dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
782 	    dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
783 	*dcp = xrecallocarray(*dcp, *ndcp, *ndcp + 1, sizeof(**dcp));
784 	(*dcp)[(*ndcp)++] = dc;
785 	free(os);
786 }
787 
788 
789 static void
790 usage(void)
791 {
792 	fprintf(stderr,
793 "usage: ssh-add [-cDdKkLlqvXx] [-E fingerprint_hash] [-H hostkey_file]\n"
794 "               [-h destination_constraint] [-S provider] [-t life]\n"
795 #ifdef WITH_XMSS
796 "               [-M maxsign] [-m minleft]\n"
797 #endif
798 "               [file ...]\n"
799 "       ssh-add -s pkcs11\n"
800 "       ssh-add -e pkcs11\n"
801 "       ssh-add -T pubkey ...\n"
802 	);
803 }
804 
805 int
806 main(int argc, char **argv)
807 {
808 	extern char *optarg;
809 	extern int optind;
810 	int agent_fd;
811 	char *pkcs11provider = NULL, *skprovider = NULL;
812 	char **dest_constraint_strings = NULL, **hostkey_files = NULL;
813 	int r, i, ch, deleting = 0, ret = 0, key_only = 0, cert_only = 0;
814 	int do_download = 0, xflag = 0, lflag = 0, Dflag = 0;
815 	int qflag = 0, Tflag = 0;
816 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
817 	LogLevel log_level = SYSLOG_LEVEL_INFO;
818 	struct sshkey *k, **certs = NULL;
819 	struct dest_constraint **dest_constraints = NULL;
820 	size_t ndest_constraints = 0i, ncerts = 0;
821 
822 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
823 	sanitise_stdfd();
824 
825 	__progname = ssh_get_progname(argv[0]);
826 	seed_rng();
827 
828 	log_init(__progname, log_level, log_facility, 1);
829 
830 	setvbuf(stdout, NULL, _IOLBF, 0);
831 
832 	/* First, get a connection to the authentication agent. */
833 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
834 	case 0:
835 		break;
836 	case SSH_ERR_AGENT_NOT_PRESENT:
837 		fprintf(stderr, "Could not open a connection to your "
838 		    "authentication agent.\n");
839 		exit(2);
840 	default:
841 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
842 		exit(2);
843 	}
844 
845 	skprovider = getenv("SSH_SK_PROVIDER");
846 
847 	while ((ch = getopt(argc, argv, "vkKlLCcdDTxXE:e:h:H:M:m:qs:S:t:")) != -1) {
848 		switch (ch) {
849 		case 'v':
850 			if (log_level == SYSLOG_LEVEL_INFO)
851 				log_level = SYSLOG_LEVEL_DEBUG1;
852 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
853 				log_level++;
854 			break;
855 		case 'E':
856 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
857 			if (fingerprint_hash == -1)
858 				fatal("Invalid hash algorithm \"%s\"", optarg);
859 			break;
860 		case 'H':
861 			stringlist_append(&hostkey_files, optarg);
862 			break;
863 		case 'h':
864 			stringlist_append(&dest_constraint_strings, optarg);
865 			break;
866 		case 'k':
867 			key_only = 1;
868 			break;
869 		case 'C':
870 			cert_only = 1;
871 			break;
872 		case 'K':
873 			do_download = 1;
874 			break;
875 		case 'l':
876 		case 'L':
877 			if (lflag != 0)
878 				fatal("-%c flag already specified", lflag);
879 			lflag = ch;
880 			break;
881 		case 'x':
882 		case 'X':
883 			if (xflag != 0)
884 				fatal("-%c flag already specified", xflag);
885 			xflag = ch;
886 			break;
887 		case 'c':
888 			confirm = 1;
889 			break;
890 		case 'm':
891 			minleft = (u_int)strtonum(optarg, 1, UINT_MAX, NULL);
892 			if (minleft == 0) {
893 				usage();
894 				ret = 1;
895 				goto done;
896 			}
897 			break;
898 		case 'M':
899 			maxsign = (u_int)strtonum(optarg, 1, UINT_MAX, NULL);
900 			if (maxsign == 0) {
901 				usage();
902 				ret = 1;
903 				goto done;
904 			}
905 			break;
906 		case 'd':
907 			deleting = 1;
908 			break;
909 		case 'D':
910 			Dflag = 1;
911 			break;
912 		case 's':
913 			pkcs11provider = optarg;
914 			break;
915 		case 'S':
916 			skprovider = optarg;
917 			break;
918 		case 'e':
919 			deleting = 1;
920 			pkcs11provider = optarg;
921 			break;
922 		case 't':
923 			if ((lifetime = convtime(optarg)) == -1 ||
924 			    lifetime < 0 || (u_long)lifetime > UINT32_MAX) {
925 				fprintf(stderr, "Invalid lifetime\n");
926 				ret = 1;
927 				goto done;
928 			}
929 			break;
930 		case 'q':
931 			qflag = 1;
932 			break;
933 		case 'T':
934 			Tflag = 1;
935 			break;
936 		default:
937 			usage();
938 			ret = 1;
939 			goto done;
940 		}
941 	}
942 	log_init(__progname, log_level, log_facility, 1);
943 
944 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
945 		fatal("Invalid combination of actions");
946 	else if (xflag) {
947 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
948 			ret = 1;
949 		goto done;
950 	} else if (lflag) {
951 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
952 			ret = 1;
953 		goto done;
954 	} else if (Dflag) {
955 		if (delete_all(agent_fd, qflag) == -1)
956 			ret = 1;
957 		goto done;
958 	}
959 
960 #ifdef ENABLE_SK_INTERNAL
961 	if (skprovider == NULL)
962 		skprovider = "internal";
963 #endif
964 
965 	if (hostkey_files == NULL) {
966 		/* use defaults from readconf.c */
967 		stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE);
968 		stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE2);
969 		stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE);
970 		stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE2);
971 	}
972 	if (dest_constraint_strings != NULL) {
973 		for (i = 0; dest_constraint_strings[i] != NULL; i++) {
974 			parse_dest_constraint(dest_constraint_strings[i],
975 			  &dest_constraints, &ndest_constraints, hostkey_files);
976 		}
977 	}
978 
979 	argc -= optind;
980 	argv += optind;
981 	if (Tflag) {
982 		if (argc <= 0)
983 			fatal("no keys to test");
984 		for (r = i = 0; i < argc; i++)
985 			r |= test_key(agent_fd, argv[i]);
986 		ret = r == 0 ? 0 : 1;
987 		goto done;
988 	}
989 	if (pkcs11provider != NULL) {
990 		for (i = 0; i < argc; i++) {
991 			if ((r = sshkey_load_public(argv[i], &k, NULL)) != 0)
992 				fatal_fr(r, "load certificate %s", argv[i]);
993 			certs = xrecallocarray(certs, ncerts, ncerts + 1,
994 			    sizeof(*certs));
995 			debug2("%s: %s", argv[i], sshkey_ssh_name(k));
996 			certs[ncerts++] = k;
997 		}
998 		debug2_f("loaded %zu certificates", ncerts);
999 		if (update_card(agent_fd, !deleting, pkcs11provider,
1000 		    qflag, key_only, cert_only,
1001 		    dest_constraints, ndest_constraints,
1002 		    certs, ncerts) == -1)
1003 			ret = 1;
1004 		goto done;
1005 	}
1006 	if (do_download) {
1007 		if (skprovider == NULL)
1008 			fatal("Cannot download keys without provider");
1009 		if (load_resident_keys(agent_fd, skprovider, qflag,
1010 		    dest_constraints, ndest_constraints) != 0)
1011 			ret = 1;
1012 		goto done;
1013 	}
1014 	if (argc == 0) {
1015 		char buf[PATH_MAX];
1016 		struct passwd *pw;
1017 		struct stat st;
1018 		int count = 0;
1019 
1020 		if ((pw = getpwuid(getuid())) == NULL) {
1021 			fprintf(stderr, "No user found with uid %u\n",
1022 			    (u_int)getuid());
1023 			ret = 1;
1024 			goto done;
1025 		}
1026 
1027 		for (i = 0; default_files[i]; i++) {
1028 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
1029 			    default_files[i]);
1030 			if (stat(buf, &st) == -1)
1031 				continue;
1032 			if (do_file(agent_fd, deleting, key_only, cert_only,
1033 			    buf, qflag, skprovider,
1034 			    dest_constraints, ndest_constraints) == -1)
1035 				ret = 1;
1036 			else
1037 				count++;
1038 		}
1039 		if (count == 0)
1040 			ret = 1;
1041 	} else {
1042 		for (i = 0; i < argc; i++) {
1043 			if (do_file(agent_fd, deleting, key_only, cert_only,
1044 			    argv[i], qflag, skprovider,
1045 			    dest_constraints, ndest_constraints) == -1)
1046 				ret = 1;
1047 		}
1048 	}
1049 done:
1050 	clear_pass();
1051 	ssh_close_authentication_socket(agent_fd);
1052 	return ret;
1053 }
1054