xref: /openbsd-src/usr.bin/ssh/ssh-add.c (revision f84b1df5a16cdd762c93854218de246e79975d3b)
1 /* $OpenBSD: ssh-add.c,v 1.165 2022/02/04 02:49:17 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);
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 	size_t slen = 0;
474 	int r, ret = -1;
475 	char data[1024];
476 
477 	if ((r = sshkey_load_public(filename, &key, NULL)) != 0) {
478 		error_r(r, "Couldn't read public key %s", filename);
479 		return -1;
480 	}
481 	arc4random_buf(data, sizeof(data));
482 	if ((r = ssh_agent_sign(agent_fd, key, &sig, &slen, data, sizeof(data),
483 	    NULL, 0)) != 0) {
484 		error_r(r, "Agent signature failed for %s", filename);
485 		goto done;
486 	}
487 	if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
488 	    NULL, 0, NULL)) != 0) {
489 		error_r(r, "Signature verification failed for %s", filename);
490 		goto done;
491 	}
492 	/* success */
493 	ret = 0;
494  done:
495 	free(sig);
496 	sshkey_free(key);
497 	return ret;
498 }
499 
500 static int
501 list_identities(int agent_fd, int do_fp)
502 {
503 	char *fp;
504 	int r;
505 	struct ssh_identitylist *idlist;
506 	u_int32_t left;
507 	size_t i;
508 
509 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
510 		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
511 			fprintf(stderr, "error fetching identities: %s\n",
512 			    ssh_err(r));
513 		else
514 			printf("The agent has no identities.\n");
515 		return -1;
516 	}
517 	for (i = 0; i < idlist->nkeys; i++) {
518 		if (do_fp) {
519 			fp = sshkey_fingerprint(idlist->keys[i],
520 			    fingerprint_hash, SSH_FP_DEFAULT);
521 			printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
522 			    fp == NULL ? "(null)" : fp, idlist->comments[i],
523 			    sshkey_type(idlist->keys[i]));
524 			free(fp);
525 		} else {
526 			if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
527 				fprintf(stderr, "sshkey_write: %s\n",
528 				    ssh_err(r));
529 				continue;
530 			}
531 			fprintf(stdout, " %s", idlist->comments[i]);
532 			left = sshkey_signatures_left(idlist->keys[i]);
533 			if (left > 0)
534 				fprintf(stdout,
535 				    " [signatures left %d]", left);
536 			fprintf(stdout, "\n");
537 		}
538 	}
539 	ssh_free_identitylist(idlist);
540 	return 0;
541 }
542 
543 static int
544 lock_agent(int agent_fd, int lock)
545 {
546 	char prompt[100], *p1, *p2;
547 	int r, passok = 1, ret = -1;
548 
549 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
550 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
551 	if (lock) {
552 		strlcpy(prompt, "Again: ", sizeof prompt);
553 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
554 		if (strcmp(p1, p2) != 0) {
555 			fprintf(stderr, "Passwords do not match.\n");
556 			passok = 0;
557 		}
558 		freezero(p2, strlen(p2));
559 	}
560 	if (passok) {
561 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
562 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
563 			ret = 0;
564 		} else {
565 			fprintf(stderr, "Failed to %slock agent: %s\n",
566 			    lock ? "" : "un", ssh_err(r));
567 		}
568 	}
569 	freezero(p1, strlen(p1));
570 	return (ret);
571 }
572 
573 static int
574 load_resident_keys(int agent_fd, const char *skprovider, int qflag,
575     struct dest_constraint **dest_constraints, size_t ndest_constraints)
576 {
577 	struct sshsk_resident_key **srks;
578 	size_t nsrks, i;
579 	struct sshkey *key;
580 	int r, ok = 0;
581 	char *fp;
582 
583 	pass = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
584 	if ((r = sshsk_load_resident(skprovider, NULL, pass, 0,
585 	    &srks, &nsrks)) != 0) {
586 		error_r(r, "Unable to load resident keys");
587 		return r;
588 	}
589 	for (i = 0; i < nsrks; i++) {
590 		key = srks[i]->key;
591 		if ((fp = sshkey_fingerprint(key,
592 		    fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
593 			fatal_f("sshkey_fingerprint failed");
594 		if ((r = ssh_add_identity_constrained(agent_fd, key, "",
595 		    lifetime, confirm, maxsign, skprovider,
596 		    dest_constraints, ndest_constraints)) != 0) {
597 			error("Unable to add key %s %s",
598 			    sshkey_type(key), fp);
599 			free(fp);
600 			ok = r;
601 			continue;
602 		}
603 		if (ok == 0)
604 			ok = 1;
605 		if (!qflag) {
606 			fprintf(stderr, "Resident identity added: %s %s\n",
607 			    sshkey_type(key), fp);
608 			if (lifetime != 0) {
609 				fprintf(stderr,
610 				    "Lifetime set to %d seconds\n", lifetime);
611 			}
612 			if (confirm != 0) {
613 				fprintf(stderr, "The user must confirm "
614 				    "each use of the key\n");
615 			}
616 		}
617 		free(fp);
618 	}
619 	sshsk_free_resident_keys(srks, nsrks);
620 	if (nsrks == 0)
621 		return SSH_ERR_KEY_NOT_FOUND;
622 	return ok == 1 ? 0 : ok;
623 }
624 
625 static int
626 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag,
627     const char *skprovider, struct dest_constraint **dest_constraints,
628     size_t ndest_constraints)
629 {
630 	if (deleting) {
631 		if (delete_file(agent_fd, file, key_only, qflag) == -1)
632 			return -1;
633 	} else {
634 		if (add_file(agent_fd, file, key_only, qflag, skprovider,
635 		    dest_constraints, ndest_constraints) == -1)
636 			return -1;
637 	}
638 	return 0;
639 }
640 
641 /* Append string 's' to a NULL-terminated array of strings */
642 static void
643 stringlist_append(char ***listp, const char *s)
644 {
645 	size_t i = 0;
646 
647 	if (*listp == NULL)
648 		*listp = xcalloc(2, sizeof(**listp));
649 	else {
650 		for (i = 0; (*listp)[i] != NULL; i++)
651 			; /* count */
652 		*listp = xrecallocarray(*listp, i + 1, i + 2, sizeof(**listp));
653 	}
654 	(*listp)[i] = xstrdup(s);
655 }
656 
657 static void
658 parse_dest_constraint_hop(const char *s, struct dest_constraint_hop *dch,
659     char **hostkey_files)
660 {
661 	char *user = NULL, *host, *os, *path;
662 	size_t i;
663 	struct hostkeys *hostkeys;
664 	const struct hostkey_entry *hke;
665 	int r, want_ca;
666 
667 	memset(dch, '\0', sizeof(*dch));
668 	os = xstrdup(s);
669 	if ((host = strchr(os, '@')) == NULL)
670 		host = os;
671 	else {
672 		*host++ = '\0';
673 		user = os;
674 	}
675 	cleanhostname(host);
676 	/* Trivial case: username@ (all hosts) */
677 	if (*host == '\0') {
678 		if (user == NULL) {
679 			fatal("Invalid key destination constraint \"%s\": "
680 			    "does not specify user or host", s);
681 		}
682 		dch->user = xstrdup(user);
683 		/* other fields left blank */
684 		free(os);
685 		return;
686 	}
687 	if (hostkey_files == NULL)
688 		fatal_f("no hostkey files");
689 	/* Otherwise we need to look up the keys for this hostname */
690 	hostkeys = init_hostkeys();
691 	for (i = 0; hostkey_files[i]; i++) {
692 		path = tilde_expand_filename(hostkey_files[i], getuid());
693 		debug2_f("looking up host keys for \"%s\" in %s", host, path);
694                 load_hostkeys(hostkeys, host, path, 0);
695 		free(path);
696 	}
697 	dch->user = user == NULL ? NULL : xstrdup(user);
698 	dch->hostname = xstrdup(host);
699 	for (i = 0; i < hostkeys->num_entries; i++) {
700 		hke = hostkeys->entries + i;
701 		want_ca = hke->marker == MRK_CA;
702 		if (hke->marker != MRK_NONE && !want_ca)
703 			continue;
704 		debug3_f("%s%s%s: adding %s %skey from %s:%lu as key %u",
705 		    user == NULL ? "": user, user == NULL ? "" : "@",
706 		    host, sshkey_type(hke->key), want_ca ? "CA " : "",
707 		    hke->file, hke->line, dch->nkeys);
708 		dch->keys = xrecallocarray(dch->keys, dch->nkeys,
709 		    dch->nkeys + 1, sizeof(*dch->keys));
710 		dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
711 		    dch->nkeys + 1, sizeof(*dch->key_is_ca));
712 		if ((r = sshkey_from_private(hke->key,
713 		    &(dch->keys[dch->nkeys]))) != 0)
714 			fatal_fr(r, "sshkey_from_private");
715 		dch->key_is_ca[dch->nkeys] = want_ca;
716 		dch->nkeys++;
717 	}
718 	if (dch->nkeys == 0)
719 		fatal("No host keys found for destination \"%s\"", host);
720 	free_hostkeys(hostkeys);
721 	free(os);
722 	return;
723 }
724 
725 static void
726 parse_dest_constraint(const char *s, struct dest_constraint ***dcp,
727     size_t *ndcp, char **hostkey_files)
728 {
729 	struct dest_constraint *dc;
730 	char *os, *cp;
731 
732 	dc = xcalloc(1, sizeof(*dc));
733 	os = xstrdup(s);
734 	if ((cp = strchr(os, '>')) == NULL) {
735 		/* initial hop; no 'from' hop specified */
736 		parse_dest_constraint_hop(os, &dc->to, hostkey_files);
737 	} else {
738 		/* two hops specified */
739 		*(cp++) = '\0';
740 		parse_dest_constraint_hop(os, &dc->from, hostkey_files);
741 		parse_dest_constraint_hop(cp, &dc->to, hostkey_files);
742 		if (dc->from.user != NULL) {
743 			fatal("Invalid key constraint %s: cannot specify "
744 			    "user on 'from' host", os);
745 		}
746 	}
747 	/* XXX eliminate or error on duplicates */
748 	debug2_f("constraint %zu: %s%s%s (%u keys) > %s%s%s (%u keys)", *ndcp,
749 	    dc->from.user ? dc->from.user : "", dc->from.user ? "@" : "",
750 	    dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
751 	    dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
752 	    dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
753 	*dcp = xrecallocarray(*dcp, *ndcp, *ndcp + 1, sizeof(**dcp));
754 	(*dcp)[(*ndcp)++] = dc;
755 	free(os);
756 }
757 
758 
759 static void
760 usage(void)
761 {
762 	fprintf(stderr,
763 "usage: ssh-add [-cDdKkLlqvXx] [-E fingerprint_hash] [-H hostkey_file]\n"
764 "               [-h destination_constraint] [-S provider] [-t life]\n"
765 #ifdef WITH_XMSS
766 "               [-M maxsign] [-m minleft]\n"
767 #endif
768 "               [file ...]\n"
769 "       ssh-add -s pkcs11\n"
770 "       ssh-add -e pkcs11\n"
771 "       ssh-add -T pubkey ...\n"
772 	);
773 }
774 
775 int
776 main(int argc, char **argv)
777 {
778 	extern char *optarg;
779 	extern int optind;
780 	int agent_fd;
781 	char *pkcs11provider = NULL, *skprovider = NULL;
782 	char **dest_constraint_strings = NULL, **hostkey_files = NULL;
783 	int r, i, ch, deleting = 0, ret = 0, key_only = 0, do_download = 0;
784 	int xflag = 0, lflag = 0, Dflag = 0, qflag = 0, Tflag = 0;
785 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
786 	LogLevel log_level = SYSLOG_LEVEL_INFO;
787 	struct dest_constraint **dest_constraints = NULL;
788 	size_t ndest_constraints = 0;
789 
790 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
791 	sanitise_stdfd();
792 
793 #ifdef WITH_OPENSSL
794 	OpenSSL_add_all_algorithms();
795 #endif
796 	log_init(__progname, log_level, log_facility, 1);
797 
798 	setvbuf(stdout, NULL, _IOLBF, 0);
799 
800 	/* First, get a connection to the authentication agent. */
801 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
802 	case 0:
803 		break;
804 	case SSH_ERR_AGENT_NOT_PRESENT:
805 		fprintf(stderr, "Could not open a connection to your "
806 		    "authentication agent.\n");
807 		exit(2);
808 	default:
809 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
810 		exit(2);
811 	}
812 
813 	skprovider = getenv("SSH_SK_PROVIDER");
814 
815 	while ((ch = getopt(argc, argv, "vkKlLcdDTxXE:e:h:H:M:m:qs:S:t:")) != -1) {
816 		switch (ch) {
817 		case 'v':
818 			if (log_level == SYSLOG_LEVEL_INFO)
819 				log_level = SYSLOG_LEVEL_DEBUG1;
820 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
821 				log_level++;
822 			break;
823 		case 'E':
824 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
825 			if (fingerprint_hash == -1)
826 				fatal("Invalid hash algorithm \"%s\"", optarg);
827 			break;
828 		case 'H':
829 			stringlist_append(&hostkey_files, optarg);
830 			break;
831 		case 'h':
832 			stringlist_append(&dest_constraint_strings, optarg);
833 			break;
834 		case 'k':
835 			key_only = 1;
836 			break;
837 		case 'K':
838 			do_download = 1;
839 			break;
840 		case 'l':
841 		case 'L':
842 			if (lflag != 0)
843 				fatal("-%c flag already specified", lflag);
844 			lflag = ch;
845 			break;
846 		case 'x':
847 		case 'X':
848 			if (xflag != 0)
849 				fatal("-%c flag already specified", xflag);
850 			xflag = ch;
851 			break;
852 		case 'c':
853 			confirm = 1;
854 			break;
855 		case 'm':
856 			minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL);
857 			if (minleft == 0) {
858 				usage();
859 				ret = 1;
860 				goto done;
861 			}
862 			break;
863 		case 'M':
864 			maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL);
865 			if (maxsign == 0) {
866 				usage();
867 				ret = 1;
868 				goto done;
869 			}
870 			break;
871 		case 'd':
872 			deleting = 1;
873 			break;
874 		case 'D':
875 			Dflag = 1;
876 			break;
877 		case 's':
878 			pkcs11provider = optarg;
879 			break;
880 		case 'S':
881 			skprovider = optarg;
882 			break;
883 		case 'e':
884 			deleting = 1;
885 			pkcs11provider = optarg;
886 			break;
887 		case 't':
888 			if ((lifetime = convtime(optarg)) == -1 ||
889 			    lifetime < 0 || (u_long)lifetime > UINT32_MAX) {
890 				fprintf(stderr, "Invalid lifetime\n");
891 				ret = 1;
892 				goto done;
893 			}
894 			break;
895 		case 'q':
896 			qflag = 1;
897 			break;
898 		case 'T':
899 			Tflag = 1;
900 			break;
901 		default:
902 			usage();
903 			ret = 1;
904 			goto done;
905 		}
906 	}
907 	log_init(__progname, log_level, log_facility, 1);
908 
909 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
910 		fatal("Invalid combination of actions");
911 	else if (xflag) {
912 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
913 			ret = 1;
914 		goto done;
915 	} else if (lflag) {
916 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
917 			ret = 1;
918 		goto done;
919 	} else if (Dflag) {
920 		if (delete_all(agent_fd, qflag) == -1)
921 			ret = 1;
922 		goto done;
923 	}
924 
925 	if (skprovider == NULL)
926 		skprovider = "internal";
927 	if (hostkey_files == NULL) {
928 		/* use defaults from readconf.c */
929 		stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE);
930 		stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE2);
931 		stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE);
932 		stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE2);
933 	}
934 	if (dest_constraint_strings != NULL) {
935 		for (i = 0; dest_constraint_strings[i] != NULL; i++) {
936 			parse_dest_constraint(dest_constraint_strings[i],
937 			  &dest_constraints, &ndest_constraints, hostkey_files);
938 		}
939 	}
940 
941 	argc -= optind;
942 	argv += optind;
943 	if (Tflag) {
944 		if (argc <= 0)
945 			fatal("no keys to test");
946 		for (r = i = 0; i < argc; i++)
947 			r |= test_key(agent_fd, argv[i]);
948 		ret = r == 0 ? 0 : 1;
949 		goto done;
950 	}
951 	if (pkcs11provider != NULL) {
952 		if (update_card(agent_fd, !deleting, pkcs11provider,
953 		    qflag, dest_constraints, ndest_constraints) == -1)
954 			ret = 1;
955 		goto done;
956 	}
957 	if (do_download) {
958 		if (skprovider == NULL)
959 			fatal("Cannot download keys without provider");
960 		if (load_resident_keys(agent_fd, skprovider, qflag,
961 		    dest_constraints, ndest_constraints) != 0)
962 			ret = 1;
963 		goto done;
964 	}
965 	if (argc == 0) {
966 		char buf[PATH_MAX];
967 		struct passwd *pw;
968 		struct stat st;
969 		int count = 0;
970 
971 		if ((pw = getpwuid(getuid())) == NULL) {
972 			fprintf(stderr, "No user found with uid %u\n",
973 			    (u_int)getuid());
974 			ret = 1;
975 			goto done;
976 		}
977 
978 		for (i = 0; default_files[i]; i++) {
979 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
980 			    default_files[i]);
981 			if (stat(buf, &st) == -1)
982 				continue;
983 			if (do_file(agent_fd, deleting, key_only, buf,
984 			    qflag, skprovider,
985 			    dest_constraints, ndest_constraints) == -1)
986 				ret = 1;
987 			else
988 				count++;
989 		}
990 		if (count == 0)
991 			ret = 1;
992 	} else {
993 		for (i = 0; i < argc; i++) {
994 			if (do_file(agent_fd, deleting, key_only,
995 			    argv[i], qflag, skprovider,
996 			    dest_constraints, ndest_constraints) == -1)
997 				ret = 1;
998 		}
999 	}
1000 done:
1001 	clear_pass();
1002 	ssh_close_authentication_socket(agent_fd);
1003 	return ret;
1004 }
1005