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