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