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