xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-add.c (revision ee85abc4170216bcc479236cf33e956766cf9eb4)
1 /*	$NetBSD: ssh-add.c,v 1.14 2016/12/25 00:07:47 christos Exp $	*/
2 /* $OpenBSD: ssh-add.c,v 1.128 2016/02/15 09:47:49 dtucker Exp $ */
3 
4 /*
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7  *                    All rights reserved
8  * Adds an identity to the authentication server, or removes an identity.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 implementation,
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include "includes.h"
41 __RCSID("$NetBSD: ssh-add.c,v 1.14 2016/12/25 00:07:47 christos Exp $");
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 
45 #include <openssl/evp.h>
46 
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <pwd.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <limits.h>
55 
56 #include "xmalloc.h"
57 #include "ssh.h"
58 #include "rsa.h"
59 #include "log.h"
60 #include "sshkey.h"
61 #include "sshbuf.h"
62 #include "authfd.h"
63 #include "authfile.h"
64 #include "pathnames.h"
65 #include "misc.h"
66 #include "ssherr.h"
67 #include "digest.h"
68 
69 /* argv0 */
70 extern char *__progname;
71 
72 /* Default files to add */
73 static const char *default_files[] = {
74 	_PATH_SSH_CLIENT_ID_RSA,
75 	_PATH_SSH_CLIENT_ID_DSA,
76 	_PATH_SSH_CLIENT_ID_ECDSA,
77 	_PATH_SSH_CLIENT_ID_ED25519,
78 #ifdef WITH_SSH1
79 	_PATH_SSH_CLIENT_IDENTITY,
80 #endif
81 	NULL
82 };
83 
84 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
85 
86 /* Default lifetime (0 == forever) */
87 static int lifetime = 0;
88 
89 /* User has to confirm key use */
90 static int confirm = 0;
91 
92 /* we keep a cache of one passphrase */
93 static char *pass = NULL;
94 static void
95 clear_pass(void)
96 {
97 	if (pass) {
98 		explicit_bzero(pass, strlen(pass));
99 		free(pass);
100 		pass = NULL;
101 	}
102 }
103 
104 static int
105 delete_file(int agent_fd, const char *filename, int key_only)
106 {
107 	struct sshkey *public, *cert = NULL;
108 	char *certpath = NULL, *comment = NULL;
109 	int r, ret = -1;
110 
111 	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
112 		printf("Bad key file %s: %s\n", filename, ssh_err(r));
113 		return -1;
114 	}
115 	if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
116 		fprintf(stderr, "Identity removed: %s (%s)\n", filename, comment);
117 		ret = 0;
118 	} else
119 		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
120 		    filename, ssh_err(r));
121 
122 	if (key_only)
123 		goto out;
124 
125 	/* Now try to delete the corresponding certificate too */
126 	free(comment);
127 	comment = NULL;
128 	xasprintf(&certpath, "%s-cert.pub", filename);
129 	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
130 		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
131 			error("Failed to load certificate \"%s\": %s",
132 			    certpath, ssh_err(r));
133 		goto out;
134 	}
135 
136 	if (!sshkey_equal_public(cert, public))
137 		fatal("Certificate %s does not match private key %s",
138 		    certpath, filename);
139 
140 	if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
141 		fprintf(stderr, "Identity removed: %s (%s)\n", certpath,
142 		    comment);
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 	if (ssh_remove_all_identities(agent_fd, 2) == 0)
164 		ret = 0;
165 	/* ignore error-code for ssh1 */
166 	ssh_remove_all_identities(agent_fd, 1);
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, "", &private,
216 	    &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, &private,
224 		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
225 			fprintf(stderr, "Error loading key \"%s\": %s\n",
226 			    filename, ssh_err(r));
227 			goto fail_load;
228 		}
229 	}
230 	if (private == NULL) {
231 		/* clear passphrase since it did not work */
232 		clear_pass();
233 		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
234 		    filename, confirm ? " (will confirm each use)" : "");
235 		for (;;) {
236 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
237 			if (strcmp(pass, "") == 0)
238 				goto fail_load;
239 			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
240 			    &private, &comment)) == 0)
241 				break;
242 			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
243 				fprintf(stderr,
244 				    "Error loading key \"%s\": %s\n",
245 				    filename, ssh_err(r));
246  fail_load:
247 				clear_pass();
248 				sshbuf_free(keyblob);
249 				return -1;
250 			}
251 			clear_pass();
252 			snprintf(msg, sizeof msg,
253 			    "Bad passphrase, try again for %s%s: ", filename,
254 			    confirm ? " (will confirm each use)" : "");
255 		}
256 	}
257 	if (comment == NULL || *comment == '\0')
258 		comment = xstrdup(filename);
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)) != 0) {
298 		error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
299 		sshkey_free(cert);
300 		goto out;
301 	}
302 	if ((r = sshkey_cert_copy(cert, private)) != 0) {
303 		error("%s: key_cert_copy: %s", __func__, ssh_err(r));
304 		sshkey_free(cert);
305 		goto out;
306 	}
307 	sshkey_free(cert);
308 
309 	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
310 	    lifetime, confirm)) != 0) {
311 		error("Certificate %s (%s) add failed: %s", certpath,
312 		    private->cert->key_id, ssh_err(r));
313 		goto out;
314 	}
315 	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
316 	    private->cert->key_id);
317 	if (lifetime != 0)
318 		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
319 	if (confirm != 0)
320 		fprintf(stderr, "The user must confirm each use of the key\n");
321  out:
322 	free(certpath);
323 	free(comment);
324 	sshkey_free(private);
325 
326 	return ret;
327 }
328 
329 static int
330 update_card(int agent_fd, int add, const char *id)
331 {
332 	char *pin = NULL;
333 	int r, ret = -1;
334 
335 	if (add) {
336 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
337 		    RP_ALLOW_STDIN)) == NULL)
338 			return -1;
339 	}
340 
341 	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
342 	    lifetime, confirm)) == 0) {
343 		fprintf(stderr, "Card %s: %s\n",
344 		    add ? "added" : "removed", id);
345 		ret = 0;
346 	} else {
347 		fprintf(stderr, "Could not %s card \"%s\": %s\n",
348 		    add ? "add" : "remove", id, ssh_err(r));
349 		ret = -1;
350 	}
351 	free(pin);
352 	return ret;
353 }
354 
355 static int
356 list_identities(int agent_fd, int do_fp)
357 {
358 	char *fp;
359 	int r, had_identities = 0;
360 	struct ssh_identitylist *idlist;
361 	size_t i;
362 #ifdef WITH_SSH1
363 	int version = 1;
364 #else
365 	int version = 2;
366 #endif
367 
368 	for (; version <= 2; version++) {
369 		if ((r = ssh_fetch_identitylist(agent_fd, version,
370 		    &idlist)) != 0) {
371 			if (r != SSH_ERR_AGENT_NO_IDENTITIES)
372 				fprintf(stderr, "error fetching identities for "
373 				    "protocol %d: %s\n", version, ssh_err(r));
374 			continue;
375 		}
376 		for (i = 0; i < idlist->nkeys; i++) {
377 			had_identities = 1;
378 			if (do_fp) {
379 				fp = sshkey_fingerprint(idlist->keys[i],
380 				    fingerprint_hash, SSH_FP_DEFAULT);
381 				printf("%u %s %s (%s)\n",
382 				    sshkey_size(idlist->keys[i]),
383 				    fp == NULL ? "(null)" : fp,
384 				    idlist->comments[i],
385 				    sshkey_type(idlist->keys[i]));
386 				free(fp);
387 			} else {
388 				if ((r = sshkey_write(idlist->keys[i],
389 				    stdout)) != 0) {
390 					fprintf(stderr, "sshkey_write: %s\n",
391 					    ssh_err(r));
392 					continue;
393 				}
394 				fprintf(stdout, " %s\n", idlist->comments[i]);
395 			}
396 		}
397 		ssh_free_identitylist(idlist);
398 	}
399 	if (!had_identities) {
400 		printf("The agent has no identities.\n");
401 		return -1;
402 	}
403 	return 0;
404 }
405 
406 static int
407 lock_agent(int agent_fd, int lock)
408 {
409 	char prompt[100], *p1, *p2;
410 	int r, passok = 1, ret = -1;
411 
412 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
413 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
414 	if (lock) {
415 		strlcpy(prompt, "Again: ", sizeof prompt);
416 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
417 		if (strcmp(p1, p2) != 0) {
418 			fprintf(stderr, "Passwords do not match.\n");
419 			passok = 0;
420 		}
421 		explicit_bzero(p2, strlen(p2));
422 		free(p2);
423 	}
424 	if (passok) {
425 		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
426 			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
427 			ret = 0;
428 		} else {
429 			fprintf(stderr, "Failed to %slock agent: %s\n",
430 			    lock ? "" : "un", ssh_err(r));
431 		}
432 	}
433 	explicit_bzero(p1, strlen(p1));
434 	free(p1);
435 	return (ret);
436 }
437 
438 static int
439 do_file(int agent_fd, int deleting, int key_only, char *file)
440 {
441 	if (deleting) {
442 		if (delete_file(agent_fd, file, key_only) == -1)
443 			return -1;
444 	} else {
445 		if (add_file(agent_fd, file, key_only) == -1)
446 			return -1;
447 	}
448 	return 0;
449 }
450 
451 static void
452 usage(void)
453 {
454 	fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
455 	fprintf(stderr, "Options:\n");
456 	fprintf(stderr, "  -l          List fingerprints of all identities.\n");
457 	fprintf(stderr, "  -E hash     Specify hash algorithm used for fingerprints.\n");
458 	fprintf(stderr, "  -L          List public key parameters of all identities.\n");
459 	fprintf(stderr, "  -k          Load only keys and not certificates.\n");
460 	fprintf(stderr, "  -c          Require confirmation to sign using identities\n");
461 	fprintf(stderr, "  -t life     Set lifetime (in seconds) when adding identities.\n");
462 	fprintf(stderr, "  -d          Delete identity.\n");
463 	fprintf(stderr, "  -D          Delete all identities.\n");
464 	fprintf(stderr, "  -x          Lock agent.\n");
465 	fprintf(stderr, "  -X          Unlock agent.\n");
466 	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
467 	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
468 }
469 
470 int
471 main(int argc, char **argv)
472 {
473 	extern char *optarg;
474 	extern int optind;
475 	int agent_fd;
476 	char *pkcs11provider = NULL;
477 	int r, i, ch, deleting = 0, ret = 0, key_only = 0;
478 	int xflag = 0, lflag = 0, Dflag = 0;
479 
480 	ssh_malloc_init();	/* must be called before any mallocs */
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