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