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