xref: /freebsd/crypto/openssh/ssh-add.c (revision 76b28ad6ab6dc8d4a62cb7de7f143595be535813)
1 /* $OpenBSD: ssh-add.c,v 1.109 2014/02/02 03:44:31 djm 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 "includes.h"
39 
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <sys/param.h>
43 
44 #include <openssl/evp.h>
45 #include "openbsd-compat/openssl-compat.h"
46 
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #include "xmalloc.h"
56 #include "ssh.h"
57 #include "rsa.h"
58 #include "log.h"
59 #include "key.h"
60 #include "buffer.h"
61 #include "authfd.h"
62 #include "authfile.h"
63 #include "pathnames.h"
64 #include "misc.h"
65 
66 /* argv0 */
67 extern char *__progname;
68 
69 /* Default files to add */
70 static char *default_files[] = {
71 	_PATH_SSH_CLIENT_ID_RSA,
72 	_PATH_SSH_CLIENT_ID_DSA,
73 #ifdef OPENSSL_HAS_ECC
74 	_PATH_SSH_CLIENT_ID_ECDSA,
75 #endif
76 	_PATH_SSH_CLIENT_ID_ED25519,
77 	_PATH_SSH_CLIENT_IDENTITY,
78 	NULL
79 };
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 passphrases */
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(AuthenticationConnection *ac, const char *filename, int key_only)
101 {
102 	Key *public = NULL, *cert = NULL;
103 	char *certpath = NULL, *comment = NULL;
104 	int ret = -1;
105 
106 	public = key_load_public(filename, &comment);
107 	if (public == NULL) {
108 		printf("Bad key file %s\n", filename);
109 		return -1;
110 	}
111 	if (ssh_remove_identity(ac, public)) {
112 		fprintf(stderr, "Identity removed: %s (%s)\n", filename, comment);
113 		ret = 0;
114 	} else
115 		fprintf(stderr, "Could not remove identity: %s\n", filename);
116 
117 	if (key_only)
118 		goto out;
119 
120 	/* Now try to delete the corresponding certificate too */
121 	free(comment);
122 	comment = NULL;
123 	xasprintf(&certpath, "%s-cert.pub", filename);
124 	if ((cert = key_load_public(certpath, &comment)) == NULL)
125 		goto out;
126 	if (!key_equal_public(cert, public))
127 		fatal("Certificate %s does not match private key %s",
128 		    certpath, filename);
129 
130 	if (ssh_remove_identity(ac, cert)) {
131 		fprintf(stderr, "Identity removed: %s (%s)\n", certpath,
132 		    comment);
133 		ret = 0;
134 	} else
135 		fprintf(stderr, "Could not remove identity: %s\n", certpath);
136 
137  out:
138 	if (cert != NULL)
139 		key_free(cert);
140 	if (public != NULL)
141 		key_free(public);
142 	free(certpath);
143 	free(comment);
144 
145 	return ret;
146 }
147 
148 /* Send a request to remove all identities. */
149 static int
150 delete_all(AuthenticationConnection *ac)
151 {
152 	int ret = -1;
153 
154 	if (ssh_remove_all_identities(ac, 1))
155 		ret = 0;
156 	/* ignore error-code for ssh2 */
157 	ssh_remove_all_identities(ac, 2);
158 
159 	if (ret == 0)
160 		fprintf(stderr, "All identities removed.\n");
161 	else
162 		fprintf(stderr, "Failed to remove all identities.\n");
163 
164 	return ret;
165 }
166 
167 static int
168 add_file(AuthenticationConnection *ac, const char *filename, int key_only)
169 {
170 	Key *private, *cert;
171 	char *comment = NULL;
172 	char msg[1024], *certpath = NULL;
173 	int fd, perms_ok, ret = -1;
174 	Buffer keyblob;
175 
176 	if (strcmp(filename, "-") == 0) {
177 		fd = STDIN_FILENO;
178 		filename = "(stdin)";
179 	} else if ((fd = open(filename, O_RDONLY)) < 0) {
180 		perror(filename);
181 		return -1;
182 	}
183 
184 	/*
185 	 * Since we'll try to load a keyfile multiple times, permission errors
186 	 * will occur multiple times, so check perms first and bail if wrong.
187 	 */
188 	if (fd != STDIN_FILENO) {
189 		perms_ok = key_perm_ok(fd, filename);
190 		if (!perms_ok) {
191 			close(fd);
192 			return -1;
193 		}
194 	}
195 	buffer_init(&keyblob);
196 	if (!key_load_file(fd, filename, &keyblob)) {
197 		buffer_free(&keyblob);
198 		close(fd);
199 		return -1;
200 	}
201 	close(fd);
202 
203 	/* At first, try empty passphrase */
204 	private = key_parse_private(&keyblob, filename, "", &comment);
205 	if (comment == NULL)
206 		comment = xstrdup(filename);
207 	/* try last */
208 	if (private == NULL && pass != NULL)
209 		private = key_parse_private(&keyblob, filename, pass, NULL);
210 	if (private == NULL) {
211 		/* clear passphrase since it did not work */
212 		clear_pass();
213 		snprintf(msg, sizeof msg, "Enter passphrase for %.200s: ",
214 		    comment);
215 		for (;;) {
216 			pass = read_passphrase(msg, RP_ALLOW_STDIN);
217 			if (strcmp(pass, "") == 0) {
218 				clear_pass();
219 				free(comment);
220 				buffer_free(&keyblob);
221 				return -1;
222 			}
223 			private = key_parse_private(&keyblob, filename, pass,
224 			    &comment);
225 			if (private != NULL)
226 				break;
227 			clear_pass();
228 			snprintf(msg, sizeof msg,
229 			    "Bad passphrase, try again for %.200s: ", comment);
230 		}
231 	}
232 	buffer_free(&keyblob);
233 
234 	if (ssh_add_identity_constrained(ac, private, comment, lifetime,
235 	    confirm)) {
236 		fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
237 		ret = 0;
238 		if (lifetime != 0)
239 			fprintf(stderr,
240 			    "Lifetime set to %d seconds\n", lifetime);
241 		if (confirm != 0)
242 			fprintf(stderr,
243 			    "The user must confirm each use of the key\n");
244 	} else {
245 		fprintf(stderr, "Could not add identity: %s\n", filename);
246 	}
247 
248 	/* Skip trying to load the cert if requested */
249 	if (key_only)
250 		goto out;
251 
252 	/* Now try to add the certificate flavour too */
253 	xasprintf(&certpath, "%s-cert.pub", filename);
254 	if ((cert = key_load_public(certpath, NULL)) == NULL)
255 		goto out;
256 
257 	if (!key_equal_public(cert, private)) {
258 		error("Certificate %s does not match private key %s",
259 		    certpath, filename);
260 		key_free(cert);
261 		goto out;
262 	}
263 
264 	/* Graft with private bits */
265 	if (key_to_certified(private, key_cert_is_legacy(cert)) != 0) {
266 		error("%s: key_to_certified failed", __func__);
267 		key_free(cert);
268 		goto out;
269 	}
270 	key_cert_copy(cert, private);
271 	key_free(cert);
272 
273 	if (!ssh_add_identity_constrained(ac, private, comment,
274 	    lifetime, confirm)) {
275 		error("Certificate %s (%s) add failed", certpath,
276 		    private->cert->key_id);
277 	}
278 	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
279 	    private->cert->key_id);
280 	if (lifetime != 0)
281 		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
282 	if (confirm != 0)
283 		fprintf(stderr, "The user must confirm each use of the key\n");
284  out:
285 	if (certpath != NULL)
286 		free(certpath);
287 	free(comment);
288 	key_free(private);
289 
290 	return ret;
291 }
292 
293 static int
294 update_card(AuthenticationConnection *ac, int add, const char *id)
295 {
296 	char *pin = NULL;
297 	int ret = -1;
298 
299 	if (add) {
300 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
301 		    RP_ALLOW_STDIN)) == NULL)
302 			return -1;
303 	}
304 
305 	if (ssh_update_card(ac, add, id, pin == NULL ? "" : pin,
306 	    lifetime, confirm)) {
307 		fprintf(stderr, "Card %s: %s\n",
308 		    add ? "added" : "removed", id);
309 		ret = 0;
310 	} else {
311 		fprintf(stderr, "Could not %s card: %s\n",
312 		    add ? "add" : "remove", id);
313 		ret = -1;
314 	}
315 	free(pin);
316 	return ret;
317 }
318 
319 static int
320 list_identities(AuthenticationConnection *ac, int do_fp)
321 {
322 	Key *key;
323 	char *comment, *fp;
324 	int had_identities = 0;
325 	int version;
326 
327 	for (version = 1; version <= 2; version++) {
328 		for (key = ssh_get_first_identity(ac, &comment, version);
329 		    key != NULL;
330 		    key = ssh_get_next_identity(ac, &comment, version)) {
331 			had_identities = 1;
332 			if (do_fp) {
333 				fp = key_fingerprint(key, SSH_FP_MD5,
334 				    SSH_FP_HEX);
335 				printf("%d %s %s (%s)\n",
336 				    key_size(key), fp, comment, key_type(key));
337 				free(fp);
338 			} else {
339 				if (!key_write(key, stdout))
340 					fprintf(stderr, "key_write failed");
341 				fprintf(stdout, " %s\n", comment);
342 			}
343 			key_free(key);
344 			free(comment);
345 		}
346 	}
347 	if (!had_identities) {
348 		printf("The agent has no identities.\n");
349 		return -1;
350 	}
351 	return 0;
352 }
353 
354 static int
355 lock_agent(AuthenticationConnection *ac, int lock)
356 {
357 	char prompt[100], *p1, *p2;
358 	int passok = 1, ret = -1;
359 
360 	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
361 	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
362 	if (lock) {
363 		strlcpy(prompt, "Again: ", sizeof prompt);
364 		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
365 		if (strcmp(p1, p2) != 0) {
366 			fprintf(stderr, "Passwords do not match.\n");
367 			passok = 0;
368 		}
369 		explicit_bzero(p2, strlen(p2));
370 		free(p2);
371 	}
372 	if (passok && ssh_lock_agent(ac, lock, p1)) {
373 		fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
374 		ret = 0;
375 	} else
376 		fprintf(stderr, "Failed to %slock agent.\n", lock ? "" : "un");
377 	explicit_bzero(p1, strlen(p1));
378 	free(p1);
379 	return (ret);
380 }
381 
382 static int
383 do_file(AuthenticationConnection *ac, int deleting, int key_only, char *file)
384 {
385 	if (deleting) {
386 		if (delete_file(ac, file, key_only) == -1)
387 			return -1;
388 	} else {
389 		if (add_file(ac, file, key_only) == -1)
390 			return -1;
391 	}
392 	return 0;
393 }
394 
395 static void
396 usage(void)
397 {
398 	fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
399 	fprintf(stderr, "Options:\n");
400 	fprintf(stderr, "  -l          List fingerprints of all identities.\n");
401 	fprintf(stderr, "  -L          List public key parameters of all identities.\n");
402 	fprintf(stderr, "  -k          Load only keys and not certificates.\n");
403 	fprintf(stderr, "  -c          Require confirmation to sign using identities\n");
404 	fprintf(stderr, "  -t life     Set lifetime (in seconds) when adding identities.\n");
405 	fprintf(stderr, "  -d          Delete identity.\n");
406 	fprintf(stderr, "  -D          Delete all identities.\n");
407 	fprintf(stderr, "  -x          Lock agent.\n");
408 	fprintf(stderr, "  -X          Unlock agent.\n");
409 	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
410 	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
411 }
412 
413 int
414 main(int argc, char **argv)
415 {
416 	extern char *optarg;
417 	extern int optind;
418 	AuthenticationConnection *ac = NULL;
419 	char *pkcs11provider = NULL;
420 	int i, ch, deleting = 0, ret = 0, key_only = 0;
421 
422 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
423 	sanitise_stdfd();
424 
425 	__progname = ssh_get_progname(argv[0]);
426 	seed_rng();
427 
428 	OpenSSL_add_all_algorithms();
429 
430 	/* At first, get a connection to the authentication agent. */
431 	ac = ssh_get_authentication_connection();
432 	if (ac == NULL) {
433 		fprintf(stderr,
434 		    "Could not open a connection to your authentication agent.\n");
435 		exit(2);
436 	}
437 	while ((ch = getopt(argc, argv, "klLcdDxXe:s:t:")) != -1) {
438 		switch (ch) {
439 		case 'k':
440 			key_only = 1;
441 			break;
442 		case 'l':
443 		case 'L':
444 			if (list_identities(ac, ch == 'l' ? 1 : 0) == -1)
445 				ret = 1;
446 			goto done;
447 		case 'x':
448 		case 'X':
449 			if (lock_agent(ac, ch == 'x' ? 1 : 0) == -1)
450 				ret = 1;
451 			goto done;
452 		case 'c':
453 			confirm = 1;
454 			break;
455 		case 'd':
456 			deleting = 1;
457 			break;
458 		case 'D':
459 			if (delete_all(ac) == -1)
460 				ret = 1;
461 			goto done;
462 		case 's':
463 			pkcs11provider = optarg;
464 			break;
465 		case 'e':
466 			deleting = 1;
467 			pkcs11provider = optarg;
468 			break;
469 		case 't':
470 			if ((lifetime = convtime(optarg)) == -1) {
471 				fprintf(stderr, "Invalid lifetime\n");
472 				ret = 1;
473 				goto done;
474 			}
475 			break;
476 		default:
477 			usage();
478 			ret = 1;
479 			goto done;
480 		}
481 	}
482 	argc -= optind;
483 	argv += optind;
484 	if (pkcs11provider != NULL) {
485 		if (update_card(ac, !deleting, pkcs11provider) == -1)
486 			ret = 1;
487 		goto done;
488 	}
489 	if (argc == 0) {
490 		char buf[MAXPATHLEN];
491 		struct passwd *pw;
492 		struct stat st;
493 		int count = 0;
494 
495 		if ((pw = getpwuid(getuid())) == NULL) {
496 			fprintf(stderr, "No user found with uid %u\n",
497 			    (u_int)getuid());
498 			ret = 1;
499 			goto done;
500 		}
501 
502 		for (i = 0; default_files[i]; i++) {
503 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
504 			    default_files[i]);
505 			if (stat(buf, &st) < 0)
506 				continue;
507 			if (do_file(ac, deleting, key_only, buf) == -1)
508 				ret = 1;
509 			else
510 				count++;
511 		}
512 		if (count == 0)
513 			ret = 1;
514 	} else {
515 		for (i = 0; i < argc; i++) {
516 			if (do_file(ac, deleting, key_only, argv[i]) == -1)
517 				ret = 1;
518 		}
519 	}
520 	clear_pass();
521 
522 done:
523 	ssh_close_authentication_connection(ac);
524 	return ret;
525 }
526