xref: /openbsd-src/usr.bin/ssh/ssh-add.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /* $OpenBSD: ssh-add.c,v 1.128 2016/02/15 09:47:49 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 #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 passphrase */
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 	sshkey_free(cert);
146 	sshkey_free(public);
147 	free(certpath);
148 	free(comment);
149 
150 	return ret;
151 }
152 
153 /* Send a request to remove all identities. */
154 static int
155 delete_all(int agent_fd)
156 {
157 	int ret = -1;
158 
159 	if (ssh_remove_all_identities(agent_fd, 2) == 0)
160 		ret = 0;
161 	/* ignore error-code for ssh1 */
162 	ssh_remove_all_identities(agent_fd, 1);
163 
164 	if (ret == 0)
165 		fprintf(stderr, "All identities removed.\n");
166 	else
167 		fprintf(stderr, "Failed to remove all identities.\n");
168 
169 	return ret;
170 }
171 
172 static int
173 add_file(int agent_fd, const char *filename, int key_only)
174 {
175 	struct sshkey *private, *cert;
176 	char *comment = NULL;
177 	char msg[1024], *certpath = NULL;
178 	int r, fd, ret = -1;
179 	struct sshbuf *keyblob;
180 
181 	if (strcmp(filename, "-") == 0) {
182 		fd = STDIN_FILENO;
183 		filename = "(stdin)";
184 	} else if ((fd = open(filename, O_RDONLY)) < 0) {
185 		perror(filename);
186 		return -1;
187 	}
188 
189 	/*
190 	 * Since we'll try to load a keyfile multiple times, permission errors
191 	 * will occur multiple times, so check perms first and bail if wrong.
192 	 */
193 	if (fd != STDIN_FILENO) {
194 		if (sshkey_perm_ok(fd, filename) != 0) {
195 			close(fd);
196 			return -1;
197 		}
198 	}
199 	if ((keyblob = sshbuf_new()) == NULL)
200 		fatal("%s: sshbuf_new failed", __func__);
201 	if ((r = sshkey_load_file(fd, keyblob)) != 0) {
202 		fprintf(stderr, "Error loading key \"%s\": %s\n",
203 		    filename, ssh_err(r));
204 		sshbuf_free(keyblob);
205 		close(fd);
206 		return -1;
207 	}
208 	close(fd);
209 
210 	/* At first, try empty passphrase */
211 	if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
212 	    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
213 		fprintf(stderr, "Error loading key \"%s\": %s\n",
214 		    filename, ssh_err(r));
215 		goto fail_load;
216 	}
217 	/* try last */
218 	if (private == NULL && pass != NULL) {
219 		if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
220 		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
221 			fprintf(stderr, "Error loading key \"%s\": %s\n",
222 			    filename, ssh_err(r));
223 			goto fail_load;
224 		}
225 	}
226 	if (private == NULL) {
227 		/* clear passphrase since it did not work */
228 		clear_pass();
229 		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
230 		    filename, confirm ? " (will confirm each use)" : "");
231 		for (;;) {
232 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
233 			if (strcmp(pass, "") == 0)
234 				goto fail_load;
235 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
236 			    &private, &comment)) == 0)
237 				break;
238 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
239 				fprintf(stderr,
240 				    "Error loading key \"%s\": %s\n",
241 				    filename, ssh_err(r));
242  fail_load:
243 				clear_pass();
244 				sshbuf_free(keyblob);
245 				return -1;
246 			}
247 			clear_pass();
248 			snprintf(msg, sizeof msg,
249 			    "Bad passphrase, try again for %s%s: ", filename,
250 			    confirm ? " (will confirm each use)" : "");
251 		}
252 	}
253 	if (comment == NULL || *comment == '\0')
254 		comment = xstrdup(filename);
255 	sshbuf_free(keyblob);
256 
257 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
258 	    lifetime, confirm)) == 0) {
259 		fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
260 		ret = 0;
261 		if (lifetime != 0)
262 			fprintf(stderr,
263 			    "Lifetime set to %d seconds\n", lifetime);
264 		if (confirm != 0)
265 			fprintf(stderr,
266 			    "The user must confirm each use of the key\n");
267 	} else {
268 		fprintf(stderr, "Could not add identity \"%s\": %s\n",
269 		    filename, ssh_err(r));
270 	}
271 
272 	/* Skip trying to load the cert if requested */
273 	if (key_only)
274 		goto out;
275 
276 	/* Now try to add the certificate flavour too */
277 	xasprintf(&certpath, "%s-cert.pub", filename);
278 	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
279 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
280 			error("Failed to load certificate \"%s\": %s",
281 			    certpath, ssh_err(r));
282 		goto out;
283 	}
284 
285 	if (!sshkey_equal_public(cert, private)) {
286 		error("Certificate %s does not match private key %s",
287 		    certpath, filename);
288 		sshkey_free(cert);
289 		goto out;
290 	}
291 
292 	/* Graft with private bits */
293 	if ((r = sshkey_to_certified(private)) != 0) {
294 		error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
295 		sshkey_free(cert);
296 		goto out;
297 	}
298 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
299 		error("%s: key_cert_copy: %s", __func__, ssh_err(r));
300 		sshkey_free(cert);
301 		goto out;
302 	}
303 	sshkey_free(cert);
304 
305 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
306 	    lifetime, confirm)) != 0) {
307 		error("Certificate %s (%s) add failed: %s", certpath,
308 		    private->cert->key_id, ssh_err(r));
309 		goto out;
310 	}
311 	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
312 	    private->cert->key_id);
313 	if (lifetime != 0)
314 		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
315 	if (confirm != 0)
316 		fprintf(stderr, "The user must confirm each use of the key\n");
317  out:
318 	free(certpath);
319 	free(comment);
320 	sshkey_free(private);
321 
322 	return ret;
323 }
324 
325 static int
326 update_card(int agent_fd, int add, const char *id)
327 {
328 	char *pin = NULL;
329 	int r, ret = -1;
330 
331 	if (add) {
332 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
333 		    RP_ALLOW_STDIN)) == NULL)
334 			return -1;
335 	}
336 
337 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
338 	    lifetime, confirm)) == 0) {
339 		fprintf(stderr, "Card %s: %s\n",
340 		    add ? "added" : "removed", id);
341 		ret = 0;
342 	} else {
343 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
344 		    add ? "add" : "remove", id, ssh_err(r));
345 		ret = -1;
346 	}
347 	free(pin);
348 	return ret;
349 }
350 
351 static int
352 list_identities(int agent_fd, int do_fp)
353 {
354 	char *fp;
355 	int r, had_identities = 0;
356 	struct ssh_identitylist *idlist;
357 	size_t i;
358 #ifdef WITH_SSH1
359 	int version = 1;
360 #else
361 	int version = 2;
362 #endif
363 
364 	for (; version <= 2; version++) {
365 		if ((r = ssh_fetch_identitylist(agent_fd, version,
366 		    &idlist)) != 0) {
367 			if (r != SSH_ERR_AGENT_NO_IDENTITIES)
368 				fprintf(stderr, "error fetching identities for "
369 				    "protocol %d: %s\n", version, ssh_err(r));
370 			continue;
371 		}
372 		for (i = 0; i < idlist->nkeys; i++) {
373 			had_identities = 1;
374 			if (do_fp) {
375 				fp = sshkey_fingerprint(idlist->keys[i],
376 				    fingerprint_hash, SSH_FP_DEFAULT);
377 				printf("%u %s %s (%s)\n",
378 				    sshkey_size(idlist->keys[i]),
379 				    fp == NULL ? "(null)" : fp,
380 				    idlist->comments[i],
381 				    sshkey_type(idlist->keys[i]));
382 				free(fp);
383 			} else {
384 				if ((r = sshkey_write(idlist->keys[i],
385 				    stdout)) != 0) {
386 					fprintf(stderr, "sshkey_write: %s\n",
387 					    ssh_err(r));
388 					continue;
389 				}
390 				fprintf(stdout, " %s\n", idlist->comments[i]);
391 			}
392 		}
393 		ssh_free_identitylist(idlist);
394 	}
395 	if (!had_identities) {
396 		printf("The agent has no identities.\n");
397 		return -1;
398 	}
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)
436 {
437 	if (deleting) {
438 		if (delete_file(agent_fd, file, key_only) == -1)
439 			return -1;
440 	} else {
441 		if (add_file(agent_fd, file, key_only) == -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 }
465 
466 int
467 main(int argc, char **argv)
468 {
469 	extern char *optarg;
470 	extern int optind;
471 	int agent_fd;
472 	char *pkcs11provider = NULL;
473 	int r, i, ch, deleting = 0, ret = 0, key_only = 0;
474 	int xflag = 0, lflag = 0, Dflag = 0;
475 
476 	ssh_malloc_init();	/* must be called before any mallocs */
477 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
478 	sanitise_stdfd();
479 
480 	OpenSSL_add_all_algorithms();
481 
482 	setvbuf(stdout, NULL, _IOLBF, 0);
483 
484 	/* First, get a connection to the authentication agent. */
485 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
486 	case 0:
487 		break;
488 	case SSH_ERR_AGENT_NOT_PRESENT:
489 		fprintf(stderr, "Could not open a connection to your "
490 		    "authentication agent.\n");
491 		exit(2);
492 	default:
493 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
494 		exit(2);
495 	}
496 
497 	while ((ch = getopt(argc, argv, "klLcdDxXE:e:s:t:")) != -1) {
498 		switch (ch) {
499 		case 'E':
500 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
501 			if (fingerprint_hash == -1)
502 				fatal("Invalid hash algorithm \"%s\"", optarg);
503 			break;
504 		case 'k':
505 			key_only = 1;
506 			break;
507 		case 'l':
508 		case 'L':
509 			if (lflag != 0)
510 				fatal("-%c flag already specified", lflag);
511 			lflag = ch;
512 			break;
513 		case 'x':
514 		case 'X':
515 			if (xflag != 0)
516 				fatal("-%c flag already specified", xflag);
517 			xflag = ch;
518 			break;
519 		case 'c':
520 			confirm = 1;
521 			break;
522 		case 'd':
523 			deleting = 1;
524 			break;
525 		case 'D':
526 			Dflag = 1;
527 			break;
528 		case 's':
529 			pkcs11provider = optarg;
530 			break;
531 		case 'e':
532 			deleting = 1;
533 			pkcs11provider = optarg;
534 			break;
535 		case 't':
536 			if ((lifetime = convtime(optarg)) == -1) {
537 				fprintf(stderr, "Invalid lifetime\n");
538 				ret = 1;
539 				goto done;
540 			}
541 			break;
542 		default:
543 			usage();
544 			ret = 1;
545 			goto done;
546 		}
547 	}
548 
549 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
550 		fatal("Invalid combination of actions");
551 	else if (xflag) {
552 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
553 			ret = 1;
554 		goto done;
555 	} else if (lflag) {
556 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
557 			ret = 1;
558 		goto done;
559 	} else if (Dflag) {
560 		if (delete_all(agent_fd) == -1)
561 			ret = 1;
562 		goto done;
563 	}
564 
565 	argc -= optind;
566 	argv += optind;
567 	if (pkcs11provider != NULL) {
568 		if (update_card(agent_fd, !deleting, pkcs11provider) == -1)
569 			ret = 1;
570 		goto done;
571 	}
572 	if (argc == 0) {
573 		char buf[PATH_MAX];
574 		struct passwd *pw;
575 		struct stat st;
576 		int count = 0;
577 
578 		if ((pw = getpwuid(getuid())) == NULL) {
579 			fprintf(stderr, "No user found with uid %u\n",
580 			    (u_int)getuid());
581 			ret = 1;
582 			goto done;
583 		}
584 
585 		for (i = 0; default_files[i]; i++) {
586 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
587 			    default_files[i]);
588 			if (stat(buf, &st) < 0)
589 				continue;
590 			if (do_file(agent_fd, deleting, key_only, buf) == -1)
591 				ret = 1;
592 			else
593 				count++;
594 		}
595 		if (count == 0)
596 			ret = 1;
597 	} else {
598 		for (i = 0; i < argc; i++) {
599 			if (do_file(agent_fd, deleting, key_only,
600 			    argv[i]) == -1)
601 				ret = 1;
602 		}
603 	}
604 	clear_pass();
605 
606 done:
607 	ssh_close_authentication_socket(agent_fd);
608 	return ret;
609 }
610