ssh-add.c revision 296781
1/* $OpenBSD: ssh-add.c,v 1.128 2016/02/15 09:47:49 dtucker 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
43#include <openssl/evp.h>
44#include "openbsd-compat/openssl-compat.h"
45
46#include <errno.h>
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#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 */
70extern char *__progname;
71
72/* Default files to add */
73static char *default_files[] = {
74#ifdef WITH_OPENSSL
75	_PATH_SSH_CLIENT_ID_RSA,
76	_PATH_SSH_CLIENT_ID_DSA,
77#ifdef OPENSSL_HAS_ECC
78	_PATH_SSH_CLIENT_ID_ECDSA,
79#endif
80#endif /* WITH_OPENSSL */
81	_PATH_SSH_CLIENT_ID_ED25519,
82#ifdef WITH_SSH1
83	_PATH_SSH_CLIENT_IDENTITY,
84#endif
85	NULL
86};
87
88static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
89
90/* Default lifetime (0 == forever) */
91static int lifetime = 0;
92
93/* User has to confirm key use */
94static int confirm = 0;
95
96/* we keep a cache of one passphrase */
97static char *pass = NULL;
98static void
99clear_pass(void)
100{
101	if (pass) {
102		explicit_bzero(pass, strlen(pass));
103		free(pass);
104		pass = NULL;
105	}
106}
107
108static int
109delete_file(int agent_fd, const char *filename, int key_only)
110{
111	struct sshkey *public, *cert = NULL;
112	char *certpath = NULL, *comment = NULL;
113	int r, ret = -1;
114
115	if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
116		printf("Bad key file %s: %s\n", filename, ssh_err(r));
117		return -1;
118	}
119	if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
120		fprintf(stderr, "Identity removed: %s (%s)\n", filename, comment);
121		ret = 0;
122	} else
123		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
124		    filename, ssh_err(r));
125
126	if (key_only)
127		goto out;
128
129	/* Now try to delete the corresponding certificate too */
130	free(comment);
131	comment = NULL;
132	xasprintf(&certpath, "%s-cert.pub", filename);
133	if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
134		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
135			error("Failed to load certificate \"%s\": %s",
136			    certpath, ssh_err(r));
137		goto out;
138	}
139
140	if (!sshkey_equal_public(cert, public))
141		fatal("Certificate %s does not match private key %s",
142		    certpath, filename);
143
144	if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
145		fprintf(stderr, "Identity removed: %s (%s)\n", certpath,
146		    comment);
147		ret = 0;
148	} else
149		fprintf(stderr, "Could not remove identity \"%s\": %s\n",
150		    certpath, ssh_err(r));
151
152 out:
153	sshkey_free(cert);
154	sshkey_free(public);
155	free(certpath);
156	free(comment);
157
158	return ret;
159}
160
161/* Send a request to remove all identities. */
162static int
163delete_all(int agent_fd)
164{
165	int ret = -1;
166
167	if (ssh_remove_all_identities(agent_fd, 2) == 0)
168		ret = 0;
169	/* ignore error-code for ssh1 */
170	ssh_remove_all_identities(agent_fd, 1);
171
172	if (ret == 0)
173		fprintf(stderr, "All identities removed.\n");
174	else
175		fprintf(stderr, "Failed to remove all identities.\n");
176
177	return ret;
178}
179
180static int
181add_file(int agent_fd, const char *filename, int key_only)
182{
183	struct sshkey *private, *cert;
184	char *comment = NULL;
185	char msg[1024], *certpath = NULL;
186	int r, fd, ret = -1;
187	struct sshbuf *keyblob;
188
189	if (strcmp(filename, "-") == 0) {
190		fd = STDIN_FILENO;
191		filename = "(stdin)";
192	} else if ((fd = open(filename, O_RDONLY)) < 0) {
193		perror(filename);
194		return -1;
195	}
196
197	/*
198	 * Since we'll try to load a keyfile multiple times, permission errors
199	 * will occur multiple times, so check perms first and bail if wrong.
200	 */
201	if (fd != STDIN_FILENO) {
202		if (sshkey_perm_ok(fd, filename) != 0) {
203			close(fd);
204			return -1;
205		}
206	}
207	if ((keyblob = sshbuf_new()) == NULL)
208		fatal("%s: sshbuf_new failed", __func__);
209	if ((r = sshkey_load_file(fd, keyblob)) != 0) {
210		fprintf(stderr, "Error loading key \"%s\": %s\n",
211		    filename, ssh_err(r));
212		sshbuf_free(keyblob);
213		close(fd);
214		return -1;
215	}
216	close(fd);
217
218	/* At first, try empty passphrase */
219	if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
220	    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
221		fprintf(stderr, "Error loading key \"%s\": %s\n",
222		    filename, ssh_err(r));
223		goto fail_load;
224	}
225	/* try last */
226	if (private == NULL && pass != NULL) {
227		if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
228		    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
229			fprintf(stderr, "Error loading key \"%s\": %s\n",
230			    filename, ssh_err(r));
231			goto fail_load;
232		}
233	}
234	if (private == NULL) {
235		/* clear passphrase since it did not work */
236		clear_pass();
237		snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
238		    filename, confirm ? " (will confirm each use)" : "");
239		for (;;) {
240			pass = read_passphrase(msg, RP_ALLOW_STDIN);
241			if (strcmp(pass, "") == 0)
242				goto fail_load;
243			if ((r = sshkey_parse_private_fileblob(keyblob, pass,
244			    &private, &comment)) == 0)
245				break;
246			else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
247				fprintf(stderr,
248				    "Error loading key \"%s\": %s\n",
249				    filename, ssh_err(r));
250 fail_load:
251				clear_pass();
252				sshbuf_free(keyblob);
253				return -1;
254			}
255			clear_pass();
256			snprintf(msg, sizeof msg,
257			    "Bad passphrase, try again for %s%s: ", filename,
258			    confirm ? " (will confirm each use)" : "");
259		}
260	}
261	if (comment == NULL || *comment == '\0')
262		comment = xstrdup(filename);
263	sshbuf_free(keyblob);
264
265	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
266	    lifetime, confirm)) == 0) {
267		fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
268		ret = 0;
269		if (lifetime != 0)
270			fprintf(stderr,
271			    "Lifetime set to %d seconds\n", lifetime);
272		if (confirm != 0)
273			fprintf(stderr,
274			    "The user must confirm each use of the key\n");
275	} else {
276		fprintf(stderr, "Could not add identity \"%s\": %s\n",
277		    filename, ssh_err(r));
278	}
279
280	/* Skip trying to load the cert if requested */
281	if (key_only)
282		goto out;
283
284	/* Now try to add the certificate flavour too */
285	xasprintf(&certpath, "%s-cert.pub", filename);
286	if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
287		if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
288			error("Failed to load certificate \"%s\": %s",
289			    certpath, ssh_err(r));
290		goto out;
291	}
292
293	if (!sshkey_equal_public(cert, private)) {
294		error("Certificate %s does not match private key %s",
295		    certpath, filename);
296		sshkey_free(cert);
297		goto out;
298	}
299
300	/* Graft with private bits */
301	if ((r = sshkey_to_certified(private)) != 0) {
302		error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
303		sshkey_free(cert);
304		goto out;
305	}
306	if ((r = sshkey_cert_copy(cert, private)) != 0) {
307		error("%s: key_cert_copy: %s", __func__, ssh_err(r));
308		sshkey_free(cert);
309		goto out;
310	}
311	sshkey_free(cert);
312
313	if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
314	    lifetime, confirm)) != 0) {
315		error("Certificate %s (%s) add failed: %s", certpath,
316		    private->cert->key_id, ssh_err(r));
317		goto out;
318	}
319	fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
320	    private->cert->key_id);
321	if (lifetime != 0)
322		fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
323	if (confirm != 0)
324		fprintf(stderr, "The user must confirm each use of the key\n");
325 out:
326	free(certpath);
327	free(comment);
328	sshkey_free(private);
329
330	return ret;
331}
332
333static int
334update_card(int agent_fd, int add, const char *id)
335{
336	char *pin = NULL;
337	int r, ret = -1;
338
339	if (add) {
340		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
341		    RP_ALLOW_STDIN)) == NULL)
342			return -1;
343	}
344
345	if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
346	    lifetime, confirm)) == 0) {
347		fprintf(stderr, "Card %s: %s\n",
348		    add ? "added" : "removed", id);
349		ret = 0;
350	} else {
351		fprintf(stderr, "Could not %s card \"%s\": %s\n",
352		    add ? "add" : "remove", id, ssh_err(r));
353		ret = -1;
354	}
355	free(pin);
356	return ret;
357}
358
359static int
360list_identities(int agent_fd, int do_fp)
361{
362	char *fp;
363	int r, had_identities = 0;
364	struct ssh_identitylist *idlist;
365	size_t i;
366#ifdef WITH_SSH1
367	int version = 1;
368#else
369	int version = 2;
370#endif
371
372	for (; version <= 2; version++) {
373		if ((r = ssh_fetch_identitylist(agent_fd, version,
374		    &idlist)) != 0) {
375			if (r != SSH_ERR_AGENT_NO_IDENTITIES)
376				fprintf(stderr, "error fetching identities for "
377				    "protocol %d: %s\n", version, ssh_err(r));
378			continue;
379		}
380		for (i = 0; i < idlist->nkeys; i++) {
381			had_identities = 1;
382			if (do_fp) {
383				fp = sshkey_fingerprint(idlist->keys[i],
384				    fingerprint_hash, SSH_FP_DEFAULT);
385				printf("%u %s %s (%s)\n",
386				    sshkey_size(idlist->keys[i]),
387				    fp == NULL ? "(null)" : fp,
388				    idlist->comments[i],
389				    sshkey_type(idlist->keys[i]));
390				free(fp);
391			} else {
392				if ((r = sshkey_write(idlist->keys[i],
393				    stdout)) != 0) {
394					fprintf(stderr, "sshkey_write: %s\n",
395					    ssh_err(r));
396					continue;
397				}
398				fprintf(stdout, " %s\n", idlist->comments[i]);
399			}
400		}
401		ssh_free_identitylist(idlist);
402	}
403	if (!had_identities) {
404		printf("The agent has no identities.\n");
405		return -1;
406	}
407	return 0;
408}
409
410static int
411lock_agent(int agent_fd, int lock)
412{
413	char prompt[100], *p1, *p2;
414	int r, passok = 1, ret = -1;
415
416	strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
417	p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
418	if (lock) {
419		strlcpy(prompt, "Again: ", sizeof prompt);
420		p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
421		if (strcmp(p1, p2) != 0) {
422			fprintf(stderr, "Passwords do not match.\n");
423			passok = 0;
424		}
425		explicit_bzero(p2, strlen(p2));
426		free(p2);
427	}
428	if (passok) {
429		if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
430			fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
431			ret = 0;
432		} else {
433			fprintf(stderr, "Failed to %slock agent: %s\n",
434			    lock ? "" : "un", ssh_err(r));
435		}
436	}
437	explicit_bzero(p1, strlen(p1));
438	free(p1);
439	return (ret);
440}
441
442static int
443do_file(int agent_fd, int deleting, int key_only, char *file)
444{
445	if (deleting) {
446		if (delete_file(agent_fd, file, key_only) == -1)
447			return -1;
448	} else {
449		if (add_file(agent_fd, file, key_only) == -1)
450			return -1;
451	}
452	return 0;
453}
454
455static void
456usage(void)
457{
458	fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
459	fprintf(stderr, "Options:\n");
460	fprintf(stderr, "  -l          List fingerprints of all identities.\n");
461	fprintf(stderr, "  -E hash     Specify hash algorithm used for fingerprints.\n");
462	fprintf(stderr, "  -L          List public key parameters of all identities.\n");
463	fprintf(stderr, "  -k          Load only keys and not certificates.\n");
464	fprintf(stderr, "  -c          Require confirmation to sign using identities\n");
465	fprintf(stderr, "  -t life     Set lifetime (in seconds) when adding identities.\n");
466	fprintf(stderr, "  -d          Delete identity.\n");
467	fprintf(stderr, "  -D          Delete all identities.\n");
468	fprintf(stderr, "  -x          Lock agent.\n");
469	fprintf(stderr, "  -X          Unlock agent.\n");
470	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
471	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
472}
473
474int
475main(int argc, char **argv)
476{
477	extern char *optarg;
478	extern int optind;
479	int agent_fd;
480	char *pkcs11provider = NULL;
481	int r, i, ch, deleting = 0, ret = 0, key_only = 0;
482	int xflag = 0, lflag = 0, Dflag = 0;
483
484	ssh_malloc_init();	/* must be called before any mallocs */
485	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
486	sanitise_stdfd();
487
488	__progname = ssh_get_progname(argv[0]);
489	seed_rng();
490
491#ifdef WITH_OPENSSL
492	OpenSSL_add_all_algorithms();
493#endif
494
495	setvbuf(stdout, NULL, _IOLBF, 0);
496
497	/* First, get a connection to the authentication agent. */
498	switch (r = ssh_get_authentication_socket(&agent_fd)) {
499	case 0:
500		break;
501	case SSH_ERR_AGENT_NOT_PRESENT:
502		fprintf(stderr, "Could not open a connection to your "
503		    "authentication agent.\n");
504		exit(2);
505	default:
506		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
507		exit(2);
508	}
509
510	while ((ch = getopt(argc, argv, "klLcdDxXE:e:s:t:")) != -1) {
511		switch (ch) {
512		case 'E':
513			fingerprint_hash = ssh_digest_alg_by_name(optarg);
514			if (fingerprint_hash == -1)
515				fatal("Invalid hash algorithm \"%s\"", optarg);
516			break;
517		case 'k':
518			key_only = 1;
519			break;
520		case 'l':
521		case 'L':
522			if (lflag != 0)
523				fatal("-%c flag already specified", lflag);
524			lflag = ch;
525			break;
526		case 'x':
527		case 'X':
528			if (xflag != 0)
529				fatal("-%c flag already specified", xflag);
530			xflag = ch;
531			break;
532		case 'c':
533			confirm = 1;
534			break;
535		case 'd':
536			deleting = 1;
537			break;
538		case 'D':
539			Dflag = 1;
540			break;
541		case 's':
542			pkcs11provider = optarg;
543			break;
544		case 'e':
545			deleting = 1;
546			pkcs11provider = optarg;
547			break;
548		case 't':
549			if ((lifetime = convtime(optarg)) == -1) {
550				fprintf(stderr, "Invalid lifetime\n");
551				ret = 1;
552				goto done;
553			}
554			break;
555		default:
556			usage();
557			ret = 1;
558			goto done;
559		}
560	}
561
562	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
563		fatal("Invalid combination of actions");
564	else if (xflag) {
565		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
566			ret = 1;
567		goto done;
568	} else if (lflag) {
569		if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
570			ret = 1;
571		goto done;
572	} else if (Dflag) {
573		if (delete_all(agent_fd) == -1)
574			ret = 1;
575		goto done;
576	}
577
578	argc -= optind;
579	argv += optind;
580	if (pkcs11provider != NULL) {
581		if (update_card(agent_fd, !deleting, pkcs11provider) == -1)
582			ret = 1;
583		goto done;
584	}
585	if (argc == 0) {
586		char buf[PATH_MAX];
587		struct passwd *pw;
588		struct stat st;
589		int count = 0;
590
591		if ((pw = getpwuid(getuid())) == NULL) {
592			fprintf(stderr, "No user found with uid %u\n",
593			    (u_int)getuid());
594			ret = 1;
595			goto done;
596		}
597
598		for (i = 0; default_files[i]; i++) {
599			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
600			    default_files[i]);
601			if (stat(buf, &st) < 0)
602				continue;
603			if (do_file(agent_fd, deleting, key_only, buf) == -1)
604				ret = 1;
605			else
606				count++;
607		}
608		if (count == 0)
609			ret = 1;
610	} else {
611		for (i = 0; i < argc; i++) {
612			if (do_file(agent_fd, deleting, key_only,
613			    argv[i]) == -1)
614				ret = 1;
615		}
616	}
617	clear_pass();
618
619done:
620	ssh_close_authentication_socket(agent_fd);
621	return ret;
622}
623