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