xref: /openssh-portable/ssh-agent.c (revision 0c111eb8)
1 /* $OpenBSD: ssh-agent.c,v 1.258 2020/05/26 01:26:58 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  * The authentication agent program.
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  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 #include "includes.h"
38 
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43 #include <sys/socket.h>
44 #include <sys/wait.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_UN_H
49 # include <sys/un.h>
50 #endif
51 #include "openbsd-compat/sys-queue.h"
52 
53 #ifdef WITH_OPENSSL
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
56 #endif
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <limits.h>
61 #ifdef HAVE_PATHS_H
62 # include <paths.h>
63 #endif
64 #ifdef HAVE_POLL_H
65 # include <poll.h>
66 #endif
67 #include <signal.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <time.h>
72 #include <string.h>
73 #include <unistd.h>
74 #ifdef HAVE_UTIL_H
75 # include <util.h>
76 #endif
77 
78 #include "xmalloc.h"
79 #include "ssh.h"
80 #include "ssh2.h"
81 #include "sshbuf.h"
82 #include "sshkey.h"
83 #include "authfd.h"
84 #include "compat.h"
85 #include "log.h"
86 #include "misc.h"
87 #include "digest.h"
88 #include "ssherr.h"
89 #include "match.h"
90 #include "msg.h"
91 #include "ssherr.h"
92 #include "pathnames.h"
93 #include "ssh-pkcs11.h"
94 #include "sk-api.h"
95 
96 #ifndef DEFAULT_PROVIDER_WHITELIST
97 # define DEFAULT_PROVIDER_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
98 #endif
99 
100 /* Maximum accepted message length */
101 #define AGENT_MAX_LEN	(256*1024)
102 /* Maximum bytes to read from client socket */
103 #define AGENT_RBUF_LEN	(4096)
104 
105 typedef enum {
106 	AUTH_UNUSED,
107 	AUTH_SOCKET,
108 	AUTH_CONNECTION
109 } sock_type;
110 
111 typedef struct {
112 	int fd;
113 	sock_type type;
114 	struct sshbuf *input;
115 	struct sshbuf *output;
116 	struct sshbuf *request;
117 } SocketEntry;
118 
119 u_int sockets_alloc = 0;
120 SocketEntry *sockets = NULL;
121 
122 typedef struct identity {
123 	TAILQ_ENTRY(identity) next;
124 	struct sshkey *key;
125 	char *comment;
126 	char *provider;
127 	time_t death;
128 	u_int confirm;
129 	char *sk_provider;
130 } Identity;
131 
132 struct idtable {
133 	int nentries;
134 	TAILQ_HEAD(idqueue, identity) idlist;
135 };
136 
137 /* private key table */
138 struct idtable *idtab;
139 
140 int max_fd = 0;
141 
142 /* pid of shell == parent of agent */
143 pid_t parent_pid = -1;
144 time_t parent_alive_interval = 0;
145 
146 /* pid of process for which cleanup_socket is applicable */
147 pid_t cleanup_pid = 0;
148 
149 /* pathname and directory for AUTH_SOCKET */
150 char socket_name[PATH_MAX];
151 char socket_dir[PATH_MAX];
152 
153 /* PKCS#11/Security key path whitelist */
154 static char *provider_whitelist;
155 
156 /* locking */
157 #define LOCK_SIZE	32
158 #define LOCK_SALT_SIZE	16
159 #define LOCK_ROUNDS	1
160 int locked = 0;
161 u_char lock_pwhash[LOCK_SIZE];
162 u_char lock_salt[LOCK_SALT_SIZE];
163 
164 extern char *__progname;
165 
166 /* Default lifetime in seconds (0 == forever) */
167 static long lifetime = 0;
168 
169 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
170 
171 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
172 static int restrict_websafe = 1;
173 
174 static void
close_socket(SocketEntry * e)175 close_socket(SocketEntry *e)
176 {
177 	close(e->fd);
178 	e->fd = -1;
179 	e->type = AUTH_UNUSED;
180 	sshbuf_free(e->input);
181 	sshbuf_free(e->output);
182 	sshbuf_free(e->request);
183 }
184 
185 static void
idtab_init(void)186 idtab_init(void)
187 {
188 	idtab = xcalloc(1, sizeof(*idtab));
189 	TAILQ_INIT(&idtab->idlist);
190 	idtab->nentries = 0;
191 }
192 
193 static void
free_identity(Identity * id)194 free_identity(Identity *id)
195 {
196 	sshkey_free(id->key);
197 	free(id->provider);
198 	free(id->comment);
199 	free(id->sk_provider);
200 	free(id);
201 }
202 
203 /* return matching private key for given public key */
204 static Identity *
lookup_identity(struct sshkey * key)205 lookup_identity(struct sshkey *key)
206 {
207 	Identity *id;
208 
209 	TAILQ_FOREACH(id, &idtab->idlist, next) {
210 		if (sshkey_equal(key, id->key))
211 			return (id);
212 	}
213 	return (NULL);
214 }
215 
216 /* Check confirmation of keysign request */
217 static int
confirm_key(Identity * id)218 confirm_key(Identity *id)
219 {
220 	char *p;
221 	int ret = -1;
222 
223 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
224 	if (p != NULL &&
225 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.",
226 	    id->comment, p))
227 		ret = 0;
228 	free(p);
229 
230 	return (ret);
231 }
232 
233 static void
send_status(SocketEntry * e,int success)234 send_status(SocketEntry *e, int success)
235 {
236 	int r;
237 
238 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
239 	    (r = sshbuf_put_u8(e->output, success ?
240 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
241 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
242 }
243 
244 /* send list of supported public keys to 'client' */
245 static void
process_request_identities(SocketEntry * e)246 process_request_identities(SocketEntry *e)
247 {
248 	Identity *id;
249 	struct sshbuf *msg;
250 	int r;
251 
252 	if ((msg = sshbuf_new()) == NULL)
253 		fatal("%s: sshbuf_new failed", __func__);
254 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
255 	    (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
256 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
257 	TAILQ_FOREACH(id, &idtab->idlist, next) {
258 		if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
259 		     != 0 ||
260 		    (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
261 			error("%s: put key/comment: %s", __func__,
262 			    ssh_err(r));
263 			continue;
264 		}
265 	}
266 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
267 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
268 	sshbuf_free(msg);
269 }
270 
271 
272 static char *
agent_decode_alg(struct sshkey * key,u_int flags)273 agent_decode_alg(struct sshkey *key, u_int flags)
274 {
275 	if (key->type == KEY_RSA) {
276 		if (flags & SSH_AGENT_RSA_SHA2_256)
277 			return "rsa-sha2-256";
278 		else if (flags & SSH_AGENT_RSA_SHA2_512)
279 			return "rsa-sha2-512";
280 	} else if (key->type == KEY_RSA_CERT) {
281 		if (flags & SSH_AGENT_RSA_SHA2_256)
282 			return "rsa-sha2-256-cert-v01@openssh.com";
283 		else if (flags & SSH_AGENT_RSA_SHA2_512)
284 			return "rsa-sha2-512-cert-v01@openssh.com";
285 	}
286 	return NULL;
287 }
288 
289 /*
290  * This function inspects a message to be signed by a FIDO key that has a
291  * web-like application string (i.e. one that does not begin with "ssh:".
292  * It checks that the message is one of those expected for SSH operations
293  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
294  * for the web.
295  */
296 static int
check_websafe_message_contents(struct sshkey * key,const u_char * msg,size_t len)297 check_websafe_message_contents(struct sshkey *key,
298     const u_char *msg, size_t len)
299 {
300 	int matched = 0;
301 	struct sshbuf *b;
302 	u_char m, n;
303 	char *cp1 = NULL, *cp2 = NULL;
304 	int r;
305 	struct sshkey *mkey = NULL;
306 
307 	if ((b = sshbuf_from(msg, len)) == NULL)
308 		fatal("%s: sshbuf_new", __func__);
309 
310 	/* SSH userauth request */
311 	if ((r = sshbuf_get_string_direct(b, NULL, NULL)) == 0 && /* sess_id */
312 	    (r = sshbuf_get_u8(b, &m)) == 0 && /* SSH2_MSG_USERAUTH_REQUEST */
313 	    (r = sshbuf_get_cstring(b, NULL, NULL)) == 0 && /* server user */
314 	    (r = sshbuf_get_cstring(b, &cp1, NULL)) == 0 && /* service */
315 	    (r = sshbuf_get_cstring(b, &cp2, NULL)) == 0 && /* method */
316 	    (r = sshbuf_get_u8(b, &n)) == 0 && /* sig-follows */
317 	    (r = sshbuf_get_cstring(b, NULL, NULL)) == 0 && /* alg */
318 	    (r = sshkey_froms(b, &mkey)) == 0 && /* key */
319 	    sshbuf_len(b) == 0) {
320 		debug("%s: parsed userauth", __func__);
321 		if (m == SSH2_MSG_USERAUTH_REQUEST && n == 1 &&
322 		    strcmp(cp1, "ssh-connection") == 0 &&
323 		    strcmp(cp2, "publickey") == 0 &&
324 		    sshkey_equal(key, mkey)) {
325 			debug("%s: well formed userauth", __func__);
326 			matched = 1;
327 		}
328 	}
329 	free(cp1);
330 	free(cp2);
331 	sshkey_free(mkey);
332 	sshbuf_free(b);
333 	if (matched)
334 		return 1;
335 
336 	if ((b = sshbuf_from(msg, len)) == NULL)
337 		fatal("%s: sshbuf_new", __func__);
338 	cp1 = cp2 = NULL;
339 	mkey = NULL;
340 
341 	/* SSHSIG */
342 	if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) == 0 &&
343 	    (r = sshbuf_consume(b, 6)) == 0 &&
344 	    (r = sshbuf_get_cstring(b, NULL, NULL)) == 0 && /* namespace */
345 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) == 0 && /* reserved */
346 	    (r = sshbuf_get_cstring(b, NULL, NULL)) == 0 && /* hashalg */
347 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) == 0 && /* H(msg) */
348 	    sshbuf_len(b) == 0) {
349 		debug("%s: parsed sshsig", __func__);
350 		matched = 1;
351 	}
352 
353 	sshbuf_free(b);
354 	if (matched)
355 		return 1;
356 
357 	/* XXX CA signature operation */
358 
359 	error("web-origin key attempting to sign non-SSH message");
360 	return 0;
361 }
362 
363 /* ssh2 only */
364 static void
process_sign_request2(SocketEntry * e)365 process_sign_request2(SocketEntry *e)
366 {
367 	const u_char *data;
368 	u_char *signature = NULL;
369 	size_t dlen, slen = 0;
370 	u_int compat = 0, flags;
371 	int r, ok = -1;
372 	char *fp = NULL;
373 	struct sshbuf *msg;
374 	struct sshkey *key = NULL;
375 	struct identity *id;
376 	struct notifier_ctx *notifier = NULL;
377 
378 	if ((msg = sshbuf_new()) == NULL)
379 		fatal("%s: sshbuf_new failed", __func__);
380 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
381 	    (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
382 	    (r = sshbuf_get_u32(e->request, &flags)) != 0) {
383 		error("%s: couldn't parse request: %s", __func__, ssh_err(r));
384 		goto send;
385 	}
386 
387 	if ((id = lookup_identity(key)) == NULL) {
388 		verbose("%s: %s key not found", __func__, sshkey_type(key));
389 		goto send;
390 	}
391 	if (id->confirm && confirm_key(id) != 0) {
392 		verbose("%s: user refused key", __func__);
393 		goto send;
394 	}
395 	if (sshkey_is_sk(id->key)) {
396 		if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
397 		    !check_websafe_message_contents(key, data, dlen)) {
398 			/* error already logged */
399 			goto send;
400 		}
401 		if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
402 			if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
403 			    SSH_FP_DEFAULT)) == NULL)
404 				fatal("%s: fingerprint failed", __func__);
405 			notifier = notify_start(0,
406 			    "Confirm user presence for key %s %s",
407 			    sshkey_type(id->key), fp);
408 		}
409 	}
410 	if ((r = sshkey_sign(id->key, &signature, &slen,
411 	    data, dlen, agent_decode_alg(key, flags),
412 	    id->sk_provider, compat)) != 0) {
413 		error("%s: sshkey_sign: %s", __func__, ssh_err(r));
414 		goto send;
415 	}
416 	/* Success */
417 	ok = 0;
418  send:
419 	notify_complete(notifier);
420 	sshkey_free(key);
421 	free(fp);
422 	if (ok == 0) {
423 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
424 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
425 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
426 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
427 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
428 
429 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
430 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
431 
432 	sshbuf_free(msg);
433 	free(signature);
434 }
435 
436 /* shared */
437 static void
process_remove_identity(SocketEntry * e)438 process_remove_identity(SocketEntry *e)
439 {
440 	int r, success = 0;
441 	struct sshkey *key = NULL;
442 	Identity *id;
443 
444 	if ((r = sshkey_froms(e->request, &key)) != 0) {
445 		error("%s: get key: %s", __func__, ssh_err(r));
446 		goto done;
447 	}
448 	if ((id = lookup_identity(key)) == NULL) {
449 		debug("%s: key not found", __func__);
450 		goto done;
451 	}
452 	/* We have this key, free it. */
453 	if (idtab->nentries < 1)
454 		fatal("%s: internal error: nentries %d",
455 		    __func__, idtab->nentries);
456 	TAILQ_REMOVE(&idtab->idlist, id, next);
457 	free_identity(id);
458 	idtab->nentries--;
459 	sshkey_free(key);
460 	success = 1;
461  done:
462 	send_status(e, success);
463 }
464 
465 static void
process_remove_all_identities(SocketEntry * e)466 process_remove_all_identities(SocketEntry *e)
467 {
468 	Identity *id;
469 
470 	/* Loop over all identities and clear the keys. */
471 	for (id = TAILQ_FIRST(&idtab->idlist); id;
472 	    id = TAILQ_FIRST(&idtab->idlist)) {
473 		TAILQ_REMOVE(&idtab->idlist, id, next);
474 		free_identity(id);
475 	}
476 
477 	/* Mark that there are no identities. */
478 	idtab->nentries = 0;
479 
480 	/* Send success. */
481 	send_status(e, 1);
482 }
483 
484 /* removes expired keys and returns number of seconds until the next expiry */
485 static time_t
reaper(void)486 reaper(void)
487 {
488 	time_t deadline = 0, now = monotime();
489 	Identity *id, *nxt;
490 
491 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
492 		nxt = TAILQ_NEXT(id, next);
493 		if (id->death == 0)
494 			continue;
495 		if (now >= id->death) {
496 			debug("expiring key '%s'", id->comment);
497 			TAILQ_REMOVE(&idtab->idlist, id, next);
498 			free_identity(id);
499 			idtab->nentries--;
500 		} else
501 			deadline = (deadline == 0) ? id->death :
502 			    MINIMUM(deadline, id->death);
503 	}
504 	if (deadline == 0 || deadline <= now)
505 		return 0;
506 	else
507 		return (deadline - now);
508 }
509 
510 static void
process_add_identity(SocketEntry * e)511 process_add_identity(SocketEntry *e)
512 {
513 	Identity *id;
514 	int success = 0, confirm = 0;
515 	u_int seconds = 0, maxsign;
516 	char *fp, *comment = NULL, *ext_name = NULL, *sk_provider = NULL;
517 	char canonical_provider[PATH_MAX];
518 	time_t death = 0;
519 	struct sshkey *k = NULL;
520 	u_char ctype;
521 	int r = SSH_ERR_INTERNAL_ERROR;
522 
523 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
524 	    k == NULL ||
525 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
526 		error("%s: decode private key: %s", __func__, ssh_err(r));
527 		goto err;
528 	}
529 	while (sshbuf_len(e->request)) {
530 		if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
531 			error("%s: buffer error: %s", __func__, ssh_err(r));
532 			goto err;
533 		}
534 		switch (ctype) {
535 		case SSH_AGENT_CONSTRAIN_LIFETIME:
536 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
537 				error("%s: bad lifetime constraint: %s",
538 				    __func__, ssh_err(r));
539 				goto err;
540 			}
541 			death = monotime() + seconds;
542 			break;
543 		case SSH_AGENT_CONSTRAIN_CONFIRM:
544 			confirm = 1;
545 			break;
546 		case SSH_AGENT_CONSTRAIN_MAXSIGN:
547 			if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
548 				error("%s: bad maxsign constraint: %s",
549 				    __func__, ssh_err(r));
550 				goto err;
551 			}
552 			if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
553 				error("%s: cannot enable maxsign: %s",
554 				    __func__, ssh_err(r));
555 				goto err;
556 			}
557 			break;
558 		case SSH_AGENT_CONSTRAIN_EXTENSION:
559 			if ((r = sshbuf_get_cstring(e->request,
560 			    &ext_name, NULL)) != 0) {
561 				error("%s: cannot parse extension: %s",
562 				    __func__, ssh_err(r));
563 				goto err;
564 			}
565 			debug("%s: constraint ext %s", __func__, ext_name);
566 			if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
567 				if (sk_provider != NULL) {
568 					error("%s already set", ext_name);
569 					goto err;
570 				}
571 				if ((r = sshbuf_get_cstring(e->request,
572 				    &sk_provider, NULL)) != 0) {
573 					error("%s: cannot parse %s: %s",
574 					    __func__, ext_name, ssh_err(r));
575 					goto err;
576 				}
577 			} else {
578 				error("%s: unsupported constraint \"%s\"",
579 				    __func__, ext_name);
580 				goto err;
581 			}
582 			free(ext_name);
583 			break;
584 		default:
585 			error("%s: Unknown constraint %d", __func__, ctype);
586  err:
587 			free(sk_provider);
588 			free(ext_name);
589 			sshbuf_reset(e->request);
590 			free(comment);
591 			sshkey_free(k);
592 			goto send;
593 		}
594 	}
595 	if (sk_provider != NULL) {
596 		if (!sshkey_is_sk(k)) {
597 			error("Cannot add provider: %s is not an "
598 			    "authenticator-hosted key", sshkey_type(k));
599 			free(sk_provider);
600 			goto send;
601 		}
602 		if (strcasecmp(sk_provider, "internal") == 0) {
603 			debug("%s: internal provider", __func__);
604 		} else {
605 			if (realpath(sk_provider, canonical_provider) == NULL) {
606 				verbose("failed provider \"%.100s\": "
607 				    "realpath: %s", sk_provider,
608 				    strerror(errno));
609 				free(sk_provider);
610 				goto send;
611 			}
612 			free(sk_provider);
613 			sk_provider = xstrdup(canonical_provider);
614 			if (match_pattern_list(sk_provider,
615 			    provider_whitelist, 0) != 1) {
616 				error("Refusing add key: "
617 				    "provider %s not whitelisted", sk_provider);
618 				free(sk_provider);
619 				goto send;
620 			}
621 		}
622 	}
623 	if ((r = sshkey_shield_private(k)) != 0) {
624 		error("%s: shield private key: %s", __func__, ssh_err(r));
625 		goto err;
626 	}
627 
628 	success = 1;
629 	if (lifetime && !death)
630 		death = monotime() + lifetime;
631 	if ((id = lookup_identity(k)) == NULL) {
632 		id = xcalloc(1, sizeof(Identity));
633 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
634 		/* Increment the number of identities. */
635 		idtab->nentries++;
636 	} else {
637 		/* key state might have been updated */
638 		sshkey_free(id->key);
639 		free(id->comment);
640 		free(id->sk_provider);
641 	}
642 	id->key = k;
643 	id->comment = comment;
644 	id->death = death;
645 	id->confirm = confirm;
646 	id->sk_provider = sk_provider;
647 
648 	if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
649 	    SSH_FP_DEFAULT)) == NULL)
650 		fatal("%s: sshkey_fingerprint failed", __func__);
651 	debug("%s: add %s %s \"%.100s\" (life: %u) (confirm: %u) "
652 	    "(provider: %s)", __func__, sshkey_ssh_name(k), fp, comment,
653 	    seconds, confirm, sk_provider == NULL ? "none" : sk_provider);
654 	free(fp);
655 send:
656 	send_status(e, success);
657 }
658 
659 /* XXX todo: encrypt sensitive data with passphrase */
660 static void
process_lock_agent(SocketEntry * e,int lock)661 process_lock_agent(SocketEntry *e, int lock)
662 {
663 	int r, success = 0, delay;
664 	char *passwd;
665 	u_char passwdhash[LOCK_SIZE];
666 	static u_int fail_count = 0;
667 	size_t pwlen;
668 
669 	/*
670 	 * This is deliberately fatal: the user has requested that we lock,
671 	 * but we can't parse their request properly. The only safe thing to
672 	 * do is abort.
673 	 */
674 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
675 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
676 	if (pwlen == 0) {
677 		debug("empty password not supported");
678 	} else if (locked && !lock) {
679 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
680 		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
681 			fatal("bcrypt_pbkdf");
682 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
683 			debug("agent unlocked");
684 			locked = 0;
685 			fail_count = 0;
686 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
687 			success = 1;
688 		} else {
689 			/* delay in 0.1s increments up to 10s */
690 			if (fail_count < 100)
691 				fail_count++;
692 			delay = 100000 * fail_count;
693 			debug("unlock failed, delaying %0.1lf seconds",
694 			    (double)delay/1000000);
695 			usleep(delay);
696 		}
697 		explicit_bzero(passwdhash, sizeof(passwdhash));
698 	} else if (!locked && lock) {
699 		debug("agent locked");
700 		locked = 1;
701 		arc4random_buf(lock_salt, sizeof(lock_salt));
702 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
703 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
704 			fatal("bcrypt_pbkdf");
705 		success = 1;
706 	}
707 	freezero(passwd, pwlen);
708 	send_status(e, success);
709 }
710 
711 static void
no_identities(SocketEntry * e)712 no_identities(SocketEntry *e)
713 {
714 	struct sshbuf *msg;
715 	int r;
716 
717 	if ((msg = sshbuf_new()) == NULL)
718 		fatal("%s: sshbuf_new failed", __func__);
719 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
720 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
721 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
722 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
723 	sshbuf_free(msg);
724 }
725 
726 #ifdef ENABLE_PKCS11
727 static void
process_add_smartcard_key(SocketEntry * e)728 process_add_smartcard_key(SocketEntry *e)
729 {
730 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
731 	char **comments = NULL;
732 	int r, i, count = 0, success = 0, confirm = 0;
733 	u_int seconds;
734 	time_t death = 0;
735 	u_char type;
736 	struct sshkey **keys = NULL, *k;
737 	Identity *id;
738 
739 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
740 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
741 		error("%s: buffer error: %s", __func__, ssh_err(r));
742 		goto send;
743 	}
744 
745 	while (sshbuf_len(e->request)) {
746 		if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
747 			error("%s: buffer error: %s", __func__, ssh_err(r));
748 			goto send;
749 		}
750 		switch (type) {
751 		case SSH_AGENT_CONSTRAIN_LIFETIME:
752 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
753 				error("%s: buffer error: %s",
754 				    __func__, ssh_err(r));
755 				goto send;
756 			}
757 			death = monotime() + seconds;
758 			break;
759 		case SSH_AGENT_CONSTRAIN_CONFIRM:
760 			confirm = 1;
761 			break;
762 		default:
763 			error("%s: Unknown constraint type %d", __func__, type);
764 			goto send;
765 		}
766 	}
767 	if (realpath(provider, canonical_provider) == NULL) {
768 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
769 		    provider, strerror(errno));
770 		goto send;
771 	}
772 	if (match_pattern_list(canonical_provider, provider_whitelist, 0) != 1) {
773 		verbose("refusing PKCS#11 add of \"%.100s\": "
774 		    "provider not whitelisted", canonical_provider);
775 		goto send;
776 	}
777 	debug("%s: add %.100s", __func__, canonical_provider);
778 	if (lifetime && !death)
779 		death = monotime() + lifetime;
780 
781 	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
782 	for (i = 0; i < count; i++) {
783 		k = keys[i];
784 		if (lookup_identity(k) == NULL) {
785 			id = xcalloc(1, sizeof(Identity));
786 			id->key = k;
787 			keys[i] = NULL; /* transferred */
788 			id->provider = xstrdup(canonical_provider);
789 			if (*comments[i] != '\0') {
790 				id->comment = comments[i];
791 				comments[i] = NULL; /* transferred */
792 			} else {
793 				id->comment = xstrdup(canonical_provider);
794 			}
795 			id->death = death;
796 			id->confirm = confirm;
797 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
798 			idtab->nentries++;
799 			success = 1;
800 		}
801 		sshkey_free(keys[i]);
802 		free(comments[i]);
803 	}
804 send:
805 	free(pin);
806 	free(provider);
807 	free(keys);
808 	free(comments);
809 	send_status(e, success);
810 }
811 
812 static void
process_remove_smartcard_key(SocketEntry * e)813 process_remove_smartcard_key(SocketEntry *e)
814 {
815 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
816 	int r, success = 0;
817 	Identity *id, *nxt;
818 
819 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
820 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
821 		error("%s: buffer error: %s", __func__, ssh_err(r));
822 		goto send;
823 	}
824 	free(pin);
825 
826 	if (realpath(provider, canonical_provider) == NULL) {
827 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
828 		    provider, strerror(errno));
829 		goto send;
830 	}
831 
832 	debug("%s: remove %.100s", __func__, canonical_provider);
833 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
834 		nxt = TAILQ_NEXT(id, next);
835 		/* Skip file--based keys */
836 		if (id->provider == NULL)
837 			continue;
838 		if (!strcmp(canonical_provider, id->provider)) {
839 			TAILQ_REMOVE(&idtab->idlist, id, next);
840 			free_identity(id);
841 			idtab->nentries--;
842 		}
843 	}
844 	if (pkcs11_del_provider(canonical_provider) == 0)
845 		success = 1;
846 	else
847 		error("%s: pkcs11_del_provider failed", __func__);
848 send:
849 	free(provider);
850 	send_status(e, success);
851 }
852 #endif /* ENABLE_PKCS11 */
853 
854 /* dispatch incoming messages */
855 
856 static int
process_message(u_int socknum)857 process_message(u_int socknum)
858 {
859 	u_int msg_len;
860 	u_char type;
861 	const u_char *cp;
862 	int r;
863 	SocketEntry *e;
864 
865 	if (socknum >= sockets_alloc) {
866 		fatal("%s: socket number %u >= allocated %u",
867 		    __func__, socknum, sockets_alloc);
868 	}
869 	e = &sockets[socknum];
870 
871 	if (sshbuf_len(e->input) < 5)
872 		return 0;		/* Incomplete message header. */
873 	cp = sshbuf_ptr(e->input);
874 	msg_len = PEEK_U32(cp);
875 	if (msg_len > AGENT_MAX_LEN) {
876 		debug("%s: socket %u (fd=%d) message too long %u > %u",
877 		    __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
878 		return -1;
879 	}
880 	if (sshbuf_len(e->input) < msg_len + 4)
881 		return 0;		/* Incomplete message body. */
882 
883 	/* move the current input to e->request */
884 	sshbuf_reset(e->request);
885 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
886 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
887 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
888 		    r == SSH_ERR_STRING_TOO_LARGE) {
889 			debug("%s: buffer error: %s", __func__, ssh_err(r));
890 			return -1;
891 		}
892 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
893 	}
894 
895 	debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
896 
897 	/* check whether agent is locked */
898 	if (locked && type != SSH_AGENTC_UNLOCK) {
899 		sshbuf_reset(e->request);
900 		switch (type) {
901 		case SSH2_AGENTC_REQUEST_IDENTITIES:
902 			/* send empty lists */
903 			no_identities(e);
904 			break;
905 		default:
906 			/* send a fail message for all other request types */
907 			send_status(e, 0);
908 		}
909 		return 0;
910 	}
911 
912 	switch (type) {
913 	case SSH_AGENTC_LOCK:
914 	case SSH_AGENTC_UNLOCK:
915 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
916 		break;
917 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
918 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
919 		break;
920 	/* ssh2 */
921 	case SSH2_AGENTC_SIGN_REQUEST:
922 		process_sign_request2(e);
923 		break;
924 	case SSH2_AGENTC_REQUEST_IDENTITIES:
925 		process_request_identities(e);
926 		break;
927 	case SSH2_AGENTC_ADD_IDENTITY:
928 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
929 		process_add_identity(e);
930 		break;
931 	case SSH2_AGENTC_REMOVE_IDENTITY:
932 		process_remove_identity(e);
933 		break;
934 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
935 		process_remove_all_identities(e);
936 		break;
937 #ifdef ENABLE_PKCS11
938 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
939 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
940 		process_add_smartcard_key(e);
941 		break;
942 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
943 		process_remove_smartcard_key(e);
944 		break;
945 #endif /* ENABLE_PKCS11 */
946 	default:
947 		/* Unknown message.  Respond with failure. */
948 		error("Unknown message %d", type);
949 		sshbuf_reset(e->request);
950 		send_status(e, 0);
951 		break;
952 	}
953 	return 0;
954 }
955 
956 static void
new_socket(sock_type type,int fd)957 new_socket(sock_type type, int fd)
958 {
959 	u_int i, old_alloc, new_alloc;
960 
961 	set_nonblock(fd);
962 
963 	if (fd > max_fd)
964 		max_fd = fd;
965 
966 	for (i = 0; i < sockets_alloc; i++)
967 		if (sockets[i].type == AUTH_UNUSED) {
968 			sockets[i].fd = fd;
969 			if ((sockets[i].input = sshbuf_new()) == NULL)
970 				fatal("%s: sshbuf_new failed", __func__);
971 			if ((sockets[i].output = sshbuf_new()) == NULL)
972 				fatal("%s: sshbuf_new failed", __func__);
973 			if ((sockets[i].request = sshbuf_new()) == NULL)
974 				fatal("%s: sshbuf_new failed", __func__);
975 			sockets[i].type = type;
976 			return;
977 		}
978 	old_alloc = sockets_alloc;
979 	new_alloc = sockets_alloc + 10;
980 	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
981 	for (i = old_alloc; i < new_alloc; i++)
982 		sockets[i].type = AUTH_UNUSED;
983 	sockets_alloc = new_alloc;
984 	sockets[old_alloc].fd = fd;
985 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
986 		fatal("%s: sshbuf_new failed", __func__);
987 	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
988 		fatal("%s: sshbuf_new failed", __func__);
989 	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
990 		fatal("%s: sshbuf_new failed", __func__);
991 	sockets[old_alloc].type = type;
992 }
993 
994 static int
handle_socket_read(u_int socknum)995 handle_socket_read(u_int socknum)
996 {
997 	struct sockaddr_un sunaddr;
998 	socklen_t slen;
999 	uid_t euid;
1000 	gid_t egid;
1001 	int fd;
1002 
1003 	slen = sizeof(sunaddr);
1004 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1005 	if (fd == -1) {
1006 		error("accept from AUTH_SOCKET: %s", strerror(errno));
1007 		return -1;
1008 	}
1009 	if (getpeereid(fd, &euid, &egid) == -1) {
1010 		error("getpeereid %d failed: %s", fd, strerror(errno));
1011 		close(fd);
1012 		return -1;
1013 	}
1014 	if ((euid != 0) && (getuid() != euid)) {
1015 		error("uid mismatch: peer euid %u != uid %u",
1016 		    (u_int) euid, (u_int) getuid());
1017 		close(fd);
1018 		return -1;
1019 	}
1020 	new_socket(AUTH_CONNECTION, fd);
1021 	return 0;
1022 }
1023 
1024 static int
handle_conn_read(u_int socknum)1025 handle_conn_read(u_int socknum)
1026 {
1027 	char buf[AGENT_RBUF_LEN];
1028 	ssize_t len;
1029 	int r;
1030 
1031 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1032 		if (len == -1) {
1033 			if (errno == EAGAIN || errno == EINTR)
1034 				return 0;
1035 			error("%s: read error on socket %u (fd %d): %s",
1036 			    __func__, socknum, sockets[socknum].fd,
1037 			    strerror(errno));
1038 		}
1039 		return -1;
1040 	}
1041 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1042 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1043 	explicit_bzero(buf, sizeof(buf));
1044 	process_message(socknum);
1045 	return 0;
1046 }
1047 
1048 static int
handle_conn_write(u_int socknum)1049 handle_conn_write(u_int socknum)
1050 {
1051 	ssize_t len;
1052 	int r;
1053 
1054 	if (sshbuf_len(sockets[socknum].output) == 0)
1055 		return 0; /* shouldn't happen */
1056 	if ((len = write(sockets[socknum].fd,
1057 	    sshbuf_ptr(sockets[socknum].output),
1058 	    sshbuf_len(sockets[socknum].output))) <= 0) {
1059 		if (len == -1) {
1060 			if (errno == EAGAIN || errno == EINTR)
1061 				return 0;
1062 			error("%s: read error on socket %u (fd %d): %s",
1063 			    __func__, socknum, sockets[socknum].fd,
1064 			    strerror(errno));
1065 		}
1066 		return -1;
1067 	}
1068 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1069 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1070 	return 0;
1071 }
1072 
1073 static void
after_poll(struct pollfd * pfd,size_t npfd,u_int maxfds)1074 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1075 {
1076 	size_t i;
1077 	u_int socknum, activefds = npfd;
1078 
1079 	for (i = 0; i < npfd; i++) {
1080 		if (pfd[i].revents == 0)
1081 			continue;
1082 		/* Find sockets entry */
1083 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
1084 			if (sockets[socknum].type != AUTH_SOCKET &&
1085 			    sockets[socknum].type != AUTH_CONNECTION)
1086 				continue;
1087 			if (pfd[i].fd == sockets[socknum].fd)
1088 				break;
1089 		}
1090 		if (socknum >= sockets_alloc) {
1091 			error("%s: no socket for fd %d", __func__, pfd[i].fd);
1092 			continue;
1093 		}
1094 		/* Process events */
1095 		switch (sockets[socknum].type) {
1096 		case AUTH_SOCKET:
1097 			if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1098 				break;
1099 			if (npfd > maxfds) {
1100 				debug3("out of fds (active %u >= limit %u); "
1101 				    "skipping accept", activefds, maxfds);
1102 				break;
1103 			}
1104 			if (handle_socket_read(socknum) == 0)
1105 				activefds++;
1106 			break;
1107 		case AUTH_CONNECTION:
1108 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1109 			    handle_conn_read(socknum) != 0) {
1110 				goto close_sock;
1111 			}
1112 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1113 			    handle_conn_write(socknum) != 0) {
1114  close_sock:
1115 				if (activefds == 0)
1116 					fatal("activefds == 0 at close_sock");
1117 				close_socket(&sockets[socknum]);
1118 				activefds--;
1119 				break;
1120 			}
1121 			break;
1122 		default:
1123 			break;
1124 		}
1125 	}
1126 }
1127 
1128 static int
prepare_poll(struct pollfd ** pfdp,size_t * npfdp,int * timeoutp,u_int maxfds)1129 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1130 {
1131 	struct pollfd *pfd = *pfdp;
1132 	size_t i, j, npfd = 0;
1133 	time_t deadline;
1134 	int r;
1135 
1136 	/* Count active sockets */
1137 	for (i = 0; i < sockets_alloc; i++) {
1138 		switch (sockets[i].type) {
1139 		case AUTH_SOCKET:
1140 		case AUTH_CONNECTION:
1141 			npfd++;
1142 			break;
1143 		case AUTH_UNUSED:
1144 			break;
1145 		default:
1146 			fatal("Unknown socket type %d", sockets[i].type);
1147 			break;
1148 		}
1149 	}
1150 	if (npfd != *npfdp &&
1151 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1152 		fatal("%s: recallocarray failed", __func__);
1153 	*pfdp = pfd;
1154 	*npfdp = npfd;
1155 
1156 	for (i = j = 0; i < sockets_alloc; i++) {
1157 		switch (sockets[i].type) {
1158 		case AUTH_SOCKET:
1159 			if (npfd > maxfds) {
1160 				debug3("out of fds (active %zu >= limit %u); "
1161 				    "skipping arming listener", npfd, maxfds);
1162 				break;
1163 			}
1164 			pfd[j].fd = sockets[i].fd;
1165 			pfd[j].revents = 0;
1166 			pfd[j].events = POLLIN;
1167 			j++;
1168 			break;
1169 		case AUTH_CONNECTION:
1170 			pfd[j].fd = sockets[i].fd;
1171 			pfd[j].revents = 0;
1172 			/*
1173 			 * Only prepare to read if we can handle a full-size
1174 			 * input read buffer and enqueue a max size reply..
1175 			 */
1176 			if ((r = sshbuf_check_reserve(sockets[i].input,
1177 			    AGENT_RBUF_LEN)) == 0 &&
1178 			    (r = sshbuf_check_reserve(sockets[i].output,
1179 			     AGENT_MAX_LEN)) == 0)
1180 				pfd[j].events = POLLIN;
1181 			else if (r != SSH_ERR_NO_BUFFER_SPACE) {
1182 				fatal("%s: buffer error: %s",
1183 				    __func__, ssh_err(r));
1184 			}
1185 			if (sshbuf_len(sockets[i].output) > 0)
1186 				pfd[j].events |= POLLOUT;
1187 			j++;
1188 			break;
1189 		default:
1190 			break;
1191 		}
1192 	}
1193 	deadline = reaper();
1194 	if (parent_alive_interval != 0)
1195 		deadline = (deadline == 0) ? parent_alive_interval :
1196 		    MINIMUM(deadline, parent_alive_interval);
1197 	if (deadline == 0) {
1198 		*timeoutp = -1; /* INFTIM */
1199 	} else {
1200 		if (deadline > INT_MAX / 1000)
1201 			*timeoutp = INT_MAX / 1000;
1202 		else
1203 			*timeoutp = deadline * 1000;
1204 	}
1205 	return (1);
1206 }
1207 
1208 static void
cleanup_socket(void)1209 cleanup_socket(void)
1210 {
1211 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1212 		return;
1213 	debug("%s: cleanup", __func__);
1214 	if (socket_name[0])
1215 		unlink(socket_name);
1216 	if (socket_dir[0])
1217 		rmdir(socket_dir);
1218 }
1219 
1220 void
cleanup_exit(int i)1221 cleanup_exit(int i)
1222 {
1223 	cleanup_socket();
1224 	_exit(i);
1225 }
1226 
1227 /*ARGSUSED*/
1228 static void
cleanup_handler(int sig)1229 cleanup_handler(int sig)
1230 {
1231 	cleanup_socket();
1232 #ifdef ENABLE_PKCS11
1233 	pkcs11_terminate();
1234 #endif
1235 	_exit(2);
1236 }
1237 
1238 static void
check_parent_exists(void)1239 check_parent_exists(void)
1240 {
1241 	/*
1242 	 * If our parent has exited then getppid() will return (pid_t)1,
1243 	 * so testing for that should be safe.
1244 	 */
1245 	if (parent_pid != -1 && getppid() != parent_pid) {
1246 		/* printf("Parent has died - Authentication agent exiting.\n"); */
1247 		cleanup_socket();
1248 		_exit(2);
1249 	}
1250 }
1251 
1252 static void
usage(void)1253 usage(void)
1254 {
1255 	fprintf(stderr,
1256 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1257 	    "                 [-P provider_whitelist] [-t life] [command [arg ...]]\n"
1258 	    "       ssh-agent [-c | -s] -k\n");
1259 	exit(1);
1260 }
1261 
1262 int
main(int ac,char ** av)1263 main(int ac, char **av)
1264 {
1265 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1266 	int sock, fd, ch, result, saved_errno;
1267 	char *shell, *format, *pidstr, *agentsocket = NULL;
1268 #ifdef HAVE_SETRLIMIT
1269 	struct rlimit rlim;
1270 #endif
1271 	extern int optind;
1272 	extern char *optarg;
1273 	pid_t pid;
1274 	char pidstrbuf[1 + 3 * sizeof pid];
1275 	size_t len;
1276 	mode_t prev_mask;
1277 	int timeout = -1; /* INFTIM */
1278 	struct pollfd *pfd = NULL;
1279 	size_t npfd = 0;
1280 	u_int maxfds;
1281 
1282 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1283 	sanitise_stdfd();
1284 
1285 	/* drop */
1286 	setegid(getgid());
1287 	setgid(getgid());
1288 
1289 	platform_disable_tracing(0);	/* strict=no */
1290 
1291 #ifdef RLIMIT_NOFILE
1292 	if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1293 		fatal("%s: getrlimit: %s", __progname, strerror(errno));
1294 #endif
1295 
1296 	__progname = ssh_get_progname(av[0]);
1297 	seed_rng();
1298 
1299 	while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
1300 		switch (ch) {
1301 		case 'E':
1302 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1303 			if (fingerprint_hash == -1)
1304 				fatal("Invalid hash algorithm \"%s\"", optarg);
1305 			break;
1306 		case 'c':
1307 			if (s_flag)
1308 				usage();
1309 			c_flag++;
1310 			break;
1311 		case 'k':
1312 			k_flag++;
1313 			break;
1314 		case 'O':
1315 			if (strcmp(optarg, "no-restrict-websafe") == 0)
1316 				restrict_websafe  = 0;
1317 			else
1318 				fatal("Unknown -O option");
1319 			break;
1320 		case 'P':
1321 			if (provider_whitelist != NULL)
1322 				fatal("-P option already specified");
1323 			provider_whitelist = xstrdup(optarg);
1324 			break;
1325 		case 's':
1326 			if (c_flag)
1327 				usage();
1328 			s_flag++;
1329 			break;
1330 		case 'd':
1331 			if (d_flag || D_flag)
1332 				usage();
1333 			d_flag++;
1334 			break;
1335 		case 'D':
1336 			if (d_flag || D_flag)
1337 				usage();
1338 			D_flag++;
1339 			break;
1340 		case 'a':
1341 			agentsocket = optarg;
1342 			break;
1343 		case 't':
1344 			if ((lifetime = convtime(optarg)) == -1) {
1345 				fprintf(stderr, "Invalid lifetime\n");
1346 				usage();
1347 			}
1348 			break;
1349 		default:
1350 			usage();
1351 		}
1352 	}
1353 	ac -= optind;
1354 	av += optind;
1355 
1356 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1357 		usage();
1358 
1359 	if (provider_whitelist == NULL)
1360 		provider_whitelist = xstrdup(DEFAULT_PROVIDER_WHITELIST);
1361 
1362 	if (ac == 0 && !c_flag && !s_flag) {
1363 		shell = getenv("SHELL");
1364 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1365 		    strncmp(shell + len - 3, "csh", 3) == 0)
1366 			c_flag = 1;
1367 	}
1368 	if (k_flag) {
1369 		const char *errstr = NULL;
1370 
1371 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1372 		if (pidstr == NULL) {
1373 			fprintf(stderr, "%s not set, cannot kill agent\n",
1374 			    SSH_AGENTPID_ENV_NAME);
1375 			exit(1);
1376 		}
1377 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1378 		if (errstr) {
1379 			fprintf(stderr,
1380 			    "%s=\"%s\", which is not a good PID: %s\n",
1381 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1382 			exit(1);
1383 		}
1384 		if (kill(pid, SIGTERM) == -1) {
1385 			perror("kill");
1386 			exit(1);
1387 		}
1388 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1389 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1390 		printf(format, SSH_AGENTPID_ENV_NAME);
1391 		printf("echo Agent pid %ld killed;\n", (long)pid);
1392 		exit(0);
1393 	}
1394 
1395 	/*
1396 	 * Minimum file descriptors:
1397 	 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1398 	 * a few spare for libc / stack protectors / sanitisers, etc.
1399 	 */
1400 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1401 	if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1402 		fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1403 		    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1404 	maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1405 
1406 	parent_pid = getpid();
1407 
1408 	if (agentsocket == NULL) {
1409 		/* Create private directory for agent socket */
1410 		mktemp_proto(socket_dir, sizeof(socket_dir));
1411 		if (mkdtemp(socket_dir) == NULL) {
1412 			perror("mkdtemp: private socket dir");
1413 			exit(1);
1414 		}
1415 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1416 		    (long)parent_pid);
1417 	} else {
1418 		/* Try to use specified agent socket */
1419 		socket_dir[0] = '\0';
1420 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1421 	}
1422 
1423 	/*
1424 	 * Create socket early so it will exist before command gets run from
1425 	 * the parent.
1426 	 */
1427 	prev_mask = umask(0177);
1428 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1429 	if (sock < 0) {
1430 		/* XXX - unix_listener() calls error() not perror() */
1431 		*socket_name = '\0'; /* Don't unlink any existing file */
1432 		cleanup_exit(1);
1433 	}
1434 	umask(prev_mask);
1435 
1436 	/*
1437 	 * Fork, and have the parent execute the command, if any, or present
1438 	 * the socket data.  The child continues as the authentication agent.
1439 	 */
1440 	if (D_flag || d_flag) {
1441 		log_init(__progname,
1442 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1443 		    SYSLOG_FACILITY_AUTH, 1);
1444 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1445 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1446 		    SSH_AUTHSOCKET_ENV_NAME);
1447 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1448 		fflush(stdout);
1449 		goto skip;
1450 	}
1451 	pid = fork();
1452 	if (pid == -1) {
1453 		perror("fork");
1454 		cleanup_exit(1);
1455 	}
1456 	if (pid != 0) {		/* Parent - execute the given command. */
1457 		close(sock);
1458 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1459 		if (ac == 0) {
1460 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1461 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1462 			    SSH_AUTHSOCKET_ENV_NAME);
1463 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1464 			    SSH_AGENTPID_ENV_NAME);
1465 			printf("echo Agent pid %ld;\n", (long)pid);
1466 			exit(0);
1467 		}
1468 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1469 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1470 			perror("setenv");
1471 			exit(1);
1472 		}
1473 		execvp(av[0], av);
1474 		perror(av[0]);
1475 		exit(1);
1476 	}
1477 	/* child */
1478 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1479 
1480 	if (setsid() == -1) {
1481 		error("setsid: %s", strerror(errno));
1482 		cleanup_exit(1);
1483 	}
1484 
1485 	(void)chdir("/");
1486 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1487 		/* XXX might close listen socket */
1488 		(void)dup2(fd, STDIN_FILENO);
1489 		(void)dup2(fd, STDOUT_FILENO);
1490 		(void)dup2(fd, STDERR_FILENO);
1491 		if (fd > 2)
1492 			close(fd);
1493 	}
1494 
1495 #ifdef HAVE_SETRLIMIT
1496 	/* deny core dumps, since memory contains unencrypted private keys */
1497 	rlim.rlim_cur = rlim.rlim_max = 0;
1498 	if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1499 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1500 		cleanup_exit(1);
1501 	}
1502 #endif
1503 
1504 skip:
1505 
1506 	cleanup_pid = getpid();
1507 
1508 #ifdef ENABLE_PKCS11
1509 	pkcs11_init(0);
1510 #endif
1511 	new_socket(AUTH_SOCKET, sock);
1512 	if (ac > 0)
1513 		parent_alive_interval = 10;
1514 	idtab_init();
1515 	ssh_signal(SIGPIPE, SIG_IGN);
1516 	ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1517 	ssh_signal(SIGHUP, cleanup_handler);
1518 	ssh_signal(SIGTERM, cleanup_handler);
1519 
1520 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1521 		fatal("%s: pledge: %s", __progname, strerror(errno));
1522 	platform_pledge_agent();
1523 
1524 	while (1) {
1525 		prepare_poll(&pfd, &npfd, &timeout, maxfds);
1526 		result = poll(pfd, npfd, timeout);
1527 		saved_errno = errno;
1528 		if (parent_alive_interval != 0)
1529 			check_parent_exists();
1530 		(void) reaper();	/* remove expired keys */
1531 		if (result == -1) {
1532 			if (saved_errno == EINTR)
1533 				continue;
1534 			fatal("poll: %s", strerror(saved_errno));
1535 		} else if (result > 0)
1536 			after_poll(pfd, npfd, maxfds);
1537 	}
1538 	/* NOTREACHED */
1539 }
1540