]> andersk Git - openssh.git/blob - ssh-agent.c
- stevesk@cvs.openbsd.org 2002/03/04 17:27:39
[openssh.git] / ssh-agent.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * The authentication agent program.
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 #include "includes.h"
37 RCSID("$OpenBSD: ssh-agent.c,v 1.82 2002/03/04 17:27:39 stevesk Exp $");
38
39 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
40 #include <sys/queue.h>
41 #else
42 #include "openbsd-compat/fake-queue.h"
43 #endif
44
45
46 #include <openssl/evp.h>
47 #include <openssl/md5.h>
48
49 #include "ssh.h"
50 #include "rsa.h"
51 #include "buffer.h"
52 #include "bufaux.h"
53 #include "xmalloc.h"
54 #include "getput.h"
55 #include "key.h"
56 #include "authfd.h"
57 #include "compat.h"
58 #include "log.h"
59
60 #ifdef SMARTCARD
61 #include <openssl/engine.h>
62 #include "scard.h"
63 #endif
64
65 typedef enum {
66         AUTH_UNUSED,
67         AUTH_SOCKET,
68         AUTH_CONNECTION
69 } sock_type;
70
71 typedef struct {
72         int fd;
73         sock_type type;
74         Buffer input;
75         Buffer output;
76 } SocketEntry;
77
78 u_int sockets_alloc = 0;
79 SocketEntry *sockets = NULL;
80
81 typedef struct identity {
82         TAILQ_ENTRY(identity) next;
83         Key *key;
84         char *comment;
85 } Identity;
86
87 typedef struct {
88         int nentries;
89         TAILQ_HEAD(idqueue, identity) idlist;
90 } Idtab;
91
92 /* private key table, one per protocol version */
93 Idtab idtable[3];
94
95 int max_fd = 0;
96
97 /* pid of shell == parent of agent */
98 pid_t parent_pid = -1;
99
100 /* pathname and directory for AUTH_SOCKET */
101 char socket_name[1024];
102 char socket_dir[1024];
103
104 #ifdef HAVE___PROGNAME
105 extern char *__progname;
106 #else
107 char *__progname;
108 #endif
109
110 static void
111 idtab_init(void)
112 {
113         int i;
114         for (i = 0; i <=2; i++) {
115                 TAILQ_INIT(&idtable[i].idlist);
116                 idtable[i].nentries = 0;
117         }
118 }
119
120 /* return private key table for requested protocol version */
121 static Idtab *
122 idtab_lookup(int version)
123 {
124         if (version < 1 || version > 2)
125                 fatal("internal error, bad protocol version %d", version);
126         return &idtable[version];
127 }
128
129 /* return matching private key for given public key */
130 static Identity *
131 lookup_identity(Key *key, int version)
132 {
133         Identity *id;
134
135         Idtab *tab = idtab_lookup(version);
136         TAILQ_FOREACH(id, &tab->idlist, next) {
137                 if (key_equal(key, id->key))
138                         return (id);
139         }
140         return (NULL);
141 }
142
143 static void
144 free_identity(Identity *id)
145 {
146         key_free(id->key);
147         xfree(id->comment);
148         xfree(id);
149 }
150
151 /* send list of supported public keys to 'client' */
152 static void
153 process_request_identities(SocketEntry *e, int version)
154 {
155         Idtab *tab = idtab_lookup(version);
156         Buffer msg;
157         Identity *id;
158
159         buffer_init(&msg);
160         buffer_put_char(&msg, (version == 1) ?
161             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
162         buffer_put_int(&msg, tab->nentries);
163         TAILQ_FOREACH(id, &tab->idlist, next) {
164                 if (id->key->type == KEY_RSA1) {
165                         buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
166                         buffer_put_bignum(&msg, id->key->rsa->e);
167                         buffer_put_bignum(&msg, id->key->rsa->n);
168                 } else {
169                         u_char *blob;
170                         u_int blen;
171                         key_to_blob(id->key, &blob, &blen);
172                         buffer_put_string(&msg, blob, blen);
173                         xfree(blob);
174                 }
175                 buffer_put_cstring(&msg, id->comment);
176         }
177         buffer_put_int(&e->output, buffer_len(&msg));
178         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
179         buffer_free(&msg);
180 }
181
182 /* ssh1 only */
183 static void
184 process_authentication_challenge1(SocketEntry *e)
185 {
186         Identity *id;
187         Key *key;
188         BIGNUM *challenge;
189         int i, len;
190         Buffer msg;
191         MD5_CTX md;
192         u_char buf[32], mdbuf[16], session_id[16];
193         u_int response_type;
194
195         buffer_init(&msg);
196         key = key_new(KEY_RSA1);
197         if ((challenge = BN_new()) == NULL)
198                 fatal("process_authentication_challenge1: BN_new failed");
199
200         buffer_get_int(&e->input);                              /* ignored */
201         buffer_get_bignum(&e->input, key->rsa->e);
202         buffer_get_bignum(&e->input, key->rsa->n);
203         buffer_get_bignum(&e->input, challenge);
204
205         /* Only protocol 1.1 is supported */
206         if (buffer_len(&e->input) == 0)
207                 goto failure;
208         buffer_get(&e->input, session_id, 16);
209         response_type = buffer_get_int(&e->input);
210         if (response_type != 1)
211                 goto failure;
212
213         id = lookup_identity(key, 1);
214         if (id != NULL) {
215                 Key *private = id->key;
216                 /* Decrypt the challenge using the private key. */
217                 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
218                         goto failure;
219
220                 /* The response is MD5 of decrypted challenge plus session id. */
221                 len = BN_num_bytes(challenge);
222                 if (len <= 0 || len > 32) {
223                         log("process_authentication_challenge: bad challenge length %d", len);
224                         goto failure;
225                 }
226                 memset(buf, 0, 32);
227                 BN_bn2bin(challenge, buf + 32 - len);
228                 MD5_Init(&md);
229                 MD5_Update(&md, buf, 32);
230                 MD5_Update(&md, session_id, 16);
231                 MD5_Final(mdbuf, &md);
232
233                 /* Send the response. */
234                 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
235                 for (i = 0; i < 16; i++)
236                         buffer_put_char(&msg, mdbuf[i]);
237                 goto send;
238         }
239
240 failure:
241         /* Unknown identity or protocol error.  Send failure. */
242         buffer_put_char(&msg, SSH_AGENT_FAILURE);
243 send:
244         buffer_put_int(&e->output, buffer_len(&msg));
245         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
246         key_free(key);
247         BN_clear_free(challenge);
248         buffer_free(&msg);
249 }
250
251 /* ssh2 only */
252 static void
253 process_sign_request2(SocketEntry *e)
254 {
255         extern int datafellows;
256         Key *key;
257         u_char *blob, *data, *signature = NULL;
258         u_int blen, dlen, slen = 0;
259         int flags;
260         Buffer msg;
261         int ok = -1;
262
263         datafellows = 0;
264
265         blob = buffer_get_string(&e->input, &blen);
266         data = buffer_get_string(&e->input, &dlen);
267
268         flags = buffer_get_int(&e->input);
269         if (flags & SSH_AGENT_OLD_SIGNATURE)
270                 datafellows = SSH_BUG_SIGBLOB;
271
272         key = key_from_blob(blob, blen);
273         if (key != NULL) {
274                 Identity *id = lookup_identity(key, 2);
275                 if (id != NULL)
276                         ok = key_sign(id->key, &signature, &slen, data, dlen);
277         }
278         key_free(key);
279         buffer_init(&msg);
280         if (ok == 0) {
281                 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
282                 buffer_put_string(&msg, signature, slen);
283         } else {
284                 buffer_put_char(&msg, SSH_AGENT_FAILURE);
285         }
286         buffer_put_int(&e->output, buffer_len(&msg));
287         buffer_append(&e->output, buffer_ptr(&msg),
288             buffer_len(&msg));
289         buffer_free(&msg);
290         xfree(data);
291         xfree(blob);
292         if (signature != NULL)
293                 xfree(signature);
294 }
295
296 /* shared */
297 static void
298 process_remove_identity(SocketEntry *e, int version)
299 {
300         Key *key = NULL;
301         u_char *blob;
302         u_int blen;
303         u_int bits;
304         int success = 0;
305
306         switch (version) {
307         case 1:
308                 key = key_new(KEY_RSA1);
309                 bits = buffer_get_int(&e->input);
310                 buffer_get_bignum(&e->input, key->rsa->e);
311                 buffer_get_bignum(&e->input, key->rsa->n);
312
313                 if (bits != key_size(key))
314                         log("Warning: identity keysize mismatch: actual %d, announced %d",
315                             key_size(key), bits);
316                 break;
317         case 2:
318                 blob = buffer_get_string(&e->input, &blen);
319                 key = key_from_blob(blob, blen);
320                 xfree(blob);
321                 break;
322         }
323         if (key != NULL) {
324                 Identity *id = lookup_identity(key, version);
325                 if (id != NULL) {
326                         /*
327                          * We have this key.  Free the old key.  Since we
328                          * don\'t want to leave empty slots in the middle of
329                          * the array, we actually free the key there and move
330                          * all the entries between the empty slot and the end
331                          * of the array.
332                          */
333                         Idtab *tab = idtab_lookup(version);
334                         if (tab->nentries < 1)
335                                 fatal("process_remove_identity: "
336                                     "internal error: tab->nentries %d",
337                                     tab->nentries);
338                         TAILQ_REMOVE(&tab->idlist, id, next);
339                         free_identity(id);
340                         tab->nentries--;
341                         success = 1;
342                 }
343                 key_free(key);
344         }
345         buffer_put_int(&e->output, 1);
346         buffer_put_char(&e->output,
347             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
348 }
349
350 static void
351 process_remove_all_identities(SocketEntry *e, int version)
352 {
353         Idtab *tab = idtab_lookup(version);
354         Identity *id;
355
356         /* Loop over all identities and clear the keys. */
357         for (id = TAILQ_FIRST(&tab->idlist); id;
358             id = TAILQ_FIRST(&tab->idlist)) {
359                 TAILQ_REMOVE(&tab->idlist, id, next);
360                 free_identity(id);
361         }
362
363         /* Mark that there are no identities. */
364         tab->nentries = 0;
365
366         /* Send success. */
367         buffer_put_int(&e->output, 1);
368         buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
369         return;
370 }
371
372 static void
373 process_add_identity(SocketEntry *e, int version)
374 {
375         Key *k = NULL;
376         char *type_name;
377         char *comment;
378         int type, success = 0;
379         Idtab *tab = idtab_lookup(version);
380
381         switch (version) {
382         case 1:
383                 k = key_new_private(KEY_RSA1);
384                 buffer_get_int(&e->input);                      /* ignored */
385                 buffer_get_bignum(&e->input, k->rsa->n);
386                 buffer_get_bignum(&e->input, k->rsa->e);
387                 buffer_get_bignum(&e->input, k->rsa->d);
388                 buffer_get_bignum(&e->input, k->rsa->iqmp);
389
390                 /* SSH and SSL have p and q swapped */
391                 buffer_get_bignum(&e->input, k->rsa->q);        /* p */
392                 buffer_get_bignum(&e->input, k->rsa->p);        /* q */
393
394                 /* Generate additional parameters */
395                 rsa_generate_additional_parameters(k->rsa);
396                 break;
397         case 2:
398                 type_name = buffer_get_string(&e->input, NULL);
399                 type = key_type_from_name(type_name);
400                 xfree(type_name);
401                 switch (type) {
402                 case KEY_DSA:
403                         k = key_new_private(type);
404                         buffer_get_bignum2(&e->input, k->dsa->p);
405                         buffer_get_bignum2(&e->input, k->dsa->q);
406                         buffer_get_bignum2(&e->input, k->dsa->g);
407                         buffer_get_bignum2(&e->input, k->dsa->pub_key);
408                         buffer_get_bignum2(&e->input, k->dsa->priv_key);
409                         break;
410                 case KEY_RSA:
411                         k = key_new_private(type);
412                         buffer_get_bignum2(&e->input, k->rsa->n);
413                         buffer_get_bignum2(&e->input, k->rsa->e);
414                         buffer_get_bignum2(&e->input, k->rsa->d);
415                         buffer_get_bignum2(&e->input, k->rsa->iqmp);
416                         buffer_get_bignum2(&e->input, k->rsa->p);
417                         buffer_get_bignum2(&e->input, k->rsa->q);
418
419                         /* Generate additional parameters */
420                         rsa_generate_additional_parameters(k->rsa);
421                         break;
422                 default:
423                         buffer_clear(&e->input);
424                         goto send;
425                 }
426                 break;
427         }
428         comment = buffer_get_string(&e->input, NULL);
429         if (k == NULL) {
430                 xfree(comment);
431                 goto send;
432         }
433         success = 1;
434         if (lookup_identity(k, version) == NULL) {
435                 Identity *id = xmalloc(sizeof(Identity));
436                 id->key = k;
437                 id->comment = comment;
438                 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
439                 /* Increment the number of identities. */
440                 tab->nentries++;
441         } else {
442                 key_free(k);
443                 xfree(comment);
444         }
445 send:
446         buffer_put_int(&e->output, 1);
447         buffer_put_char(&e->output,
448             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
449 }
450
451
452 #ifdef SMARTCARD
453 static void
454 process_add_smartcard_key (SocketEntry *e)
455 {
456         Idtab *tab;
457         Key *n = NULL, *k = NULL;
458         char *sc_reader_id = NULL;
459         int success = 0;
460
461         sc_reader_id = buffer_get_string(&e->input, NULL);
462         k = sc_get_key(sc_reader_id);
463         xfree(sc_reader_id);
464
465         if (k == NULL) {
466                 error("sc_get_pubkey failed");
467                 goto send;
468         }
469         success = 1;
470
471         tab = idtab_lookup(1);
472         k->type = KEY_RSA1;
473         if (lookup_identity(k, 1) == NULL) {
474                 Identity *id = xmalloc(sizeof(Identity));
475                 n = key_new(KEY_RSA1);
476                 BN_copy(n->rsa->n, k->rsa->n);
477                 BN_copy(n->rsa->e, k->rsa->e);
478                 RSA_set_method(n->rsa, sc_get_engine());
479                 id->key = n;
480                 id->comment = xstrdup("rsa1 smartcard");
481                 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
482                 tab->nentries++;
483         }
484         k->type = KEY_RSA;
485         tab = idtab_lookup(2);
486         if (lookup_identity(k, 2) == NULL) {
487                 Identity *id = xmalloc(sizeof(Identity));
488                 n = key_new(KEY_RSA);
489                 BN_copy(n->rsa->n, k->rsa->n);
490                 BN_copy(n->rsa->e, k->rsa->e);
491                 RSA_set_method(n->rsa, sc_get_engine());
492                 id->key = n;
493                 id->comment = xstrdup("rsa smartcard");
494                 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
495                 tab->nentries++;
496         }
497         key_free(k);
498 send:
499         buffer_put_int(&e->output, 1);
500         buffer_put_char(&e->output,
501             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
502 }
503
504 static void
505 process_remove_smartcard_key(SocketEntry *e)
506 {
507         Key *k = NULL;
508         int success = 0;
509         char *sc_reader_id = NULL;
510
511         sc_reader_id = buffer_get_string(&e->input, NULL);
512         k = sc_get_key(sc_reader_id);
513         xfree(sc_reader_id);
514
515         if (k == NULL) {
516                 error("sc_get_pubkey failed");
517         } else {
518                 Identity *id;
519                 k->type = KEY_RSA1;
520                 id = lookup_identity(k, 1);
521                 if (id != NULL) {
522                         Idtab *tab = idtab_lookup(1);
523                         TAILQ_REMOVE(&tab->idlist, id, next);
524                         free_identity(id);
525                         tab->nentries--;
526                         success = 1;
527                 }
528                 k->type = KEY_RSA;
529                 id = lookup_identity(k, 2);
530                 if (id != NULL) {
531                         Idtab *tab = idtab_lookup(2);
532                         TAILQ_REMOVE(&tab->idlist, id, next);
533                         free_identity(id);
534                         tab->nentries--;
535                         success = 1;
536                 }
537                 key_free(k);
538         }
539
540         buffer_put_int(&e->output, 1);
541         buffer_put_char(&e->output,
542             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
543 }
544 #endif /* SMARTCARD */
545
546 /* dispatch incoming messages */
547
548 static void
549 process_message(SocketEntry *e)
550 {
551         u_int msg_len;
552         u_int type;
553         u_char *cp;
554         if (buffer_len(&e->input) < 5)
555                 return;         /* Incomplete message. */
556         cp = buffer_ptr(&e->input);
557         msg_len = GET_32BIT(cp);
558         if (msg_len > 256 * 1024) {
559                 shutdown(e->fd, SHUT_RDWR);
560                 close(e->fd);
561                 e->type = AUTH_UNUSED;
562                 return;
563         }
564         if (buffer_len(&e->input) < msg_len + 4)
565                 return;
566         buffer_consume(&e->input, 4);
567         type = buffer_get_char(&e->input);
568
569         debug("type %d", type);
570         switch (type) {
571         /* ssh1 */
572         case SSH_AGENTC_RSA_CHALLENGE:
573                 process_authentication_challenge1(e);
574                 break;
575         case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
576                 process_request_identities(e, 1);
577                 break;
578         case SSH_AGENTC_ADD_RSA_IDENTITY:
579                 process_add_identity(e, 1);
580                 break;
581         case SSH_AGENTC_REMOVE_RSA_IDENTITY:
582                 process_remove_identity(e, 1);
583                 break;
584         case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
585                 process_remove_all_identities(e, 1);
586                 break;
587         /* ssh2 */
588         case SSH2_AGENTC_SIGN_REQUEST:
589                 process_sign_request2(e);
590                 break;
591         case SSH2_AGENTC_REQUEST_IDENTITIES:
592                 process_request_identities(e, 2);
593                 break;
594         case SSH2_AGENTC_ADD_IDENTITY:
595                 process_add_identity(e, 2);
596                 break;
597         case SSH2_AGENTC_REMOVE_IDENTITY:
598                 process_remove_identity(e, 2);
599                 break;
600         case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
601                 process_remove_all_identities(e, 2);
602                 break;
603 #ifdef SMARTCARD
604         case SSH_AGENTC_ADD_SMARTCARD_KEY:
605                 process_add_smartcard_key(e);
606                 break;
607         case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
608                 process_remove_smartcard_key(e);
609                 break;
610 #endif /* SMARTCARD */
611         default:
612                 /* Unknown message.  Respond with failure. */
613                 error("Unknown message %d", type);
614                 buffer_clear(&e->input);
615                 buffer_put_int(&e->output, 1);
616                 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
617                 break;
618         }
619 }
620
621 static void
622 new_socket(sock_type type, int fd)
623 {
624         u_int i, old_alloc;
625         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
626                 error("fcntl O_NONBLOCK: %s", strerror(errno));
627
628         if (fd > max_fd)
629                 max_fd = fd;
630
631         for (i = 0; i < sockets_alloc; i++)
632                 if (sockets[i].type == AUTH_UNUSED) {
633                         sockets[i].fd = fd;
634                         sockets[i].type = type;
635                         buffer_init(&sockets[i].input);
636                         buffer_init(&sockets[i].output);
637                         return;
638                 }
639         old_alloc = sockets_alloc;
640         sockets_alloc += 10;
641         if (sockets)
642                 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
643         else
644                 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
645         for (i = old_alloc; i < sockets_alloc; i++)
646                 sockets[i].type = AUTH_UNUSED;
647         sockets[old_alloc].type = type;
648         sockets[old_alloc].fd = fd;
649         buffer_init(&sockets[old_alloc].input);
650         buffer_init(&sockets[old_alloc].output);
651 }
652
653 static int
654 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, int *nallocp)
655 {
656         u_int i, sz;
657         int n = 0;
658
659         for (i = 0; i < sockets_alloc; i++) {
660                 switch (sockets[i].type) {
661                 case AUTH_SOCKET:
662                 case AUTH_CONNECTION:
663                         n = MAX(n, sockets[i].fd);
664                         break;
665                 case AUTH_UNUSED:
666                         break;
667                 default:
668                         fatal("Unknown socket type %d", sockets[i].type);
669                         break;
670                 }
671         }
672
673         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
674         if (*fdrp == NULL || sz > *nallocp) {
675                 if (*fdrp)
676                         xfree(*fdrp);
677                 if (*fdwp)
678                         xfree(*fdwp);
679                 *fdrp = xmalloc(sz);
680                 *fdwp = xmalloc(sz);
681                 *nallocp = sz;
682         }
683         if (n < *fdl)
684                 debug("XXX shrink: %d < %d", n, *fdl);
685         *fdl = n;
686         memset(*fdrp, 0, sz);
687         memset(*fdwp, 0, sz);
688
689         for (i = 0; i < sockets_alloc; i++) {
690                 switch (sockets[i].type) {
691                 case AUTH_SOCKET:
692                 case AUTH_CONNECTION:
693                         FD_SET(sockets[i].fd, *fdrp);
694                         if (buffer_len(&sockets[i].output) > 0)
695                                 FD_SET(sockets[i].fd, *fdwp);
696                         break;
697                 default:
698                         break;
699                 }
700         }
701         return (1);
702 }
703
704 static void
705 after_select(fd_set *readset, fd_set *writeset)
706 {
707         u_int i;
708         int len, sock;
709         socklen_t slen;
710         char buf[1024];
711         struct sockaddr_un sunaddr;
712
713         for (i = 0; i < sockets_alloc; i++)
714                 switch (sockets[i].type) {
715                 case AUTH_UNUSED:
716                         break;
717                 case AUTH_SOCKET:
718                         if (FD_ISSET(sockets[i].fd, readset)) {
719                                 slen = sizeof(sunaddr);
720                                 sock = accept(sockets[i].fd,
721                                     (struct sockaddr *) &sunaddr, &slen);
722                                 if (sock < 0) {
723                                         error("accept from AUTH_SOCKET: %s",
724                                             strerror(errno));
725                                         break;
726                                 }
727                                 new_socket(AUTH_CONNECTION, sock);
728                         }
729                         break;
730                 case AUTH_CONNECTION:
731                         if (buffer_len(&sockets[i].output) > 0 &&
732                             FD_ISSET(sockets[i].fd, writeset)) {
733                                 do {
734                                         len = write(sockets[i].fd,
735                                             buffer_ptr(&sockets[i].output),
736                                             buffer_len(&sockets[i].output));
737                                         if (len == -1 && (errno == EAGAIN ||
738                                             errno == EINTR))
739                                                 continue;
740                                         break;
741                                 } while (1);
742                                 if (len <= 0) {
743                                         shutdown(sockets[i].fd, SHUT_RDWR);
744                                         close(sockets[i].fd);
745                                         sockets[i].type = AUTH_UNUSED;
746                                         buffer_free(&sockets[i].input);
747                                         buffer_free(&sockets[i].output);
748                                         break;
749                                 }
750                                 buffer_consume(&sockets[i].output, len);
751                         }
752                         if (FD_ISSET(sockets[i].fd, readset)) {
753                                 do {
754                                         len = read(sockets[i].fd, buf, sizeof(buf));
755                                         if (len == -1 && (errno == EAGAIN ||
756                                             errno == EINTR))
757                                                 continue;
758                                         break;
759                                 } while (1);
760                                 if (len <= 0) {
761                                         shutdown(sockets[i].fd, SHUT_RDWR);
762                                         close(sockets[i].fd);
763                                         sockets[i].type = AUTH_UNUSED;
764                                         buffer_free(&sockets[i].input);
765                                         buffer_free(&sockets[i].output);
766                                         break;
767                                 }
768                                 buffer_append(&sockets[i].input, buf, len);
769                                 process_message(&sockets[i]);
770                         }
771                         break;
772                 default:
773                         fatal("Unknown type %d", sockets[i].type);
774                 }
775 }
776
777 static void
778 cleanup_socket(void *p)
779 {
780         if (socket_name[0])
781                 unlink(socket_name);
782         if (socket_dir[0])
783                 rmdir(socket_dir);
784 }
785
786 static void
787 cleanup_exit(int i)
788 {
789         cleanup_socket(NULL);
790         exit(i);
791 }
792
793 static void
794 cleanup_handler(int sig)
795 {
796         cleanup_socket(NULL);
797         _exit(2);
798 }
799
800 static void
801 check_parent_exists(int sig)
802 {
803         int save_errno = errno;
804
805         if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
806                 /* printf("Parent has died - Authentication agent exiting.\n"); */
807                 cleanup_handler(sig); /* safe */
808         }
809         signal(SIGALRM, check_parent_exists);
810         alarm(10);
811         errno = save_errno;
812 }
813
814 static void
815 usage(void)
816 {
817         fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
818             __progname);
819         fprintf(stderr, "Options:\n");
820         fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
821         fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
822         fprintf(stderr, "  -k          Kill the current agent.\n");
823         fprintf(stderr, "  -d          Debug mode.\n");
824         exit(1);
825 }
826
827 int
828 main(int ac, char **av)
829 {
830         int sock, c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0, ch, nalloc;
831         struct sockaddr_un sunaddr;
832 #ifdef HAVE_SETRLIMIT
833         struct rlimit rlim;
834 #endif
835 #ifdef HAVE_CYGWIN
836         int prev_mask;
837 #endif
838         pid_t pid;
839         char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
840         extern int optind;
841         fd_set *readsetp = NULL, *writesetp = NULL;
842
843         SSLeay_add_all_algorithms();
844
845         __progname = get_progname(av[0]);
846         init_rng();
847         seed_rng();
848
849 #ifdef __GNU_LIBRARY__
850         while ((ch = getopt(ac, av, "+cdks")) != -1) {
851 #else /* __GNU_LIBRARY__ */
852         while ((ch = getopt(ac, av, "cdks")) != -1) {
853 #endif /* __GNU_LIBRARY__ */
854                 switch (ch) {
855                 case 'c':
856                         if (s_flag)
857                                 usage();
858                         c_flag++;
859                         break;
860                 case 'k':
861                         k_flag++;
862                         break;
863                 case 's':
864                         if (c_flag)
865                                 usage();
866                         s_flag++;
867                         break;
868                 case 'd':
869                         if (d_flag)
870                                 usage();
871                         d_flag++;
872                         break;
873                 default:
874                         usage();
875                 }
876         }
877         ac -= optind;
878         av += optind;
879
880         if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
881                 usage();
882
883         if (ac == 0 && !c_flag && !k_flag && !s_flag && !d_flag) {
884                 shell = getenv("SHELL");
885                 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
886                         c_flag = 1;
887         }
888         if (k_flag) {
889                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
890                 if (pidstr == NULL) {
891                         fprintf(stderr, "%s not set, cannot kill agent\n",
892                             SSH_AGENTPID_ENV_NAME);
893                         exit(1);
894                 }
895                 pid = atoi(pidstr);
896                 if (pid < 1) {
897                         fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
898                             SSH_AGENTPID_ENV_NAME, pidstr);
899                         exit(1);
900                 }
901                 if (kill(pid, SIGTERM) == -1) {
902                         perror("kill");
903                         exit(1);
904                 }
905                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
906                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
907                 printf(format, SSH_AGENTPID_ENV_NAME);
908                 printf("echo Agent pid %d killed;\n", pid);
909                 exit(0);
910         }
911         parent_pid = getpid();
912
913         /* Create private directory for agent socket */
914         strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
915         if (mkdtemp(socket_dir) == NULL) {
916                 perror("mkdtemp: private socket dir");
917                 exit(1);
918         }
919         snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
920             parent_pid);
921
922         /*
923          * Create socket early so it will exist before command gets run from
924          * the parent.
925          */
926         sock = socket(AF_UNIX, SOCK_STREAM, 0);
927         if (sock < 0) {
928                 perror("socket");
929                 cleanup_exit(1);
930         }
931         memset(&sunaddr, 0, sizeof(sunaddr));
932         sunaddr.sun_family = AF_UNIX;
933         strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
934 #ifdef HAVE_CYGWIN
935         prev_mask = umask(0177);
936 #endif
937         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
938                 perror("bind");
939 #ifdef HAVE_CYGWIN
940                 umask(prev_mask);
941 #endif
942                 cleanup_exit(1);
943         }
944 #ifdef HAVE_CYGWIN
945         umask(prev_mask);
946 #endif
947         if (listen(sock, 5) < 0) {
948                 perror("listen");
949                 cleanup_exit(1);
950         }
951
952         /*
953          * Fork, and have the parent execute the command, if any, or present
954          * the socket data.  The child continues as the authentication agent.
955          */
956         if (d_flag) {
957                 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
958                 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
959                 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
960                     SSH_AUTHSOCKET_ENV_NAME);
961                 printf("echo Agent pid %d;\n", parent_pid);
962                 goto skip;
963         }
964         pid = fork();
965         if (pid == -1) {
966                 perror("fork");
967                 cleanup_exit(1);
968         }
969         if (pid != 0) {         /* Parent - execute the given command. */
970                 close(sock);
971                 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
972                 if (ac == 0) {
973                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
974                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
975                             SSH_AUTHSOCKET_ENV_NAME);
976                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
977                             SSH_AGENTPID_ENV_NAME);
978                         printf("echo Agent pid %d;\n", pid);
979                         exit(0);
980                 }
981                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
982                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
983                         perror("setenv");
984                         exit(1);
985                 }
986                 execvp(av[0], av);
987                 perror(av[0]);
988                 exit(1);
989         }
990         /* child */
991         log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
992
993         if (setsid() == -1) {
994                 error("setsid: %s", strerror(errno));
995                 cleanup_exit(1);
996         }
997
998         (void)chdir("/");
999         close(0);
1000         close(1);
1001         close(2);
1002
1003 #ifdef HAVE_SETRLIMIT
1004         /* deny core dumps, since memory contains unencrypted private keys */
1005         rlim.rlim_cur = rlim.rlim_max = 0;
1006         if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1007                 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1008                 cleanup_exit(1);
1009         }
1010 #endif
1011
1012 skip:
1013         fatal_add_cleanup(cleanup_socket, NULL);
1014         new_socket(AUTH_SOCKET, sock);
1015         if (ac > 0) {
1016                 signal(SIGALRM, check_parent_exists);
1017                 alarm(10);
1018         }
1019         idtab_init();
1020         if (!d_flag)
1021                 signal(SIGINT, SIG_IGN);
1022         signal(SIGPIPE, SIG_IGN);
1023         signal(SIGHUP, cleanup_handler);
1024         signal(SIGTERM, cleanup_handler);
1025         nalloc = 0;
1026
1027         while (1) {
1028                 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1029                 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1030                         if (errno == EINTR)
1031                                 continue;
1032                         fatal("select: %s", strerror(errno));
1033                 }
1034                 after_select(readsetp, writesetp);
1035         }
1036         /* NOTREACHED */
1037 }
This page took 0.119424 seconds and 5 git commands to generate.