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