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