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