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