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