ssh-agent.c revision 1.11
1/*	$NetBSD: ssh-agent.c,v 1.11 2012/10/26 12:42:10 christos Exp $	*/
2/* $OpenBSD: ssh-agent.c,v 1.172 2011/06/03 01:37:40 dtucker Exp $ */
3/*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 *                    All rights reserved
7 * The authentication agent program.
8 *
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose.  Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 *
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__RCSID("$NetBSD: ssh-agent.c,v 1.11 2012/10/26 12:42:10 christos Exp $");
40#include <sys/types.h>
41#include <sys/time.h>
42#include <sys/queue.h>
43#include <sys/resource.h>
44#include <sys/types.h>
45#include <sys/socket.h>
46#include <sys/un.h>
47#include <sys/param.h>
48
49#include <openssl/evp.h>
50#include <openssl/md5.h>
51
52#include <errno.h>
53#include <fcntl.h>
54#include <paths.h>
55#include <signal.h>
56#include <stdlib.h>
57#include <stdio.h>
58#include <string.h>
59#include <time.h>
60#include <unistd.h>
61
62#include "xmalloc.h"
63#include "ssh.h"
64#include "rsa.h"
65#include "buffer.h"
66#include "key.h"
67#include "authfd.h"
68#include "compat.h"
69#include "log.h"
70#include "misc.h"
71#include "getpeereid.h"
72
73#ifdef ENABLE_PKCS11
74#include "ssh-pkcs11.h"
75#endif
76
77typedef enum {
78	AUTH_UNUSED,
79	AUTH_SOCKET,
80	AUTH_CONNECTION
81} sock_type;
82
83typedef struct {
84	int fd;
85	sock_type type;
86	Buffer input;
87	Buffer output;
88	Buffer request;
89} SocketEntry;
90
91u_int sockets_alloc = 0;
92SocketEntry *sockets = NULL;
93
94typedef struct identity {
95	TAILQ_ENTRY(identity) next;
96	Key *key;
97	char *comment;
98	char *provider;
99	u_int death;
100	u_int confirm;
101} Identity;
102
103typedef struct {
104	int nentries;
105	TAILQ_HEAD(idqueue, identity) idlist;
106} Idtab;
107
108/* private key table, one per protocol version */
109Idtab idtable[3];
110
111int max_fd = 0;
112
113/* pid of shell == parent of agent */
114pid_t parent_pid = -1;
115u_int parent_alive_interval = 0;
116
117/* pathname and directory for AUTH_SOCKET */
118char socket_name[MAXPATHLEN];
119char socket_dir[MAXPATHLEN];
120
121/* locking */
122int locked = 0;
123char *lock_passwd = NULL;
124
125extern char *__progname;
126
127/* Default lifetime (0 == forever) */
128static int lifetime = 0;
129
130static void
131close_socket(SocketEntry *e)
132{
133	close(e->fd);
134	e->fd = -1;
135	e->type = AUTH_UNUSED;
136	buffer_free(&e->input);
137	buffer_free(&e->output);
138	buffer_free(&e->request);
139}
140
141static void
142idtab_init(void)
143{
144	int i;
145
146	for (i = 0; i <=2; i++) {
147		TAILQ_INIT(&idtable[i].idlist);
148		idtable[i].nentries = 0;
149	}
150}
151
152/* return private key table for requested protocol version */
153static Idtab *
154idtab_lookup(int version)
155{
156	if (version < 1 || version > 2)
157		fatal("internal error, bad protocol version %d", version);
158	return &idtable[version];
159}
160
161static void
162free_identity(Identity *id)
163{
164	key_free(id->key);
165	if (id->provider != NULL)
166		xfree(id->provider);
167	xfree(id->comment);
168	xfree(id);
169}
170
171/* return matching private key for given public key */
172static Identity *
173lookup_identity(Key *key, int version)
174{
175	Identity *id;
176
177	Idtab *tab = idtab_lookup(version);
178	TAILQ_FOREACH(id, &tab->idlist, next) {
179		if (key_equal(key, id->key))
180			return (id);
181	}
182	return (NULL);
183}
184
185/* Check confirmation of keysign request */
186static int
187confirm_key(Identity *id)
188{
189	char *p;
190	int ret = -1;
191
192	p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
193	if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
194	    id->comment, p))
195		ret = 0;
196	xfree(p);
197
198	return (ret);
199}
200
201/* send list of supported public keys to 'client' */
202static void
203process_request_identities(SocketEntry *e, int version)
204{
205	Idtab *tab = idtab_lookup(version);
206	Identity *id;
207	Buffer msg;
208
209	buffer_init(&msg);
210	buffer_put_char(&msg, (version == 1) ?
211	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
212	buffer_put_int(&msg, tab->nentries);
213	TAILQ_FOREACH(id, &tab->idlist, next) {
214		if (id->key->type == KEY_RSA1) {
215			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
216			buffer_put_bignum(&msg, id->key->rsa->e);
217			buffer_put_bignum(&msg, id->key->rsa->n);
218		} else {
219			u_char *blob;
220			u_int blen;
221			key_to_blob(id->key, &blob, &blen);
222			buffer_put_string(&msg, blob, blen);
223			xfree(blob);
224		}
225		buffer_put_cstring(&msg, id->comment);
226	}
227	buffer_put_int(&e->output, buffer_len(&msg));
228	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
229	buffer_free(&msg);
230}
231
232/* ssh1 only */
233static void
234process_authentication_challenge1(SocketEntry *e)
235{
236	u_char buf[32], mdbuf[16], session_id[16];
237	u_int response_type;
238	BIGNUM *challenge;
239	Identity *id;
240	int i, len;
241	Buffer msg;
242	MD5_CTX md;
243	Key *key;
244
245	buffer_init(&msg);
246	key = key_new(KEY_RSA1);
247	if ((challenge = BN_new()) == NULL)
248		fatal("process_authentication_challenge1: BN_new failed");
249
250	(void) buffer_get_int(&e->request);			/* ignored */
251	buffer_get_bignum(&e->request, key->rsa->e);
252	buffer_get_bignum(&e->request, key->rsa->n);
253	buffer_get_bignum(&e->request, challenge);
254
255	/* Only protocol 1.1 is supported */
256	if (buffer_len(&e->request) == 0)
257		goto failure;
258	buffer_get(&e->request, session_id, 16);
259	response_type = buffer_get_int(&e->request);
260	if (response_type != 1)
261		goto failure;
262
263	id = lookup_identity(key, 1);
264	if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
265		Key *private = id->key;
266		/* Decrypt the challenge using the private key. */
267		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
268			goto failure;
269
270		/* The response is MD5 of decrypted challenge plus session id. */
271		len = BN_num_bytes(challenge);
272		if (len <= 0 || len > 32) {
273			logit("process_authentication_challenge: bad challenge length %d", len);
274			goto failure;
275		}
276		memset(buf, 0, 32);
277		BN_bn2bin(challenge, buf + 32 - len);
278		MD5_Init(&md);
279		MD5_Update(&md, buf, 32);
280		MD5_Update(&md, session_id, 16);
281		MD5_Final(mdbuf, &md);
282
283		/* Send the response. */
284		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
285		for (i = 0; i < 16; i++)
286			buffer_put_char(&msg, mdbuf[i]);
287		goto send;
288	}
289
290failure:
291	/* Unknown identity or protocol error.  Send failure. */
292	buffer_put_char(&msg, SSH_AGENT_FAILURE);
293send:
294	buffer_put_int(&e->output, buffer_len(&msg));
295	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
296	key_free(key);
297	BN_clear_free(challenge);
298	buffer_free(&msg);
299}
300
301/* ssh2 only */
302static void
303process_sign_request2(SocketEntry *e)
304{
305	u_char *blob, *data, *signature = NULL;
306	u_int blen, dlen, slen = 0;
307	extern int datafellows;
308	int odatafellows;
309	int ok = -1, flags;
310	Buffer msg;
311	Key *key;
312
313	odatafellows = datafellows;
314	datafellows = 0;
315
316	blob = buffer_get_string(&e->request, &blen);
317	data = buffer_get_string(&e->request, &dlen);
318
319	flags = buffer_get_int(&e->request);
320	if (flags & SSH_AGENT_OLD_SIGNATURE)
321		datafellows = SSH_BUG_SIGBLOB;
322
323	key = key_from_blob(blob, blen);
324	if (key != NULL) {
325		Identity *id = lookup_identity(key, 2);
326		if (id != NULL && (!id->confirm || confirm_key(id) == 0))
327			ok = key_sign(id->key, &signature, &slen, data, dlen);
328		key_free(key);
329	}
330	buffer_init(&msg);
331	if (ok == 0) {
332		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
333		buffer_put_string(&msg, signature, slen);
334	} else {
335		buffer_put_char(&msg, SSH_AGENT_FAILURE);
336	}
337	buffer_put_int(&e->output, buffer_len(&msg));
338	buffer_append(&e->output, buffer_ptr(&msg),
339	    buffer_len(&msg));
340	buffer_free(&msg);
341	xfree(data);
342	xfree(blob);
343	if (signature != NULL)
344		xfree(signature);
345	datafellows = odatafellows;
346}
347
348/* shared */
349static void
350process_remove_identity(SocketEntry *e, int version)
351{
352	u_int blen, bits;
353	int success = 0;
354	Key *key = NULL;
355	u_char *blob;
356
357	switch (version) {
358	case 1:
359		key = key_new(KEY_RSA1);
360		bits = buffer_get_int(&e->request);
361		buffer_get_bignum(&e->request, key->rsa->e);
362		buffer_get_bignum(&e->request, key->rsa->n);
363
364		if (bits != key_size(key))
365			logit("Warning: identity keysize mismatch: actual %u, announced %u",
366			    key_size(key), bits);
367		break;
368	case 2:
369		blob = buffer_get_string(&e->request, &blen);
370		key = key_from_blob(blob, blen);
371		xfree(blob);
372		break;
373	}
374	if (key != NULL) {
375		Identity *id = lookup_identity(key, version);
376		if (id != NULL) {
377			/*
378			 * We have this key.  Free the old key.  Since we
379			 * don't want to leave empty slots in the middle of
380			 * the array, we actually free the key there and move
381			 * all the entries between the empty slot and the end
382			 * of the array.
383			 */
384			Idtab *tab = idtab_lookup(version);
385			if (tab->nentries < 1)
386				fatal("process_remove_identity: "
387				    "internal error: tab->nentries %d",
388				    tab->nentries);
389			TAILQ_REMOVE(&tab->idlist, id, next);
390			free_identity(id);
391			tab->nentries--;
392			success = 1;
393		}
394		key_free(key);
395	}
396	buffer_put_int(&e->output, 1);
397	buffer_put_char(&e->output,
398	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
399}
400
401static void
402process_remove_all_identities(SocketEntry *e, int version)
403{
404	Idtab *tab = idtab_lookup(version);
405	Identity *id;
406
407	/* Loop over all identities and clear the keys. */
408	while ((id = TAILQ_FIRST(&tab->idlist)) != NULL) {
409		TAILQ_REMOVE(&tab->idlist, id, next);
410		free_identity(id);
411	}
412
413	/* Mark that there are no identities. */
414	tab->nentries = 0;
415
416	/* Send success. */
417	buffer_put_int(&e->output, 1);
418	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
419}
420
421/* removes expired keys and returns number of seconds until the next expiry */
422static u_int
423reaper(void)
424{
425	u_int deadline = 0, now = time(NULL);
426	Identity *id, *nxt;
427	int version;
428	Idtab *tab;
429
430	for (version = 1; version < 3; version++) {
431		tab = idtab_lookup(version);
432		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
433			nxt = TAILQ_NEXT(id, next);
434			if (id->death == 0)
435				continue;
436			if (now >= id->death) {
437				debug("expiring key '%s'", id->comment);
438				TAILQ_REMOVE(&tab->idlist, id, next);
439				free_identity(id);
440				tab->nentries--;
441			} else
442				deadline = (deadline == 0) ? id->death :
443				    MIN(deadline, id->death);
444		}
445	}
446	if (deadline == 0 || deadline <= now)
447		return 0;
448	else
449		return (deadline - now);
450}
451
452static void
453process_add_identity(SocketEntry *e, int version)
454{
455	Idtab *tab = idtab_lookup(version);
456	Identity *id;
457	int type, success = 0, death = 0, confirm = 0;
458	char *type_name, *comment, *curve;
459	Key *k = NULL;
460	BIGNUM *exponent;
461	EC_POINT *q;
462	u_char *cert;
463	u_int len;
464
465	switch (version) {
466	case 1:
467		k = key_new_private(KEY_RSA1);
468		(void) buffer_get_int(&e->request);		/* ignored */
469		buffer_get_bignum(&e->request, k->rsa->n);
470		buffer_get_bignum(&e->request, k->rsa->e);
471		buffer_get_bignum(&e->request, k->rsa->d);
472		buffer_get_bignum(&e->request, k->rsa->iqmp);
473
474		/* SSH and SSL have p and q swapped */
475		buffer_get_bignum(&e->request, k->rsa->q);	/* p */
476		buffer_get_bignum(&e->request, k->rsa->p);	/* q */
477
478		/* Generate additional parameters */
479		rsa_generate_additional_parameters(k->rsa);
480		break;
481	case 2:
482		type_name = buffer_get_string(&e->request, NULL);
483		type = key_type_from_name(type_name);
484		switch (type) {
485		case KEY_DSA:
486			k = key_new_private(type);
487			buffer_get_bignum2(&e->request, k->dsa->p);
488			buffer_get_bignum2(&e->request, k->dsa->q);
489			buffer_get_bignum2(&e->request, k->dsa->g);
490			buffer_get_bignum2(&e->request, k->dsa->pub_key);
491			buffer_get_bignum2(&e->request, k->dsa->priv_key);
492			break;
493		case KEY_DSA_CERT_V00:
494		case KEY_DSA_CERT:
495			cert = buffer_get_string(&e->request, &len);
496			if ((k = key_from_blob(cert, len)) == NULL)
497				fatal("Certificate parse failed");
498			xfree(cert);
499			key_add_private(k);
500			buffer_get_bignum2(&e->request, k->dsa->priv_key);
501			break;
502		case KEY_ECDSA:
503			k = key_new_private(type);
504			k->ecdsa_nid = key_ecdsa_nid_from_name(type_name);
505			curve = buffer_get_string(&e->request, NULL);
506			if (k->ecdsa_nid != key_curve_name_to_nid(curve))
507				fatal("%s: curve names mismatch", __func__);
508			xfree(curve);
509			k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
510			if (k->ecdsa == NULL)
511				fatal("%s: EC_KEY_new_by_curve_name failed",
512				    __func__);
513			q = EC_POINT_new(EC_KEY_get0_group(k->ecdsa));
514			if (q == NULL)
515				fatal("%s: BN_new failed", __func__);
516			if ((exponent = BN_new()) == NULL)
517				fatal("%s: BN_new failed", __func__);
518			buffer_get_ecpoint(&e->request,
519				EC_KEY_get0_group(k->ecdsa), q);
520			buffer_get_bignum2(&e->request, exponent);
521			if (EC_KEY_set_public_key(k->ecdsa, q) != 1)
522				fatal("%s: EC_KEY_set_public_key failed",
523				    __func__);
524			if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
525				fatal("%s: EC_KEY_set_private_key failed",
526				    __func__);
527			if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
528			    EC_KEY_get0_public_key(k->ecdsa)) != 0)
529				fatal("%s: bad ECDSA public key", __func__);
530			if (key_ec_validate_private(k->ecdsa) != 0)
531				fatal("%s: bad ECDSA private key", __func__);
532			BN_clear_free(exponent);
533			EC_POINT_free(q);
534			break;
535		case KEY_ECDSA_CERT:
536			cert = buffer_get_string(&e->request, &len);
537			if ((k = key_from_blob(cert, len)) == NULL)
538				fatal("Certificate parse failed");
539			xfree(cert);
540			key_add_private(k);
541			if ((exponent = BN_new()) == NULL)
542				fatal("%s: BN_new failed", __func__);
543			buffer_get_bignum2(&e->request, exponent);
544			if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
545				fatal("%s: EC_KEY_set_private_key failed",
546				    __func__);
547			if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
548			    EC_KEY_get0_public_key(k->ecdsa)) != 0 ||
549			    key_ec_validate_private(k->ecdsa) != 0)
550				fatal("%s: bad ECDSA key", __func__);
551			BN_clear_free(exponent);
552			break;
553		case KEY_RSA:
554			k = key_new_private(type);
555			buffer_get_bignum2(&e->request, k->rsa->n);
556			buffer_get_bignum2(&e->request, k->rsa->e);
557			buffer_get_bignum2(&e->request, k->rsa->d);
558			buffer_get_bignum2(&e->request, k->rsa->iqmp);
559			buffer_get_bignum2(&e->request, k->rsa->p);
560			buffer_get_bignum2(&e->request, k->rsa->q);
561
562			/* Generate additional parameters */
563			rsa_generate_additional_parameters(k->rsa);
564			break;
565		case KEY_RSA_CERT_V00:
566		case KEY_RSA_CERT:
567			cert = buffer_get_string(&e->request, &len);
568			if ((k = key_from_blob(cert, len)) == NULL)
569				fatal("Certificate parse failed");
570			xfree(cert);
571			key_add_private(k);
572			buffer_get_bignum2(&e->request, k->rsa->d);
573			buffer_get_bignum2(&e->request, k->rsa->iqmp);
574			buffer_get_bignum2(&e->request, k->rsa->p);
575			buffer_get_bignum2(&e->request, k->rsa->q);
576			break;
577		default:
578			xfree(type_name);
579			buffer_clear(&e->request);
580			goto send;
581		}
582		xfree(type_name);
583		break;
584	}
585	/* enable blinding */
586	switch (k->type) {
587	case KEY_RSA:
588	case KEY_RSA_CERT_V00:
589	case KEY_RSA_CERT:
590	case KEY_RSA1:
591		if (RSA_blinding_on(k->rsa, NULL) != 1) {
592			error("process_add_identity: RSA_blinding_on failed");
593			key_free(k);
594			goto send;
595		}
596		break;
597	}
598	comment = buffer_get_string(&e->request, NULL);
599	if (k == NULL) {
600		xfree(comment);
601		goto send;
602	}
603	while (buffer_len(&e->request)) {
604		switch ((type = buffer_get_char(&e->request))) {
605		case SSH_AGENT_CONSTRAIN_LIFETIME:
606			death = time(NULL) + buffer_get_int(&e->request);
607			break;
608		case SSH_AGENT_CONSTRAIN_CONFIRM:
609			confirm = 1;
610			break;
611		default:
612			error("process_add_identity: "
613			    "Unknown constraint type %d", type);
614			xfree(comment);
615			key_free(k);
616			goto send;
617		}
618	}
619	success = 1;
620	if (lifetime && !death)
621		death = time(NULL) + lifetime;
622	if ((id = lookup_identity(k, version)) == NULL) {
623		id = xcalloc(1, sizeof(Identity));
624		id->key = k;
625		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
626		/* Increment the number of identities. */
627		tab->nentries++;
628	} else {
629		key_free(k);
630		xfree(id->comment);
631	}
632	id->comment = comment;
633	id->death = death;
634	id->confirm = confirm;
635send:
636	buffer_put_int(&e->output, 1);
637	buffer_put_char(&e->output,
638	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
639}
640
641/* XXX todo: encrypt sensitive data with passphrase */
642static void
643process_lock_agent(SocketEntry *e, int lock)
644{
645	int success = 0;
646	char *passwd;
647
648	passwd = buffer_get_string(&e->request, NULL);
649	if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
650		locked = 0;
651		memset(lock_passwd, 0, strlen(lock_passwd));
652		xfree(lock_passwd);
653		lock_passwd = NULL;
654		success = 1;
655	} else if (!locked && lock) {
656		locked = 1;
657		lock_passwd = xstrdup(passwd);
658		success = 1;
659	}
660	memset(passwd, 0, strlen(passwd));
661	xfree(passwd);
662
663	buffer_put_int(&e->output, 1);
664	buffer_put_char(&e->output,
665	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
666}
667
668static void
669no_identities(SocketEntry *e, u_int type)
670{
671	Buffer msg;
672
673	buffer_init(&msg);
674	buffer_put_char(&msg,
675	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
676	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
677	buffer_put_int(&msg, 0);
678	buffer_put_int(&e->output, buffer_len(&msg));
679	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
680	buffer_free(&msg);
681}
682
683#ifdef ENABLE_PKCS11
684static void
685process_add_smartcard_key(SocketEntry *e)
686{
687	char *provider = NULL, *pin;
688	int i, type, version, count = 0, success = 0, death = 0, confirm = 0;
689	Key **keys = NULL, *k;
690	Identity *id;
691	Idtab *tab;
692
693	provider = buffer_get_string(&e->request, NULL);
694	pin = buffer_get_string(&e->request, NULL);
695
696	while (buffer_len(&e->request)) {
697		switch ((type = buffer_get_char(&e->request))) {
698		case SSH_AGENT_CONSTRAIN_LIFETIME:
699			death = time(NULL) + buffer_get_int(&e->request);
700			break;
701		case SSH_AGENT_CONSTRAIN_CONFIRM:
702			confirm = 1;
703			break;
704		default:
705			error("process_add_smartcard_key: "
706			    "Unknown constraint type %d", type);
707			goto send;
708		}
709	}
710	if (lifetime && !death)
711		death = time(NULL) + lifetime;
712
713	count = pkcs11_add_provider(provider, pin, &keys);
714	for (i = 0; i < count; i++) {
715		k = keys[i];
716		version = k->type == KEY_RSA1 ? 1 : 2;
717		tab = idtab_lookup(version);
718		if (lookup_identity(k, version) == NULL) {
719			id = xcalloc(1, sizeof(Identity));
720			id->key = k;
721			id->provider = xstrdup(provider);
722			id->comment = xstrdup(provider); /* XXX */
723			id->death = death;
724			id->confirm = confirm;
725			TAILQ_INSERT_TAIL(&tab->idlist, id, next);
726			tab->nentries++;
727			success = 1;
728		} else {
729			key_free(k);
730		}
731		keys[i] = NULL;
732	}
733send:
734	if (pin)
735		xfree(pin);
736	if (provider)
737		xfree(provider);
738	if (keys)
739		xfree(keys);
740	buffer_put_int(&e->output, 1);
741	buffer_put_char(&e->output,
742	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
743}
744
745static void
746process_remove_smartcard_key(SocketEntry *e)
747{
748	char *provider = NULL, *pin = NULL;
749	int version, success = 0;
750	Identity *id, *nxt;
751	Idtab *tab;
752
753	provider = buffer_get_string(&e->request, NULL);
754	pin = buffer_get_string(&e->request, NULL);
755	xfree(pin);
756
757	for (version = 1; version < 3; version++) {
758		tab = idtab_lookup(version);
759		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
760			nxt = TAILQ_NEXT(id, next);
761			if (!strcmp(provider, id->provider)) {
762				TAILQ_REMOVE(&tab->idlist, id, next);
763				free_identity(id);
764				tab->nentries--;
765			}
766		}
767	}
768	if (pkcs11_del_provider(provider) == 0)
769		success = 1;
770	else
771		error("process_remove_smartcard_key:"
772		    " pkcs11_del_provider failed");
773	xfree(provider);
774	buffer_put_int(&e->output, 1);
775	buffer_put_char(&e->output,
776	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
777}
778#endif /* ENABLE_PKCS11 */
779
780/* dispatch incoming messages */
781
782static void
783process_message(SocketEntry *e)
784{
785	u_int msg_len, type;
786	u_char *cp;
787
788	if (buffer_len(&e->input) < 5)
789		return;		/* Incomplete message. */
790	cp = buffer_ptr(&e->input);
791	msg_len = get_u32(cp);
792	if (msg_len > 256 * 1024) {
793		close_socket(e);
794		return;
795	}
796	if (buffer_len(&e->input) < msg_len + 4)
797		return;
798
799	/* move the current input to e->request */
800	buffer_consume(&e->input, 4);
801	buffer_clear(&e->request);
802	buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
803	buffer_consume(&e->input, msg_len);
804	type = buffer_get_char(&e->request);
805
806	/* check wheter agent is locked */
807	if (locked && type != SSH_AGENTC_UNLOCK) {
808		buffer_clear(&e->request);
809		switch (type) {
810		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
811		case SSH2_AGENTC_REQUEST_IDENTITIES:
812			/* send empty lists */
813			no_identities(e, type);
814			break;
815		default:
816			/* send a fail message for all other request types */
817			buffer_put_int(&e->output, 1);
818			buffer_put_char(&e->output, SSH_AGENT_FAILURE);
819		}
820		return;
821	}
822
823	debug("type %d", type);
824	switch (type) {
825	case SSH_AGENTC_LOCK:
826	case SSH_AGENTC_UNLOCK:
827		process_lock_agent(e, type == SSH_AGENTC_LOCK);
828		break;
829	/* ssh1 */
830	case SSH_AGENTC_RSA_CHALLENGE:
831		process_authentication_challenge1(e);
832		break;
833	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
834		process_request_identities(e, 1);
835		break;
836	case SSH_AGENTC_ADD_RSA_IDENTITY:
837	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
838		process_add_identity(e, 1);
839		break;
840	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
841		process_remove_identity(e, 1);
842		break;
843	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
844		process_remove_all_identities(e, 1);
845		break;
846	/* ssh2 */
847	case SSH2_AGENTC_SIGN_REQUEST:
848		process_sign_request2(e);
849		break;
850	case SSH2_AGENTC_REQUEST_IDENTITIES:
851		process_request_identities(e, 2);
852		break;
853	case SSH2_AGENTC_ADD_IDENTITY:
854	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
855		process_add_identity(e, 2);
856		break;
857	case SSH2_AGENTC_REMOVE_IDENTITY:
858		process_remove_identity(e, 2);
859		break;
860	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
861		process_remove_all_identities(e, 2);
862		break;
863#ifdef ENABLE_PKCS11
864	case SSH_AGENTC_ADD_SMARTCARD_KEY:
865	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
866		process_add_smartcard_key(e);
867		break;
868	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
869		process_remove_smartcard_key(e);
870		break;
871#endif /* ENABLE_PKCS11 */
872	default:
873		/* Unknown message.  Respond with failure. */
874		error("Unknown message %d", type);
875		buffer_clear(&e->request);
876		buffer_put_int(&e->output, 1);
877		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
878		break;
879	}
880}
881
882static void
883new_socket(sock_type type, int fd)
884{
885	u_int i, old_alloc, new_alloc;
886
887	set_nonblock(fd);
888
889	if (fd > max_fd)
890		max_fd = fd;
891
892	for (i = 0; i < sockets_alloc; i++)
893		if (sockets[i].type == AUTH_UNUSED) {
894			sockets[i].fd = fd;
895			buffer_init(&sockets[i].input);
896			buffer_init(&sockets[i].output);
897			buffer_init(&sockets[i].request);
898			sockets[i].type = type;
899			return;
900		}
901	old_alloc = sockets_alloc;
902	new_alloc = sockets_alloc + 10;
903	sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
904	for (i = old_alloc; i < new_alloc; i++)
905		sockets[i].type = AUTH_UNUSED;
906	sockets_alloc = new_alloc;
907	sockets[old_alloc].fd = fd;
908	buffer_init(&sockets[old_alloc].input);
909	buffer_init(&sockets[old_alloc].output);
910	buffer_init(&sockets[old_alloc].request);
911	sockets[old_alloc].type = type;
912}
913
914static int
915prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
916    struct timeval **tvpp)
917{
918	u_int i, sz, deadline;
919	int n = 0;
920	static struct timeval tv;
921
922	for (i = 0; i < sockets_alloc; i++) {
923		switch (sockets[i].type) {
924		case AUTH_SOCKET:
925		case AUTH_CONNECTION:
926			n = MAX(n, sockets[i].fd);
927			break;
928		case AUTH_UNUSED:
929			break;
930		default:
931			fatal("Unknown socket type %d", sockets[i].type);
932			break;
933		}
934	}
935
936	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
937	if (*fdrp == NULL || sz > *nallocp) {
938		if (*fdrp)
939			xfree(*fdrp);
940		if (*fdwp)
941			xfree(*fdwp);
942		*fdrp = xmalloc(sz);
943		*fdwp = xmalloc(sz);
944		*nallocp = sz;
945	}
946	if (n < *fdl)
947		debug("XXX shrink: %d < %d", n, *fdl);
948	*fdl = n;
949	memset(*fdrp, 0, sz);
950	memset(*fdwp, 0, sz);
951
952	for (i = 0; i < sockets_alloc; i++) {
953		switch (sockets[i].type) {
954		case AUTH_SOCKET:
955		case AUTH_CONNECTION:
956			FD_SET(sockets[i].fd, *fdrp);
957			if (buffer_len(&sockets[i].output) > 0)
958				FD_SET(sockets[i].fd, *fdwp);
959			break;
960		default:
961			break;
962		}
963	}
964	deadline = reaper();
965	if (parent_alive_interval != 0)
966		deadline = (deadline == 0) ? parent_alive_interval :
967		    MIN(deadline, parent_alive_interval);
968	if (deadline == 0) {
969		*tvpp = NULL;
970	} else {
971		tv.tv_sec = deadline;
972		tv.tv_usec = 0;
973		*tvpp = &tv;
974	}
975	return (1);
976}
977
978static void
979after_select(fd_set *readset, fd_set *writeset)
980{
981	struct sockaddr_un sunaddr;
982	socklen_t slen;
983	char buf[1024];
984	int len, sock;
985	u_int i, orig_alloc;
986	uid_t euid;
987	gid_t egid;
988
989	for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
990		switch (sockets[i].type) {
991		case AUTH_UNUSED:
992			break;
993		case AUTH_SOCKET:
994			if (FD_ISSET(sockets[i].fd, readset)) {
995				slen = sizeof(sunaddr);
996				sock = accept(sockets[i].fd,
997				    (struct sockaddr *)&sunaddr, &slen);
998				if (sock < 0) {
999					error("accept from AUTH_SOCKET: %s",
1000					    strerror(errno));
1001					break;
1002				}
1003				if (getpeereid(sock, &euid, &egid) < 0) {
1004					error("getpeereid %d failed: %s",
1005					    sock, strerror(errno));
1006					close(sock);
1007					break;
1008				}
1009				if ((euid != 0) && (getuid() != euid)) {
1010					error("uid mismatch: "
1011					    "peer euid %u != uid %u",
1012					    (u_int) euid, (u_int) getuid());
1013					close(sock);
1014					break;
1015				}
1016				new_socket(AUTH_CONNECTION, sock);
1017			}
1018			break;
1019		case AUTH_CONNECTION:
1020			if (buffer_len(&sockets[i].output) > 0 &&
1021			    FD_ISSET(sockets[i].fd, writeset)) {
1022				len = write(sockets[i].fd,
1023				    buffer_ptr(&sockets[i].output),
1024				    buffer_len(&sockets[i].output));
1025				if (len == -1 && (errno == EAGAIN ||
1026				    errno == EINTR))
1027					continue;
1028				if (len <= 0) {
1029					close_socket(&sockets[i]);
1030					break;
1031				}
1032				buffer_consume(&sockets[i].output, len);
1033			}
1034			if (FD_ISSET(sockets[i].fd, readset)) {
1035				len = read(sockets[i].fd, buf, sizeof(buf));
1036				if (len == -1 && (errno == EAGAIN ||
1037				    errno == EINTR))
1038					continue;
1039				if (len <= 0) {
1040					close_socket(&sockets[i]);
1041					break;
1042				}
1043				buffer_append(&sockets[i].input, buf, len);
1044				process_message(&sockets[i]);
1045			}
1046			break;
1047		default:
1048			fatal("Unknown type %d", sockets[i].type);
1049		}
1050}
1051
1052static void
1053cleanup_socket(void)
1054{
1055	if (socket_name[0])
1056		unlink(socket_name);
1057	if (socket_dir[0])
1058		rmdir(socket_dir);
1059}
1060
1061void
1062cleanup_exit(int i)
1063{
1064	cleanup_socket();
1065	_exit(i);
1066}
1067
1068/*ARGSUSED*/
1069__dead static void
1070cleanup_handler(int sig)
1071{
1072	cleanup_socket();
1073#ifdef ENABLE_PKCS11
1074	pkcs11_terminate();
1075#endif
1076	_exit(2);
1077}
1078
1079static void
1080check_parent_exists(void)
1081{
1082	/*
1083	 * If our parent has exited then getppid() will return (pid_t)1,
1084	 * so testing for that should be safe.
1085	 */
1086	if (parent_pid != -1 && getppid() != parent_pid) {
1087		/* printf("Parent has died - Authentication agent exiting.\n"); */
1088		cleanup_socket();
1089		_exit(2);
1090	}
1091}
1092
1093__dead static void
1094usage(void)
1095{
1096	fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1097	    __progname);
1098	fprintf(stderr, "Options:\n");
1099	fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
1100	fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
1101	fprintf(stderr, "  -k          Kill the current agent.\n");
1102	fprintf(stderr, "  -d          Debug mode.\n");
1103	fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
1104	fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
1105	exit(1);
1106}
1107
1108static void
1109csh_setenv(const char *name, const char *value)
1110{
1111	printf("setenv %s %s;\n", name, value);
1112}
1113
1114static void
1115csh_unsetenv(const char *name)
1116{
1117	printf("unsetenv %s;\n", name);
1118}
1119
1120static void
1121sh_setenv(const char *name, const char *value)
1122{
1123	printf("%s=%s; export %s;\n", name, value, name);
1124}
1125
1126static void
1127sh_unsetenv(const char *name)
1128{
1129	printf("unset %s;\n", name);
1130}
1131int
1132main(int ac, char **av)
1133{
1134	int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1135	int sock, fd, ch, result, saved_errno;
1136	u_int nalloc;
1137	char *shell, *pidstr, *agentsocket = NULL;
1138	fd_set *readsetp = NULL, *writesetp = NULL;
1139	struct sockaddr_un sunaddr;
1140	struct rlimit rlim;
1141	extern int optind;
1142	extern char *optarg;
1143	pid_t pid;
1144	char pidstrbuf[1 + 3 * sizeof pid];
1145	struct timeval *tvp = NULL;
1146	size_t len;
1147	void (*f_setenv)(const char *, const char *);
1148	void (*f_unsetenv)(const char *);
1149
1150	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1151	sanitise_stdfd();
1152
1153	/* drop */
1154	setegid(getgid());
1155	setgid(getgid());
1156
1157	OpenSSL_add_all_algorithms();
1158
1159	while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1160		switch (ch) {
1161		case 'c':
1162			if (s_flag)
1163				usage();
1164			c_flag++;
1165			break;
1166		case 'k':
1167			k_flag++;
1168			break;
1169		case 's':
1170			if (c_flag)
1171				usage();
1172			s_flag++;
1173			break;
1174		case 'd':
1175			if (d_flag)
1176				usage();
1177			d_flag++;
1178			break;
1179		case 'a':
1180			agentsocket = optarg;
1181			break;
1182		case 't':
1183			if ((lifetime = convtime(optarg)) == -1) {
1184				fprintf(stderr, "Invalid lifetime\n");
1185				usage();
1186			}
1187			break;
1188		default:
1189			usage();
1190		}
1191	}
1192	ac -= optind;
1193	av += optind;
1194
1195	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1196		usage();
1197
1198	if (ac == 0 && !c_flag && !s_flag) {
1199		shell = getenv("SHELL");
1200		if (shell != NULL && (len = strlen(shell)) > 2 &&
1201		    strncmp(shell + len - 3, "csh", 3) == 0)
1202			c_flag = 1;
1203	}
1204	if (c_flag) {
1205		f_setenv = csh_setenv;
1206		f_unsetenv = csh_unsetenv;
1207	} else {
1208		f_setenv = sh_setenv;
1209		f_unsetenv = sh_unsetenv;
1210	}
1211	if (k_flag) {
1212		const char *errstr = NULL;
1213
1214		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1215		if (pidstr == NULL) {
1216			fprintf(stderr, "%s not set, cannot kill agent\n",
1217			    SSH_AGENTPID_ENV_NAME);
1218			exit(1);
1219		}
1220		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1221		if (errstr) {
1222			fprintf(stderr,
1223			    "%s=\"%s\", which is not a good PID: %s\n",
1224			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1225			exit(1);
1226		}
1227		if (kill(pid, SIGTERM) == -1) {
1228			perror("kill");
1229			exit(1);
1230		}
1231		(*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME);
1232		(*f_unsetenv)(SSH_AGENTPID_ENV_NAME);
1233		printf("echo Agent pid %ld killed;\n", (long)pid);
1234		exit(0);
1235	}
1236	parent_pid = getpid();
1237
1238	if (agentsocket == NULL) {
1239		/* Create private directory for agent socket */
1240		mktemp_proto(socket_dir, sizeof(socket_dir));
1241		if (mkdtemp(socket_dir) == NULL) {
1242			perror("mkdtemp: private socket dir");
1243			exit(1);
1244		}
1245		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1246		    (long)parent_pid);
1247	} else {
1248		/* Try to use specified agent socket */
1249		socket_dir[0] = '\0';
1250		strlcpy(socket_name, agentsocket, sizeof socket_name);
1251	}
1252
1253	/*
1254	 * Create socket early so it will exist before command gets run from
1255	 * the parent.
1256	 */
1257	sock = socket(AF_UNIX, SOCK_STREAM, 0);
1258	if (sock < 0) {
1259		perror("socket");
1260		*socket_name = '\0'; /* Don't unlink any existing file */
1261		cleanup_exit(1);
1262	}
1263	memset(&sunaddr, 0, sizeof(sunaddr));
1264	sunaddr.sun_family = AF_UNIX;
1265	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1266	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1267		perror("bind");
1268		*socket_name = '\0'; /* Don't unlink any existing file */
1269		cleanup_exit(1);
1270	}
1271	if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1272		perror("listen");
1273		cleanup_exit(1);
1274	}
1275
1276	/*
1277	 * Fork, and have the parent execute the command, if any, or present
1278	 * the socket data.  The child continues as the authentication agent.
1279	 */
1280	if (d_flag) {
1281		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1282		(*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
1283		printf("echo Agent pid %ld;\n", (long)parent_pid);
1284		goto skip;
1285	}
1286	pid = fork();
1287	if (pid == -1) {
1288		perror("fork");
1289		cleanup_exit(1);
1290	}
1291	if (pid != 0) {		/* Parent - execute the given command. */
1292		close(sock);
1293		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1294		if (ac == 0) {
1295			(*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
1296			(*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf);
1297			printf("echo Agent pid %ld;\n", (long)pid);
1298			exit(0);
1299		}
1300		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1301		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1302			perror("setenv");
1303			exit(1);
1304		}
1305		execvp(av[0], av);
1306		perror(av[0]);
1307		exit(1);
1308	}
1309	/* child */
1310	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1311
1312	if (setsid() == -1) {
1313		error("setsid: %s", strerror(errno));
1314		cleanup_exit(1);
1315	}
1316
1317	(void)chdir("/");
1318
1319	if (sock != STDERR_FILENO + 1) {
1320		if (dup2(sock, STDERR_FILENO + 1) == -1) {
1321			error("dup2: %s", strerror(errno));
1322			cleanup_exit(1);
1323		}
1324		close(sock);
1325		sock = STDERR_FILENO + 1;
1326	}
1327#if defined(F_CLOSEM)
1328	if (fcntl(sock + 1, F_CLOSEM, 0) == -1) {
1329		error("fcntl F_CLOSEM: %s", strerror(errno));
1330		cleanup_exit(1);
1331	}
1332#else
1333	{
1334		int nfiles;
1335#if defined(_SC_OPEN_MAX)
1336		nfiles = sysconf(_SC_OPEN_MAX);
1337#elif defined(RLIMIT_NOFILE)
1338		if (getrlimit(RLIMIT_CORE, &rlim) < 0) {
1339			error("getrlimit RLIMIT_NOFILE: %s", strerror(errno));
1340			cleanup_exit(1);
1341		}
1342		nfiles = rlim.rlim_cur;
1343#elif defined(OPEN_MAX)
1344		nfiles = OPEN_MAX;
1345#elif defined(NOFILE)
1346		nfiles = NOFILE;
1347#else
1348		nfiles = 1024;
1349#endif
1350		for (fd = sock + 1; fd < nfiles; fd++)
1351			close(fd);
1352	}
1353#endif
1354	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1355		if (dup2(fd, STDIN_FILENO) == -1 ||
1356		    dup2(fd, STDOUT_FILENO) == -1 ||
1357		    dup2(fd, STDERR_FILENO) == -1) {
1358			error("dup2: %s", strerror(errno));
1359			cleanup_exit(1);
1360		}
1361		if (fd > STDERR_FILENO)
1362			close(fd);
1363	}
1364
1365	/* deny core dumps, since memory contains unencrypted private keys */
1366	rlim.rlim_cur = rlim.rlim_max = 0;
1367	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1368		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1369		cleanup_exit(1);
1370	}
1371
1372skip:
1373
1374#ifdef ENABLE_PKCS11
1375	pkcs11_init(0);
1376#endif
1377	new_socket(AUTH_SOCKET, sock);
1378	if (ac > 0)
1379		parent_alive_interval = 10;
1380	idtab_init();
1381	if (!d_flag)
1382		signal(SIGINT, SIG_IGN);
1383	signal(SIGPIPE, SIG_IGN);
1384	signal(SIGHUP, cleanup_handler);
1385	signal(SIGTERM, cleanup_handler);
1386	nalloc = 0;
1387
1388	while (1) {
1389		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1390		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1391		saved_errno = errno;
1392		if (parent_alive_interval != 0)
1393			check_parent_exists();
1394		(void) reaper();	/* remove expired keys */
1395		if (result < 0) {
1396			if (saved_errno == EINTR)
1397				continue;
1398			fatal("select: %s", strerror(saved_errno));
1399		} else if (result > 0)
1400			after_select(readsetp, writesetp);
1401	}
1402	/* NOTREACHED */
1403}
1404