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