xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-add.c (revision e4d43b8226fdb8c949cce02b52dfec6fb53138b6)
1 /*	$NetBSD: ssh-add.c,v 1.10 2015/04/03 23:58:19 christos Exp $	*/
2 /* $OpenBSD: ssh-add.c,v 1.120 2015/02/21 21:46:57 halex Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * Adds an identity to the authentication server, or removes an identity.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * SSH2 implementation,
16  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include "includes.h"
40 __RCSID("$NetBSD: ssh-add.c,v 1.10 2015/04/03 23:58:19 christos Exp $");
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 
44 #include <openssl/evp.h>
45 
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <limits.h>
54 
55 #include "xmalloc.h"
56 #include "ssh.h"
57 #include "rsa.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 const char *default_files[] = {
73 	_PATH_SSH_CLIENT_ID_RSA,
74 	_PATH_SSH_CLIENT_ID_DSA,
75 	_PATH_SSH_CLIENT_ID_ECDSA,
76 	_PATH_SSH_CLIENT_ID_ED25519,
77 	_PATH_SSH_CLIENT_IDENTITY,
78 	NULL
79 };
80 
81 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
82 
83 /* Default lifetime (0 == forever) */
84 static int lifetime = 0;
85 
86 /* User has to confirm key use */
87 static int confirm = 0;
88 
89 /* we keep a cache of one passphrases */
90 static char *pass = NULL;
91 static void
92 clear_pass(void)
93 {
94 	if (pass) {
95 		explicit_bzero(pass, strlen(pass));
96 		free(pass);
97 		pass = NULL;
98 	}
99 }
100 
101 static int
102 delete_file(int agent_fd, const char *filename, int key_only)
103 {
104 	struct sshkey *public, *cert = NULL;
105 	char *certpath = NULL, *comment = NULL;
106 	int r, ret = -1;
107 
108 	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
109 		printf("Bad key file %s: %s\n", filename, ssh_err(r));
110 		return -1;
111 	}
112 	if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
113 		fprintf(stderr, "Identity removed: %s (%s)\n", filename, comment);
114 		ret = 0;
115 	} else
116 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
117 		    filename, ssh_err(r));
118 
119 	if (key_only)
120 		goto out;
121 
122 	/* Now try to delete the corresponding certificate too */
123 	free(comment);
124 	comment = NULL;
125 	xasprintf(&certpath, "%s-cert.pub", filename);
126 	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
127 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
128 			error("Failed to load certificate \"%s\": %s",
129 			    certpath, ssh_err(r));
130 		goto out;
131 	}
132 
133 	if (!sshkey_equal_public(cert, public))
134 		fatal("Certificate %s does not match private key %s",
135 		    certpath, filename);
136 
137 	if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
138 		fprintf(stderr, "Identity removed: %s (%s)\n", certpath,
139 		    comment);
140 		ret = 0;
141 	} else
142 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
143 		    certpath, ssh_err(r));
144 
145  out:
146 	if (cert != NULL)
147 		sshkey_free(cert);
148 	if (public != NULL)
149 		sshkey_free(public);
150 	free(certpath);
151 	free(comment);
152 
153 	return ret;
154 }
155 
156 /* Send a request to remove all identities. */
157 static int
158 delete_all(int agent_fd)
159 {
160 	int ret = -1;
161 
162 	if (ssh_remove_all_identities(agent_fd, 1) == 0)
163 		ret = 0;
164 	/* ignore error-code for ssh2 */
165 	/* XXX revisit */
166 	ssh_remove_all_identities(agent_fd, 2);
167 
168 	if (ret == 0)
169 		fprintf(stderr, "All identities removed.\n");
170 	else
171 		fprintf(stderr, "Failed to remove all identities.\n");
172 
173 	return ret;
174 }
175 
176 static int
177 add_file(int agent_fd, const char *filename, int key_only)
178 {
179 	struct sshkey *private, *cert;
180 	char *comment = NULL;
181 	char msg[1024], *certpath = NULL;
182 	int r, fd, ret = -1;
183 	struct sshbuf *keyblob;
184 
185 	if (strcmp(filename, "-") == 0) {
186 		fd = STDIN_FILENO;
187 		filename = "(stdin)";
188 	} else if ((fd = open(filename, O_RDONLY)) < 0) {
189 		perror(filename);
190 		return -1;
191 	}
192 
193 	/*
194 	 * Since we'll try to load a keyfile multiple times, permission errors
195 	 * will occur multiple times, so check perms first and bail if wrong.
196 	 */
197 	if (fd != STDIN_FILENO) {
198 		if (sshkey_perm_ok(fd, filename) != 0) {
199 			close(fd);
200 			return -1;
201 		}
202 	}
203 	if ((keyblob = sshbuf_new()) == NULL)
204 		fatal("%s: sshbuf_new failed", __func__);
205 	if ((r = sshkey_load_file(fd, keyblob)) != 0) {
206 		fprintf(stderr, "Error loading key \"%s\": %s\n",
207 		    filename, ssh_err(r));
208 		sshbuf_free(keyblob);
209 		close(fd);
210 		return -1;
211 	}
212 	close(fd);
213 
214 	/* At first, try empty passphrase */
215 	if ((r = sshkey_parse_private_fileblob(keyblob, "", filename,
216 	    &private, &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
217 		fprintf(stderr, "Error loading key \"%s\": %s\n",
218 		    filename, ssh_err(r));
219 		goto fail_load;
220 	}
221 	/* try last */
222 	if (private == NULL && pass != NULL) {
223 		if ((r = sshkey_parse_private_fileblob(keyblob, pass, filename,
224 		    &private, &comment)) != 0 &&
225 		    r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
226 			fprintf(stderr, "Error loading key \"%s\": %s\n",
227 			    filename, ssh_err(r));
228 			goto fail_load;
229 		}
230 	}
231 	if (comment == NULL)
232 		comment = xstrdup(filename);
233 	if (private == NULL) {
234 		/* clear passphrase since it did not work */
235 		clear_pass();
236 		snprintf(msg, sizeof msg, "Enter passphrase for %.200s%s: ",
237 		    comment, confirm ? " (will confirm each use)" : "");
238 		for (;;) {
239 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
240 			if (strcmp(pass, "") == 0)
241 				goto fail_load;
242 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
243 			    filename, &private, NULL)) == 0)
244 				break;
245 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
246 				fprintf(stderr,
247 				    "Error loading key \"%s\": %s\n",
248 				    filename, ssh_err(r));
249  fail_load:
250 				clear_pass();
251 				free(comment);
252 				sshbuf_free(keyblob);
253 				return -1;
254 			}
255 			clear_pass();
256 			snprintf(msg, sizeof msg,
257 			    "Bad passphrase, try again for %.200s%s: ", comment,
258 			    confirm ? " (will confirm each use)" : "");
259 		}
260 	}
261 	sshbuf_free(keyblob);
262 
263 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
264 	    lifetime, confirm)) == 0) {
265 		fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
266 		ret = 0;
267 		if (lifetime != 0)
268 			fprintf(stderr,
269 			    "Lifetime set to %d seconds\n", lifetime);
270 		if (confirm != 0)
271 			fprintf(stderr,
272 			    "The user must confirm each use of the key\n");
273 	} else {
274 		fprintf(stderr, "Could not add identity \"%s\": %s\n",
275 		    filename, ssh_err(r));
276 	}
277 
278 	/* Skip trying to load the cert if requested */
279 	if (key_only)
280 		goto out;
281 
282 	/* Now try to add the certificate flavour too */
283 	xasprintf(&certpath, "%s-cert.pub", filename);
284 	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
285 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
286 			error("Failed to load certificate \"%s\": %s",
287 			    certpath, ssh_err(r));
288 		goto out;
289 	}
290 
291 	if (!sshkey_equal_public(cert, private)) {
292 		error("Certificate %s does not match private key %s",
293 		    certpath, filename);
294 		sshkey_free(cert);
295 		goto out;
296 	}
297 
298 	/* Graft with private bits */
299 	if ((r = sshkey_to_certified(private,
300 	    sshkey_cert_is_legacy(cert))) != 0) {
301 		error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
302 		sshkey_free(cert);
303 		goto out;
304 	}
305 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
306 		error("%s: key_cert_copy: %s", __func__, ssh_err(r));
307 		sshkey_free(cert);
308 		goto out;
309 	}
310 	sshkey_free(cert);
311 
312 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
313 	    lifetime, confirm)) != 0) {
314 		error("Certificate %s (%s) add failed: %s", certpath,
315 		    private->cert->key_id, ssh_err(r));
316 		goto out;
317 	}
318 	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
319 	    private->cert->key_id);
320 	if (lifetime != 0)
321 		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
322 	if (confirm != 0)
323 		fprintf(stderr, "The user must confirm each use of the key\n");
324  out:
325 	free(certpath);
326 	free(comment);
327 	sshkey_free(private);
328 
329 	return ret;
330 }
331 
332 static int
333 update_card(int agent_fd, int add, const char *id)
334 {
335 	char *pin = NULL;
336 	int r, ret = -1;
337 
338 	if (add) {
339 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
340 		    RP_ALLOW_STDIN)) == NULL)
341 			return -1;
342 	}
343 
344 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
345 	    lifetime, confirm)) == 0) {
346 		fprintf(stderr, "Card %s: %s\n",
347 		    add ? "added" : "removed", id);
348 		ret = 0;
349 	} else {
350 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
351 		    add ? "add" : "remove", id, ssh_err(r));
352 		ret = -1;
353 	}
354 	free(pin);
355 	return ret;
356 }
357 
358 static int
359 list_identities(int agent_fd, int do_fp)
360 {
361 	char *fp;
362 	int version, r, had_identities = 0;
363 	struct ssh_identitylist *idlist;
364 	size_t i;
365 
366 	for (version = 1; version <= 2; version++) {
367 		if ((r = ssh_fetch_identitylist(agent_fd, version,
368 		    &idlist)) != 0) {
369 			if (r != SSH_ERR_AGENT_NO_IDENTITIES)
370 				fprintf(stderr, "error fetching identities for "
371 				    "protocol %d: %s\n", version, ssh_err(r));
372 			continue;
373 		}
374 		for (i = 0; i < idlist->nkeys; i++) {
375 			had_identities = 1;
376 			if (do_fp) {
377 				fp = sshkey_fingerprint(idlist->keys[i],
378 				    fingerprint_hash, SSH_FP_DEFAULT);
379 				printf("%d %s %s (%s)\n",
380 				    sshkey_size(idlist->keys[i]),
381 				    fp == NULL ? "(null)" : fp,
382 				    idlist->comments[i],
383 				    sshkey_type(idlist->keys[i]));
384 				free(fp);
385 			} else {
386 				if ((r = sshkey_write(idlist->keys[i],
387 				    stdout)) != 0) {
388 					fprintf(stderr, "sshkey_write: %s\n",
389 					    ssh_err(r));
390 					continue;
391 				}
392 				fprintf(stdout, " %s\n", idlist->comments[i]);
393 			}
394 		}
395 		ssh_free_identitylist(idlist);
396 	}
397 	if (!had_identities) {
398 		printf("The agent has no identities.\n");
399 		return -1;
400 	}
401 	return 0;
402 }
403 
404 static int
405 lock_agent(int agent_fd, int lock)
406 {
407 	char prompt[100], *p1, *p2;
408 	int r, passok = 1, ret = -1;
409 
410 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
411 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
412 	if (lock) {
413 		strlcpy(prompt, "Again: ", sizeof prompt);
414 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
415 		if (strcmp(p1, p2) != 0) {
416 			fprintf(stderr, "Passwords do not match.\n");
417 			passok = 0;
418 		}
419 		explicit_bzero(p2, strlen(p2));
420 		free(p2);
421 	}
422 	if (passok) {
423 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
424 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
425 			ret = 0;
426 		} else {
427 			fprintf(stderr, "Failed to %slock agent: %s\n",
428 			    lock ? "" : "un", ssh_err(r));
429 		}
430 	}
431 	explicit_bzero(p1, strlen(p1));
432 	free(p1);
433 	return (ret);
434 }
435 
436 static int
437 do_file(int agent_fd, int deleting, int key_only, char *file)
438 {
439 	if (deleting) {
440 		if (delete_file(agent_fd, file, key_only) == -1)
441 			return -1;
442 	} else {
443 		if (add_file(agent_fd, file, key_only) == -1)
444 			return -1;
445 	}
446 	return 0;
447 }
448 
449 static void
450 usage(void)
451 {
452 	fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
453 	fprintf(stderr, "Options:\n");
454 	fprintf(stderr, "  -l          List fingerprints of all identities.\n");
455 	fprintf(stderr, "  -E hash     Specify hash algorithm used for fingerprints.\n");
456 	fprintf(stderr, "  -L          List public key parameters of all identities.\n");
457 	fprintf(stderr, "  -k          Load only keys and not certificates.\n");
458 	fprintf(stderr, "  -c          Require confirmation to sign using identities\n");
459 	fprintf(stderr, "  -t life     Set lifetime (in seconds) when adding identities.\n");
460 	fprintf(stderr, "  -d          Delete identity.\n");
461 	fprintf(stderr, "  -D          Delete all identities.\n");
462 	fprintf(stderr, "  -x          Lock agent.\n");
463 	fprintf(stderr, "  -X          Unlock agent.\n");
464 	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
465 	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
466 }
467 
468 int
469 main(int argc, char **argv)
470 {
471 	extern char *optarg;
472 	extern int optind;
473 	int agent_fd;
474 	char *pkcs11provider = NULL;
475 	int r, i, ch, deleting = 0, ret = 0, key_only = 0;
476 	int xflag = 0, lflag = 0, Dflag = 0;
477 
478 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
479 	sanitise_stdfd();
480 
481 	OpenSSL_add_all_algorithms();
482 
483 	setvbuf(stdout, NULL, _IOLBF, 0);
484 
485 	/* First, get a connection to the authentication agent. */
486 	switch (r = ssh_get_authentication_socket(&agent_fd)) {
487 	case 0:
488 		break;
489 	case SSH_ERR_AGENT_NOT_PRESENT:
490 		fprintf(stderr, "Could not open a connection to your "
491 		    "authentication agent.\n");
492 		exit(2);
493 	default:
494 		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
495 		exit(2);
496 	}
497 
498 	while ((ch = getopt(argc, argv, "klLcdDxXE:e:s:t:")) != -1) {
499 		switch (ch) {
500 		case 'E':
501 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
502 			if (fingerprint_hash == -1)
503 				fatal("Invalid hash algorithm \"%s\"", optarg);
504 			break;
505 		case 'k':
506 			key_only = 1;
507 			break;
508 		case 'l':
509 		case 'L':
510 			if (lflag != 0)
511 				fatal("-%c flag already specified", lflag);
512 			lflag = ch;
513 			break;
514 		case 'x':
515 		case 'X':
516 			if (xflag != 0)
517 				fatal("-%c flag already specified", xflag);
518 			xflag = ch;
519 			break;
520 		case 'c':
521 			confirm = 1;
522 			break;
523 		case 'd':
524 			deleting = 1;
525 			break;
526 		case 'D':
527 			Dflag = 1;
528 			break;
529 		case 's':
530 			pkcs11provider = optarg;
531 			break;
532 		case 'e':
533 			deleting = 1;
534 			pkcs11provider = optarg;
535 			break;
536 		case 't':
537 			if ((lifetime = convtime(optarg)) == -1) {
538 				fprintf(stderr, "Invalid lifetime\n");
539 				ret = 1;
540 				goto done;
541 			}
542 			break;
543 		default:
544 			usage();
545 			ret = 1;
546 			goto done;
547 		}
548 	}
549 
550 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
551 		fatal("Invalid combination of actions");
552 	else if (xflag) {
553 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
554 			ret = 1;
555 		goto done;
556 	} else if (lflag) {
557 		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
558 			ret = 1;
559 		goto done;
560 	} else if (Dflag) {
561 		if (delete_all(agent_fd) == -1)
562 			ret = 1;
563 		goto done;
564 	}
565 
566 	argc -= optind;
567 	argv += optind;
568 	if (pkcs11provider != NULL) {
569 		if (update_card(agent_fd, !deleting, pkcs11provider) == -1)
570 			ret = 1;
571 		goto done;
572 	}
573 	if (argc == 0) {
574 		char buf[PATH_MAX];
575 		struct passwd *pw;
576 		struct stat st;
577 		int count = 0;
578 
579 		if ((pw = getpwuid(getuid())) == NULL) {
580 			fprintf(stderr, "No user found with uid %u\n",
581 			    (u_int)getuid());
582 			ret = 1;
583 			goto done;
584 		}
585 
586 		for (i = 0; default_files[i]; i++) {
587 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
588 			    default_files[i]);
589 			if (stat(buf, &st) < 0)
590 				continue;
591 			if (do_file(agent_fd, deleting, key_only, buf) == -1)
592 				ret = 1;
593 			else
594 				count++;
595 		}
596 		if (count == 0)
597 			ret = 1;
598 	} else {
599 		for (i = 0; i < argc; i++) {
600 			if (do_file(agent_fd, deleting, key_only,
601 			    argv[i]) == -1)
602 				ret = 1;
603 		}
604 	}
605 	clear_pass();
606 
607 done:
608 	ssh_close_authentication_socket(agent_fd);
609 	return ret;
610 }
611