xref: /dragonfly/crypto/openssh/ssh-add.c (revision ce74baca)
1 /* $OpenBSD: ssh-add.c,v 1.134 2017/08/29 09:42:29 dlg 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 #include <openssl/evp.h>
44 #include "openbsd-compat/openssl-compat.h"
45 
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <limits.h>
55 
56 #include "xmalloc.h"
57 #include "ssh.h"
58 #include "log.h"
59 #include "sshkey.h"
60 #include "sshbuf.h"
61 #include "authfd.h"
62 #include "authfile.h"
63 #include "pathnames.h"
64 #include "misc.h"
65 #include "ssherr.h"
66 #include "digest.h"
67 
68 /* argv0 */
69 extern char *__progname;
70 
71 /* Default files to add */
72 static char *default_files[] = {
73 #ifdef WITH_OPENSSL
74 	_PATH_SSH_CLIENT_ID_RSA,
75 	_PATH_SSH_CLIENT_ID_DSA,
76 #ifdef OPENSSL_HAS_ECC
77 	_PATH_SSH_CLIENT_ID_ECDSA,
78 #endif
79 #endif /* WITH_OPENSSL */
80 	_PATH_SSH_CLIENT_ID_ED25519,
81 	NULL
82 };
83 
84 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
85 
86 /* Default lifetime (0 == forever) */
87 static int lifetime = 0;
88 
89 /* User has to confirm key use */
90 static int confirm = 0;
91 
92 /* we keep a cache of one passphrase */
93 static char *pass = NULL;
94 static void
95 clear_pass(void)
96 {
97 	if (pass) {
98 		explicit_bzero(pass, strlen(pass));
99 		free(pass);
100 		pass = NULL;
101 	}
102 }
103 
104 static int
105 delete_file(int agent_fd, const char *filename, int key_only, int qflag)
106 {
107 	struct sshkey *public, *cert = NULL;
108 	char *certpath = NULL, *comment = NULL;
109 	int r, ret = -1;
110 
111 	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
112 		printf("Bad key file %s: %s\n", filename, ssh_err(r));
113 		return -1;
114 	}
115 	if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
116 		if (!qflag) {
117 			fprintf(stderr, "Identity removed: %s (%s)\n",
118 			    filename, comment);
119 		}
120 		ret = 0;
121 	} else
122 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
123 		    filename, ssh_err(r));
124 
125 	if (key_only)
126 		goto out;
127 
128 	/* Now try to delete the corresponding certificate too */
129 	free(comment);
130 	comment = NULL;
131 	xasprintf(&certpath, "%s-cert.pub", filename);
132 	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
133 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
134 			error("Failed to load certificate \"%s\": %s",
135 			    certpath, ssh_err(r));
136 		goto out;
137 	}
138 
139 	if (!sshkey_equal_public(cert, public))
140 		fatal("Certificate %s does not match private key %s",
141 		    certpath, filename);
142 
143 	if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
144 		if (!qflag) {
145 			fprintf(stderr, "Identity removed: %s (%s)\n",
146 			    certpath, comment);
147 		}
148 		ret = 0;
149 	} else
150 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
151 		    certpath, ssh_err(r));
152 
153  out:
154 	sshkey_free(cert);
155 	sshkey_free(public);
156 	free(certpath);
157 	free(comment);
158 
159 	return ret;
160 }
161 
162 /* Send a request to remove all identities. */
163 static int
164 delete_all(int agent_fd)
165 {
166 	int ret = -1;
167 
168 	/*
169 	 * Since the agent might be forwarded, old or non-OpenSSH, when asked
170 	 * to remove all keys, attempt to remove both protocol v.1 and v.2
171 	 * keys.
172 	 */
173 	if (ssh_remove_all_identities(agent_fd, 2) == 0)
174 		ret = 0;
175 	/* ignore error-code for ssh1 */
176 	ssh_remove_all_identities(agent_fd, 1);
177 
178 	if (ret == 0)
179 		fprintf(stderr, "All identities removed.\n");
180 	else
181 		fprintf(stderr, "Failed to remove all identities.\n");
182 
183 	return ret;
184 }
185 
186 static int
187 add_file(int agent_fd, const char *filename, int key_only, int qflag)
188 {
189 	struct sshkey *private, *cert;
190 	char *comment = NULL;
191 	char msg[1024], *certpath = NULL;
192 	int r, fd, ret = -1;
193 	struct sshbuf *keyblob;
194 
195 	if (strcmp(filename, "-") == 0) {
196 		fd = STDIN_FILENO;
197 		filename = "(stdin)";
198 	} else if ((fd = open(filename, O_RDONLY)) < 0) {
199 		perror(filename);
200 		return -1;
201 	}
202 
203 	/*
204 	 * Since we'll try to load a keyfile multiple times, permission errors
205 	 * will occur multiple times, so check perms first and bail if wrong.
206 	 */
207 	if (fd != STDIN_FILENO) {
208 		if (sshkey_perm_ok(fd, filename) != 0) {
209 			close(fd);
210 			return -1;
211 		}
212 	}
213 	if ((keyblob = sshbuf_new()) == NULL)
214 		fatal("%s: sshbuf_new failed", __func__);
215 	if ((r = sshkey_load_file(fd, keyblob)) != 0) {
216 		fprintf(stderr, "Error loading key \"%s\": %s\n",
217 		    filename, ssh_err(r));
218 		sshbuf_free(keyblob);
219 		close(fd);
220 		return -1;
221 	}
222 	close(fd);
223 
224 	/* At first, try empty passphrase */
225 	if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
226 	    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
227 		fprintf(stderr, "Error loading key \"%s\": %s\n",
228 		    filename, ssh_err(r));
229 		goto fail_load;
230 	}
231 	/* try last */
232 	if (private == NULL && pass != NULL) {
233 		if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
234 		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
235 			fprintf(stderr, "Error loading key \"%s\": %s\n",
236 			    filename, ssh_err(r));
237 			goto fail_load;
238 		}
239 	}
240 	if (private == NULL) {
241 		/* clear passphrase since it did not work */
242 		clear_pass();
243 		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
244 		    filename, confirm ? " (will confirm each use)" : "");
245 		for (;;) {
246 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
247 			if (strcmp(pass, "") == 0)
248 				goto fail_load;
249 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
250 			    &private, &comment)) == 0)
251 				break;
252 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
253 				fprintf(stderr,
254 				    "Error loading key \"%s\": %s\n",
255 				    filename, ssh_err(r));
256  fail_load:
257 				clear_pass();
258 				sshbuf_free(keyblob);
259 				return -1;
260 			}
261 			clear_pass();
262 			snprintf(msg, sizeof msg,
263 			    "Bad passphrase, try again for %s%s: ", filename,
264 			    confirm ? " (will confirm each use)" : "");
265 		}
266 	}
267 	if (comment == NULL || *comment == '\0')
268 		comment = xstrdup(filename);
269 	sshbuf_free(keyblob);
270 
271 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
272 	    lifetime, confirm)) == 0) {
273 		fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
274 		ret = 0;
275 		if (lifetime != 0)
276 			fprintf(stderr,
277 			    "Lifetime set to %d seconds\n", lifetime);
278 		if (confirm != 0)
279 			fprintf(stderr,
280 			    "The user must confirm each use of the key\n");
281 	} else {
282 		fprintf(stderr, "Could not add identity \"%s\": %s\n",
283 		    filename, ssh_err(r));
284 	}
285 
286 	/* Skip trying to load the cert if requested */
287 	if (key_only)
288 		goto out;
289 
290 	/* Now try to add the certificate flavour too */
291 	xasprintf(&certpath, "%s-cert.pub", filename);
292 	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
293 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
294 			error("Failed to load certificate \"%s\": %s",
295 			    certpath, ssh_err(r));
296 		goto out;
297 	}
298 
299 	if (!sshkey_equal_public(cert, private)) {
300 		error("Certificate %s does not match private key %s",
301 		    certpath, filename);
302 		sshkey_free(cert);
303 		goto out;
304 	}
305 
306 	/* Graft with private bits */
307 	if ((r = sshkey_to_certified(private)) != 0) {
308 		error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
309 		sshkey_free(cert);
310 		goto out;
311 	}
312 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
313 		error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
314 		sshkey_free(cert);
315 		goto out;
316 	}
317 	sshkey_free(cert);
318 
319 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
320 	    lifetime, confirm)) != 0) {
321 		error("Certificate %s (%s) add failed: %s", certpath,
322 		    private->cert->key_id, ssh_err(r));
323 		goto out;
324 	}
325 	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
326 	    private->cert->key_id);
327 	if (lifetime != 0)
328 		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
329 	if (confirm != 0)
330 		fprintf(stderr, "The user must confirm each use of the key\n");
331  out:
332 	free(certpath);
333 	free(comment);
334 	sshkey_free(private);
335 
336 	return ret;
337 }
338 
339 static int
340 update_card(int agent_fd, int add, const char *id)
341 {
342 	char *pin = NULL;
343 	int r, ret = -1;
344 
345 	if (add) {
346 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
347 		    RP_ALLOW_STDIN)) == NULL)
348 			return -1;
349 	}
350 
351 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
352 	    lifetime, confirm)) == 0) {
353 		fprintf(stderr, "Card %s: %s\n",
354 		    add ? "added" : "removed", id);
355 		ret = 0;
356 	} else {
357 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
358 		    add ? "add" : "remove", id, ssh_err(r));
359 		ret = -1;
360 	}
361 	free(pin);
362 	return ret;
363 }
364 
365 static int
366 list_identities(int agent_fd, int do_fp)
367 {
368 	char *fp;
369 	int r;
370 	struct ssh_identitylist *idlist;
371 	size_t i;
372 
373 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
374 		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
375 			fprintf(stderr, "error fetching identities: %s\n",
376 			    ssh_err(r));
377 		else
378 			printf("The agent has no identities.\n");
379 		return -1;
380 	}
381 	for (i = 0; i < idlist->nkeys; i++) {
382 		if (do_fp) {
383 			fp = sshkey_fingerprint(idlist->keys[i],
384 			    fingerprint_hash, SSH_FP_DEFAULT);
385 			printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
386 			    fp == NULL ? "(null)" : fp, idlist->comments[i],
387 			    sshkey_type(idlist->keys[i]));
388 			free(fp);
389 		} else {
390 			if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
391 				fprintf(stderr, "sshkey_write: %s\n",
392 				    ssh_err(r));
393 				continue;
394 			}
395 			fprintf(stdout, " %s\n", idlist->comments[i]);
396 		}
397 	}
398 	ssh_free_identitylist(idlist);
399 	return 0;
400 }
401 
402 static int
403 lock_agent(int agent_fd, int lock)
404 {
405 	char prompt[100], *p1, *p2;
406 	int r, passok = 1, ret = -1;
407 
408 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
409 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
410 	if (lock) {
411 		strlcpy(prompt, "Again: ", sizeof prompt);
412 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
413 		if (strcmp(p1, p2) != 0) {
414 			fprintf(stderr, "Passwords do not match.\n");
415 			passok = 0;
416 		}
417 		explicit_bzero(p2, strlen(p2));
418 		free(p2);
419 	}
420 	if (passok) {
421 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
422 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
423 			ret = 0;
424 		} else {
425 			fprintf(stderr, "Failed to %slock agent: %s\n",
426 			    lock ? "" : "un", ssh_err(r));
427 		}
428 	}
429 	explicit_bzero(p1, strlen(p1));
430 	free(p1);
431 	return (ret);
432 }
433 
434 static int
435 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag)
436 {
437 	if (deleting) {
438 		if (delete_file(agent_fd, file, key_only, qflag) == -1)
439 			return -1;
440 	} else {
441 		if (add_file(agent_fd, file, key_only, qflag) == -1)
442 			return -1;
443 	}
444 	return 0;
445 }
446 
447 static void
448 usage(void)
449 {
450 	fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
451 	fprintf(stderr, "Options:\n");
452 	fprintf(stderr, "  -l          List fingerprints of all identities.\n");
453 	fprintf(stderr, "  -E hash     Specify hash algorithm used for fingerprints.\n");
454 	fprintf(stderr, "  -L          List public key parameters of all identities.\n");
455 	fprintf(stderr, "  -k          Load only keys and not certificates.\n");
456 	fprintf(stderr, "  -c          Require confirmation to sign using identities\n");
457 	fprintf(stderr, "  -t life     Set lifetime (in seconds) when adding identities.\n");
458 	fprintf(stderr, "  -d          Delete identity.\n");
459 	fprintf(stderr, "  -D          Delete all identities.\n");
460 	fprintf(stderr, "  -x          Lock agent.\n");
461 	fprintf(stderr, "  -X          Unlock agent.\n");
462 	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
463 	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
464 	fprintf(stderr, "  -q          Be quiet after a successful operation.\n");
465 }
466 
467 int
468 main(int argc, char **argv)
469 {
470 	extern char *optarg;
471 	extern int optind;
472 	int agent_fd;
473 	char *pkcs11provider = NULL;
474 	int r, i, ch, deleting = 0, ret = 0, key_only = 0;
475 	int xflag = 0, lflag = 0, Dflag = 0, qflag = 0;
476 
477 	ssh_malloc_init();	/* must be called before any mallocs */
478 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
479 	sanitise_stdfd();
480 
481 	__progname = ssh_get_progname(argv[0]);
482 	seed_rng();
483 
484 #ifdef WITH_OPENSSL
485 	OpenSSL_add_all_algorithms();
486 #endif
487 
488 	setvbuf(stdout, NULL, _IOLBF, 0);
489 
490 	/* First, get a connection to the authentication agent. */
491 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
492 	case 0:
493 		break;
494 	case SSH_ERR_AGENT_NOT_PRESENT:
495 		fprintf(stderr, "Could not open a connection to your "
496 		    "authentication agent.\n");
497 		exit(2);
498 	default:
499 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
500 		exit(2);
501 	}
502 
503 	while ((ch = getopt(argc, argv, "klLcdDxXE:e:qs:t:")) != -1) {
504 		switch (ch) {
505 		case 'E':
506 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
507 			if (fingerprint_hash == -1)
508 				fatal("Invalid hash algorithm \"%s\"", optarg);
509 			break;
510 		case 'k':
511 			key_only = 1;
512 			break;
513 		case 'l':
514 		case 'L':
515 			if (lflag != 0)
516 				fatal("-%c flag already specified", lflag);
517 			lflag = ch;
518 			break;
519 		case 'x':
520 		case 'X':
521 			if (xflag != 0)
522 				fatal("-%c flag already specified", xflag);
523 			xflag = ch;
524 			break;
525 		case 'c':
526 			confirm = 1;
527 			break;
528 		case 'd':
529 			deleting = 1;
530 			break;
531 		case 'D':
532 			Dflag = 1;
533 			break;
534 		case 's':
535 			pkcs11provider = optarg;
536 			break;
537 		case 'e':
538 			deleting = 1;
539 			pkcs11provider = optarg;
540 			break;
541 		case 't':
542 			if ((lifetime = convtime(optarg)) == -1) {
543 				fprintf(stderr, "Invalid lifetime\n");
544 				ret = 1;
545 				goto done;
546 			}
547 			break;
548 		case 'q':
549 			qflag = 1;
550 			break;
551 		default:
552 			usage();
553 			ret = 1;
554 			goto done;
555 		}
556 	}
557 
558 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
559 		fatal("Invalid combination of actions");
560 	else if (xflag) {
561 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
562 			ret = 1;
563 		goto done;
564 	} else if (lflag) {
565 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
566 			ret = 1;
567 		goto done;
568 	} else if (Dflag) {
569 		if (delete_all(agent_fd) == -1)
570 			ret = 1;
571 		goto done;
572 	}
573 
574 	argc -= optind;
575 	argv += optind;
576 	if (pkcs11provider != NULL) {
577 		if (update_card(agent_fd, !deleting, pkcs11provider) == -1)
578 			ret = 1;
579 		goto done;
580 	}
581 	if (argc == 0) {
582 		char buf[PATH_MAX];
583 		struct passwd *pw;
584 		struct stat st;
585 		int count = 0;
586 
587 		if ((pw = getpwuid(getuid())) == NULL) {
588 			fprintf(stderr, "No user found with uid %u\n",
589 			    (u_int)getuid());
590 			ret = 1;
591 			goto done;
592 		}
593 
594 		for (i = 0; default_files[i]; i++) {
595 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
596 			    default_files[i]);
597 			if (stat(buf, &st) < 0)
598 				continue;
599 			if (do_file(agent_fd, deleting, key_only, buf,
600 			    qflag) == -1)
601 				ret = 1;
602 			else
603 				count++;
604 		}
605 		if (count == 0)
606 			ret = 1;
607 	} else {
608 		for (i = 0; i < argc; i++) {
609 			if (do_file(agent_fd, deleting, key_only,
610 			    argv[i], qflag) == -1)
611 				ret = 1;
612 		}
613 	}
614 	clear_pass();
615 
616 done:
617 	ssh_close_authentication_socket(agent_fd);
618 	return ret;
619 }
620