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