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