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