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