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